query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
makeLimitStatment renders statment as below if r.limit>0: LIMIT
func (op *OpQuery) makeLimitStatment() string { if op.limit > 0 { return fmt.Sprintf("LIMIT %d", op.limit) } return "" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Condition) Limit(l int) *Condition {\n\tc.limit = \"LIMIT \" + strconv.Itoa(l)\n\treturn c\n}", "func buildLimit(conditions map[string][]string) int {\n\tres := 20\n\tif len(conditions[\"limit\"]) > 0 {\n\t\tres, _ = strconv.Atoi(conditions[\"limit\"][0])\n\t\tif res > 300 {\n\t\t\tres = 300\n\t\t}\n\t}\n\treturn res\n}", "func buildLimit(limit int64) string {\n\tif limit == 0 {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\" LIMIT %d\", limit)\n}", "func (stmt *statement) Limit(limit interface{}) Statement {\n\tstmt.addPart(posLimit, \"LIMIT ?\", \"\", []interface{}{limit}, \"\")\n\treturn stmt\n}", "func (p *queryPlan) limit() {\n\tif p.stm.IsLimitSet() {\n\t\tstmLimit := p.stm.Limit()\n\t\ttracer.V(2).Trace(p.tracer, func() *tracer.Arguments {\n\t\t\treturn &tracer.Arguments{\n\t\t\t\tMsgs: []string{fmt.Sprintf(\"Limit results to %s\", strconv.Itoa(int(stmLimit)))},\n\t\t\t}\n\t\t})\n\t\tp.tbl.Limit(stmLimit)\n\t}\n}", "func (w *Wrapper) buildLimit() (query string) {\n\tswitch len(w.limit) {\n\tcase 0:\n\t\treturn\n\tcase 1:\n\t\tquery = fmt.Sprintf(\"LIMIT %d \", w.limit[0])\n\tcase 2:\n\t\tquery = fmt.Sprintf(\"LIMIT %d, %d \", w.limit[0], w.limit[1])\n\t}\n\treturn\n}", "func (hdq *HTTPDetectorQuery) Limit(limit int) *HTTPDetectorQuery {\n\thdq.ctx.Limit = &limit\n\treturn hdq\n}", "func (r *Request) Limit(value int64) *Request {\n\treturn r.WithParam(common.ModifierLimit, strconv.FormatInt(value, 10))\n}", "func (o ApplicationStatusOperationStateOperationRetryOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationRetry) *int { return v.Limit }).(pulumi.IntPtrOutput)\n}", "func Limit(limit uint64) func() (uint64, error) {\n\treturn func() (uint64, error) {\n\t\treturn limit, nil\n\t}\n}", "func (o ApplicationOperationRetryOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ApplicationOperationRetry) *int { return v.Limit }).(pulumi.IntPtrOutput)\n}", "func (q *Query) Limit(limit uint64) *Query {\n\tq.limit = strconv.FormatUint(limit, 10)\n\treturn q\n}", "func (osq *OfflineSessionQuery) Limit(limit int) *OfflineSessionQuery {\n\tosq.ctx.Limit = &limit\n\treturn osq\n}", "func (o ApplicationSpecSyncPolicyRetryOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSyncPolicyRetry) *int { return v.Limit }).(pulumi.IntPtrOutput)\n}", "func Limit(limit int) Parameter {\n\treturn func(pa Parameterizable) {\n\t\tpa.SetParameter(\"limit\", limit)\n\t}\n}", "func (o GoogleCloudRetailV2alphaSearchRequestFacetSpecResponseOutput) Limit() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaSearchRequestFacetSpecResponse) int { return v.Limit }).(pulumi.IntOutput)\n}", "func (tdq *TCPDetectorQuery) Limit(limit int) *TCPDetectorQuery {\n\ttdq.ctx.Limit = &limit\n\treturn tdq\n}", "func (q *queryImpl) Limit(limit uint64) Query {\n\tq.limit = strconv.FormatUint(limit, 10)\n\treturn q\n}", "func (rq *RentQuery) Limit(limit int) *RentQuery {\n\trq.limit = &limit\n\treturn rq\n}", "func (tq *TeamQuery) Limit(limit int) *TeamQuery {\n\ttq.ctx.Limit = &limit\n\treturn tq\n}", "func (m *Pump) LimitParam(l int) func() {\n\treturn func() {\n\t\tm.Limit = l\n\t}\n}", "func RateLimit(r *http.Response) int {\n\treturn intResponseHeaderOrNegOne(r, \"X-RateLimit-Limit\")\n}", "func (c *ReconcileCall) Limit(limit int64) *ReconcileCall {\n\tc.urlParams_.Set(\"limit\", fmt.Sprint(limit))\n\treturn c\n}", "func (s SelectStatement) Limit() int {\n\tif s.limit < 1 {\n\t\treturn 0\n\t}\n\treturn s.limit\n}", "func (rrq *ReserveRoomQuery) Limit(limit int) *ReserveRoomQuery {\n\trrq.limit = &limit\n\treturn rrq\n}", "func (o UsagePlanQuotaSettingsOutput) Limit() pulumi.IntOutput {\n\treturn o.ApplyT(func(v UsagePlanQuotaSettings) int { return v.Limit }).(pulumi.IntOutput)\n}", "func limit(n, limit int) (rv int) {\n\trv = n\n\tif rv >= limit {\n\t\trv = limit\n\t}\n\treturn\n}", "func rateLimit(rw http.ResponseWriter, req *http.Request, app *App) bool {\n\tif app.Config.Rate_Limit.Enable {\n\t\tduration := time.Now().Unix() - app.Config.Rate_Limit.Seconds\n\t\tip, err := relevantIpBytes(req.RemoteAddr)\n\t\terrors := map[string]string{\"overall\": \"Rate limit reached.\"}\n\n\t\tif err != nil {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\n\t\tvar count int64\n\t\trow := app.Db.QueryRow(\"select count(*) from comments where ClientIp=? and Created>?\", ip, duration)\n\t\terr = row.Scan(&count)\n\n\t\tif err != nil || count >= app.Config.Rate_Limit.Max_Comments {\n\t\t\trenderErrors(rw, errors, 429)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (mq *MediaQuery) Limit(limit int) *MediaQuery {\n\tmq.ctx.Limit = &limit\n\treturn mq\n}", "func Limit(val int) Argument {\n\treturn func(request *requests.Request) error {\n\t\tif val < 20 || 100 < val {\n\t\t\treturn errors.New(\"limit must be an integer greater or equal to 20 and lesser or equal to 100\")\n\t\t}\n\t\trequest.AddArgument(\"limit\", strconv.Itoa(val))\n\t\treturn nil\n\t}\n}", "func (l *Limiter) limit(w http.ResponseWriter, r *http.Request, h http.Handler) {\n\tavailable := l.bucket.TakeAvailable(1)\n\n\theaders := w.Header()\n\theaders.Set(\"X-RateLimit-Limit\", strconv.Itoa(l.capacity()))\n\theaders.Set(\"X-RateLimit-Remaining\", strconv.Itoa(l.remaining()))\n\n\t// If tokens are not available, reply with error, usually with 429\n\tif available == 0 {\n\t\tl.responder(w, r)\n\t\treturn\n\t}\n\n\t// Otherwise track time and forward the request\n\th.ServeHTTP(w, r)\n}", "func (rlq *RuleLimitQuery) Limit(limit int) *RuleLimitQuery {\n\trlq.limit = &limit\n\treturn rlq\n}", "func (ulq *UserLogQuery) Limit(limit int) *UserLogQuery {\n\tulq.limit = &limit\n\treturn ulq\n}", "func (mvq *ModuleVersionQuery) Limit(limit int) *ModuleVersionQuery {\n\tmvq.limit = &limit\n\treturn mvq\n}", "func (statement *Statement) Limit(limit int, start ...int) *Statement {\n\tstatement.LimitN = &limit\n\tif len(start) > 0 {\n\t\tstatement.Start = start[0]\n\t}\n\treturn statement\n}", "func (self *TStatement) Limit(limit int64, offset ...int64) *TStatement {\r\n\tself.LimitClause = limit\r\n\tif len(offset) > 0 {\r\n\t\tself.OffsetClause = offset[0]\r\n\t}\r\n\treturn self\r\n}", "func (osq *OfflineSessionQuery) Limit(limit int) *OfflineSessionQuery {\n\tosq.limit = &limit\n\treturn osq\n}", "func (o *LogsListRequestPage) GetLimitOk() (*int32, bool) {\n\tif o == nil || o.Limit == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Limit, true\n}", "func (lbq *LatestBlockQuery) Limit(limit int) *LatestBlockQuery {\n\tlbq.limit = &limit\n\treturn lbq\n}", "func WithLimit(l int) Opts {\n\treturn func(r *retryable) {\n\t\tif l > 0 {\n\t\t\tr.limit = l\n\t\t}\n\t}\n}", "func ActLimit(ctx echo.Context, id, action string, maxCount, period int) int {\n\treqTimeSec, err := strconv.ParseInt(ctx.Request().Header.Get(\"REQUEST_TIME\"), 10, 64)\n\treqTime := time.Now()\n\tif err == nil {\n\t\treqTime = time.Unix(reqTimeSec, 0)\n\t}\n\n\treqTimeUnix := int(reqTime.Unix())\n\tttl := reqTimeUnix/period*period + period - reqTimeUnix\n\tkey := fmt.Sprintf(\"mdclubgo_throttle_%s_%s\", action, id)\n\tcurrentCount, err := strconv.Atoi(cache.Get(key, \"0\"))\n\tcurrentCount++\n\tif err != nil || currentCount > maxCount {\n\t\tif err != nil {\n\t\t\tlog.Error(fmt.Errorf(\"act limit get cache: %w\", err).Error())\n\t\t}\n\n\t\treturn 0\n\t}\n\n\terr = cache.Set(key, fmt.Sprintf(\"%d\", currentCount), ttl)\n\tif err != nil {\n\t\tlog.Error(fmt.Errorf(\"act limit set cache: %w\", err).Error())\n\t}\n\n\treturn maxCount - currentCount + 1\n}", "func (self *Query) Limit(l int) *Query {\n\tself.limit = l\n\treturn self\n}", "func (tq *TweetQuery) Limit(limit int) *TweetQuery {\n\ttq.ctx.Limit = &limit\n\treturn tq\n}", "func (lim Limit) Name() string { return \"limit\" }", "func (luq *LastUpdatedQuery) Limit(limit int) *LastUpdatedQuery {\n\tluq.limit = &limit\n\treturn luq\n}", "func (rq *RemedyQuery) Limit(limit int) *RemedyQuery {\n\trq.limit = &limit\n\treturn rq\n}", "func (o *TelemetryDruidScanRequestAllOf) GetLimitOk() (*int32, bool) {\n\tif o == nil || o.Limit == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Limit, true\n}", "func (s Sequence) Limit(l int) Sequence {\n\tif l < 0 {\n\t\ts.limit = 0\n\t} else {\n\t\ts.limit = l\n\t}\n\treturn s\n}", "func (s *Server) Limit(limiter Limiter) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\tif limiter.Allow(info.FullMethod) {\n\t\t\tif s.Proba.TrueOrNot() {\n\t\t\t\ts.Logger.Error(\"Limit exceed\", zap.String(\"method\", info.FullMethod))\n\t\t\t}\n\t\t\t//在触发RPC调用前就return了,所以其他需要捕获错误的中间件需要设置在limiter之前\n\t\t\t//return nil, status.Errorf(codes.ResourceExhausted, \"%s is rejected by ratelimit middleware\", info.FullMethod)\n\t\t\t//for short metrics:atreusns_atreusss_server_counter_total{code=\"ErrRatelimit\",method=\"/proto.GreeterService/SayHello\",type=\"unary\"} 2\n\t\t\treturn nil, status.Error(codes.ResourceExhausted, pyerrors.RatelimiterServiceReject)\n\t\t}\n\n\t\treturn handler(ctx, req)\n\t}\n}", "func (s *SearchForAssets) Limit(lim uint64) *SearchForAssets {\n\ts.p.Limit = lim\n\treturn s\n}", "func (pgq *PlayGroupQuery) Limit(limit int) *PlayGroupQuery {\n\tpgq.limit = &limit\n\treturn pgq\n}", "func (o GoogleCloudRetailV2alphaSearchRequestFacetSpecOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v GoogleCloudRetailV2alphaSearchRequestFacetSpec) *int { return v.Limit }).(pulumi.IntPtrOutput)\n}", "func (eq *EntryQuery) Limit(limit int) *EntryQuery {\n\teq.ctx.Limit = &limit\n\treturn eq\n}", "func (nimq *NetInterfaceModeQuery) Limit(limit int) *NetInterfaceModeQuery {\n\tnimq.limit = &limit\n\treturn nimq\n}", "func (o ApplicationStatusOperationStateOperationRetryPtrOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationStatusOperationStateOperationRetry) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Limit\n\t}).(pulumi.IntPtrOutput)\n}", "func Limit(limit int) QueryMod {\n\treturn func(q *queries.Query) {\n\t\tqueries.SetLimit(q, limit)\n\t}\n}", "func (deq *DentalExpenseQuery) Limit(limit int) *DentalExpenseQuery {\n\tdeq.limit = &limit\n\treturn deq\n}", "func TryAddExtraLimit(ctx sessionctx.Context, node ast.StmtNode) ast.StmtNode {\n\tif ctx.GetSessionVars().SelectLimit == math.MaxUint64 || ctx.GetSessionVars().InRestrictedSQL {\n\t\treturn node\n\t}\n\tif explain, ok := node.(*ast.ExplainStmt); ok {\n\t\texplain.Stmt = TryAddExtraLimit(ctx, explain.Stmt)\n\t\treturn explain\n\t} else if sel, ok := node.(*ast.SelectStmt); ok {\n\t\tif sel.Limit != nil || sel.SelectIntoOpt != nil {\n\t\t\treturn node\n\t\t}\n\t\tnewSel := *sel\n\t\tnewSel.Limit = &ast.Limit{\n\t\t\tCount: ast.NewValueExpr(ctx.GetSessionVars().SelectLimit, \"\", \"\"),\n\t\t}\n\t\treturn &newSel\n\t} else if show, ok := node.(*ast.ShowStmt); ok {\n\t\t// Only when Limit is nil, for Show stmt Limit should always nil when be here,\n\t\t// and the show STMT's behavior should consist with MySQL does.\n\t\tif show.Limit != nil || !show.NeedLimitRSRow() {\n\t\t\treturn node\n\t\t}\n\t\tnewShow := *show\n\t\tnewShow.Limit = &ast.Limit{\n\t\t\tCount: ast.NewValueExpr(ctx.GetSessionVars().SelectLimit, \"\", \"\"),\n\t\t}\n\t\treturn &newShow\n\t} else if setOprStmt, ok := node.(*ast.SetOprStmt); ok {\n\t\tif setOprStmt.Limit != nil {\n\t\t\treturn node\n\t\t}\n\t\tnewSetOpr := *setOprStmt\n\t\tnewSetOpr.Limit = &ast.Limit{\n\t\t\tCount: ast.NewValueExpr(ctx.GetSessionVars().SelectLimit, \"\", \"\"),\n\t\t}\n\t\treturn &newSetOpr\n\t}\n\treturn node\n}", "func (wq *WidgetQuery) Limit(limit int) *WidgetQuery {\n\twq.limit = &limit\n\treturn wq\n}", "func (gq *GoodsQuery) Limit(limit int) *GoodsQuery {\n\tgq.limit = &limit\n\treturn gq\n}", "func (node *Limit) Format(buf *TrackedBuffer) {\n\tif node == nil {\n\t\treturn\n\t}\n\tbuf.astPrintf(node, \" limit \")\n\tif node.Offset != nil {\n\t\tbuf.astPrintf(node, \"%v, \", node.Offset)\n\t}\n\tbuf.astPrintf(node, \"%v\", node.Rowcount)\n}", "func (o ApplicationOperationRetryPtrOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationOperationRetry) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Limit\n\t}).(pulumi.IntPtrOutput)\n}", "func (omq *OutcomeMeasureQuery) Limit(limit int) *OutcomeMeasureQuery {\n\tomq.limit = &limit\n\treturn omq\n}", "func getLimit(r *http.Request, defaultSize, maxSize uint64) (uint64, error) {\n\tlimit, err := hchi.GetStringFromURL(r, actions.ParamLimit)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"loading param limit from URL\")\n\t}\n\tif limit == \"\" {\n\t\treturn defaultSize, nil\n\t}\n\n\tlimitInt64, err := strconv.ParseInt(limit, 10, 64)\n\tif err != nil {\n\t\treturn 0, problem.MakeInvalidFieldProblem(actions.ParamLimit, errors.New(\"invalid int64 value\"))\n\t}\n\tif limitInt64 <= 0 {\n\t\treturn 0, problem.MakeInvalidFieldProblem(actions.ParamLimit, errors.Errorf(\"limit %d is a non-positive number: \", limitInt64))\n\t}\n\tif limitInt64 > int64(maxSize) {\n\t\treturn 0, problem.MakeInvalidFieldProblem(actions.ParamLimit, errors.Errorf(\"limit %d is greater than limit max of %d\", limitInt64, maxSize))\n\t}\n\n\treturn uint64(limitInt64), nil\n}", "func LimitFilter(limit int) Filter {\n\treturn Param(\"limit\", strconv.Itoa(limit))\n}", "func (wq *WorkflowQuery) Limit(limit int) *WorkflowQuery {\n\twq.limit = &limit\n\treturn wq\n}", "func (o *GetModerationRulesParams) SetLimit(limit *int64) {\n\to.Limit = limit\n}", "func (hq *HarborQuery) Limit(limit int) *HarborQuery {\n\thq.limit = &limit\n\treturn hq\n}", "func Limit(value uint) Strategy {\n\treturn func(_ Breaker, attempt uint, _ error) bool {\n\t\treturn attempt < value\n\t}\n}", "func (ub *UpdateBuilder) Limit(limit int) *UpdateBuilder {\n\tub.limit = limit\n\tub.marker = updateMarkerAfterLimit\n\treturn ub\n}", "func (PullOption) Limit(val int) PullOption {\n\treturn func(settings *PullSettings) {\n\t\tsettings.Limit = val\n\t}\n}", "func (liq *LineItemQuery) Limit(limit int) *LineItemQuery {\n\tliq.limit = &limit\n\treturn liq\n}", "func (r UserApiGetUserCommentsRequest) Limit(limit int32) UserApiGetUserCommentsRequest {\n\tr.limit = &limit\n\treturn r\n}", "func (m *Pump) LimitParam(l Limit) func() {\n\treturn func() {\n\t\tm.Limit = l\n\t}\n}", "func (sq *ServerQuery) Limit(limit int) *ServerQuery {\n\tsq.limit = &limit\n\treturn sq\n}", "func (evsq *ExValueScanQuery) Limit(limit int) *ExValueScanQuery {\n\tevsq.ctx.Limit = &limit\n\treturn evsq\n}", "func (o QuotaLimitResponseOutput) MaxLimit() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.MaxLimit }).(pulumi.StringOutput)\n}", "func (irq *InstanceRuntimeQuery) Limit(limit int) *InstanceRuntimeQuery {\n\tirq.limit = &limit\n\treturn irq\n}", "func (ouq *OrgUnitQuery) Limit(limit int) *OrgUnitQuery {\n\touq.limit = &limit\n\treturn ouq\n}", "func (r *Request) Limit(value int64) *Request {\n\tr.UnderlyingRequest.Limit(value)\n\treturn r\n}", "func (o ApplicationSpecSyncPolicyRetryPtrOutput) Limit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationSpecSyncPolicyRetry) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Limit\n\t}).(pulumi.IntPtrOutput)\n}", "func (esq *EventSeverityQuery) Limit(limit int) *EventSeverityQuery {\n\tesq.limit = &limit\n\treturn esq\n}", "func (w *Wrapper) Limit(from int, count ...int) *Wrapper {\n\tif len(count) == 0 {\n\t\tw.limit = []int{from}\n\t} else {\n\t\tw.limit = []int{from, count[0]}\n\t}\n\treturn w\n}", "func (lm *SimpleManager) Limit(l chan int) <-chan bool {\n\tdone := make(chan bool, 1)\n\tready := make(chan struct{})\n\tlm.newLimit <- &limit{\n\t\tlim: l,\n\t\tdone: done,\n\t\tready: ready,\n\t}\n\t<-ready\n\treturn done\n}", "func newLimit(plan logicalPlan) *limit {\n\treturn &limit{\n\t\tlogicalPlanCommon: newBuilderCommon(plan),\n\t\telimit: &engine.Limit{},\n\t}\n}", "func (rdq *ResultsDefinitionQuery) Limit(limit int) *ResultsDefinitionQuery {\n\trdq.limit = &limit\n\treturn rdq\n}", "func (ttrq *TradeTimeRangeQuery) Limit(limit int) *TradeTimeRangeQuery {\n\tttrq.limit = &limit\n\treturn ttrq\n}", "func (db *DB) Limit(limit int) (tx *DB) {\n\ttx = db.getInstance()\n\ttx.Statement.AddClause(clause.Limit{Limit: limit})\n\treturn\n}", "func (o *GetRefPlantsParams) bindLimit(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\n\t// Required: false\n\t// AllowEmptyValue: true\n\n\tif raw == \"\" { // empty values pass all other validations\n\t\t// Default values have been previously initialized by NewGetRefPlantsParams()\n\t\treturn nil\n\t}\n\n\tvalue, err := swag.ConvertInt64(raw)\n\tif err != nil {\n\t\treturn errors.InvalidType(\"limit\", \"query\", \"int64\", raw)\n\t}\n\to.Limit = value\n\n\tif err := o.validateLimit(formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r ApiGetPlansRequest) Limit(limit int32) ApiGetPlansRequest {\n\tr.limit = &limit\n\treturn r\n}", "func (q *Query) Limit(limit int) *Query {\n\tif limit < 1 {\n\t\tlogrus.Warn(\"illegal limit: \", limit)\n\t\treturn q\n\t}\n\tq.limit = limit\n\treturn q\n}", "func (o *GetNodeChildrenParams) bindLimit(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\n\t// Required: false\n\t// AllowEmptyValue: false\n\n\tif raw == \"\" { // empty values pass all other validations\n\t\t// Default values have been previously initialized by NewGetNodeChildrenParams()\n\t\treturn nil\n\t}\n\n\tvalue, err := swag.ConvertInt64(raw)\n\tif err != nil {\n\t\treturn errors.InvalidType(\"limit\", \"query\", \"int64\", raw)\n\t}\n\to.Limit = &value\n\n\tif err := o.validateLimit(formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (lm *SimpleManager) limit(l Limiter) {\n\tlm.m[l] = make(chan int)\n\tdone := l.Limit(lm.m[l])\n\tgo func() {\n\t\t//If `true` passed on channel, limiter is closed\n\t\tif <-done {\n\t\t\tlm.Unmanage(l)\n\t\t}\n\t}()\n}", "func parseLimit(req *http.Request, limit *int) error {\n\t*limit = 0\n\tif arg := req.URL.Query().Get(\"limit\"); arg != \"\" {\n\t\ti, err := strconv.Atoi(arg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*limit = i\n\t}\n\treturn nil\n}", "func (o *GetPostListParams) bindLimit(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\n\t// Required: false\n\t// AllowEmptyValue: false\n\n\tif raw == \"\" { // empty values pass all other validations\n\t\treturn nil\n\t}\n\n\tvalue, err := swag.ConvertInt64(raw)\n\tif err != nil {\n\t\treturn errors.InvalidType(\"limit\", \"query\", \"int64\", raw)\n\t}\n\to.Limit = &value\n\n\treturn nil\n}", "func resultsLimit(r *http.Request) int {\n\tvalues := r.URL.Query()[\"limit\"]\n\tif len(values) == 0 {\n\t\treturn 20\n\t}\n\n\tlimitStr := values[0]\n\tif limitStr == \"\" {\n\t\treturn 20\n\t}\n\n\tlimit, err := strconv.Atoi(limitStr)\n\tif err != nil {\n\t\tLogWithRequestID(r, fmt.Sprintf(\"Bad limit '%s': %+v\", limitStr, err))\n\t\treturn 20\n\t}\n\n\t// Cap limit at a reasonable number for the DB.\n\tif limit > 100 {\n\t\treturn 100\n\t}\n\n\treturn limit\n}", "func (oupq *OrgUnitPositionQuery) Limit(limit int) *OrgUnitPositionQuery {\n\toupq.limit = &limit\n\treturn oupq\n}", "func (uq *UserQuery) Limit(limit int) *UserQuery {\n\tuq.limit = &limit\n\treturn uq\n}", "func Limit(limit int) Option {\n\treturn func(opts *Options) error {\n\t\topts.Limit = limit\n\t\treturn nil\n\t}\n}", "func (v *vertex) Limit(maxElements int) interfaces.Vertex {\n\treturn v.Add(NewSimpleQB(\".limit(%d)\", maxElements))\n}" ]
[ "0.6710295", "0.6347146", "0.6295109", "0.6226007", "0.62210786", "0.6170679", "0.6131475", "0.6119971", "0.6116671", "0.6077754", "0.6076456", "0.6064844", "0.6052961", "0.6028746", "0.6022812", "0.5987972", "0.5964589", "0.59535724", "0.5941685", "0.58898014", "0.5885067", "0.5883937", "0.588377", "0.58800244", "0.58717346", "0.5857695", "0.5847282", "0.58468986", "0.58339334", "0.58257353", "0.58128065", "0.5802207", "0.5799996", "0.5798799", "0.5795837", "0.5791677", "0.5780716", "0.57750833", "0.5772957", "0.57624555", "0.5759631", "0.5751555", "0.5745459", "0.5740573", "0.57320446", "0.571878", "0.5714362", "0.5699625", "0.568893", "0.568876", "0.56851614", "0.56850755", "0.5682602", "0.56789124", "0.5670263", "0.5655529", "0.56526905", "0.5645735", "0.56447077", "0.5638725", "0.56371987", "0.5635588", "0.5632736", "0.5623835", "0.5619437", "0.5615035", "0.5614409", "0.5611518", "0.55994874", "0.5590723", "0.5590575", "0.55896944", "0.5585422", "0.55850303", "0.55844665", "0.558059", "0.5571631", "0.5569877", "0.55672675", "0.55587137", "0.55582386", "0.5553538", "0.5546532", "0.55440277", "0.5542341", "0.55374366", "0.5526205", "0.5522429", "0.5520036", "0.55157053", "0.5509957", "0.55096096", "0.55094737", "0.5506035", "0.5505355", "0.5493672", "0.5480985", "0.54803336", "0.5479981", "0.54744256" ]
0.7328498
0
NewOpQuery returns a OpQuery instance with given sobjectName.
func NewOpQuery(sobjectName string) *OpQuery { return &OpQuery{ sobjectName: sobjectName, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewOplogQuery(dataset map[string]interface{}) (Query, error) {\n\tnamespace, ok := dataset[\"ns\"].(string)\n\tif namespace == \"\" || !ok {\n\t\treturn nil, errors.New(\"namespace not given\")\n\t}\n\n\tp := strings.Index(namespace, \".\")\n\tif p == -1 {\n\t\treturn nil, errors.New(\"Invalid namespace given, must contain dot\")\n\t}\n\n\ttriggerDB := namespace[:p]\n\ttriggerCollection := namespace[p+1:]\n\n\treturn oplogQuery{dataset: dataset, db: triggerDB, collection: triggerCollection}, nil\n}", "func (op *OpQuery) From(sobjectName string) *OpQuery {\n\top.sobjectName = sobjectName\n\treturn op\n}", "func New(userName string) Query {\n\treturn Query{\n\t\tuserName: userName,\n\t}\n}", "func NewQuery(s *Storage) *Query {\n\tq := new(Query)\n\tq.s = s\n\tq.order = \"ASC\"\n\tq.eq = make(map[string]interface{})\n\tq.limit = [2]int{-1, -1}\n\treturn q\n}", "func NewQuery(svc productivity.Service) Query {\n\treturn Query{svc: svc}\n}", "func New() Query {\n\treturn Query{}\n}", "func NewQuery(store database.Store) Query {\n\treturn Query{store: store}\n}", "func NewQuery(query *gocql.Query) QueryInterface {\n\treturn &Query{\n\t\tquery,\n\t}\n}", "func (c *Client) NewQuery(kind string) storage.Query {\n\treturn &Query{query: datastore.NewQuery(kind)}\n}", "func NewQuery(ql string, currentTime time.Time) (*influxql.Query, error) {\n\treturn newQuery(ql, currentTime)\n}", "func (c *Client) NewQuery(rq string) (model.AdminQuery, error) {\n\tctx := context.Background()\n\treq := graphql.NewRequest(rq)\n\treq.Header.Add(\"Authorization\", c.bearer)\n\n\tvar res model.AdminQuery\n\tif err := c.graphql.Run(ctx, req, &res); err != nil {\n\t\treturn model.AdminQuery{}, err\n\t}\n\treturn res, nil\n}", "func (b *QueryBuilder) NewQuery(collection string) *Query {\n\treturn NewQuery(collection, b.CensusClient)\n}", "func (h *datastoreHandler) NewQuery(kind string) PersistenceQuery {\n\treturn NewQuery(kind)\n}", "func New() Query {\n\tq := make(query)\n\tq.init()\n\treturn q\n}", "func NewQuery() *Query {\n\treturn &Query{targets: make([]string, 0)}\n}", "func NewQuery(m map[string]string) Query {\n\treturn Query(m)\n}", "func (q queryManager) NewQuery(sql string, pubKey []byte) (uint, []byte, []byte, *structures.Transaction, error) {\n\treturn q.processQuery(sql, pubKey, true)\n}", "func New(s string) (*PegQuery, error) {\n\tp := &QueryParser{\n\t\tBuffer: s,\n\t}\n\tp.Expression.explainer = func(format string, args ...interface{}) {\n\t\tfmt.Printf(format, args...)\n\t}\n\tp.Init()\n\terr := p.Parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.Execute()\n\treturn &PegQuery{str: s, parser: p}, nil\n}", "func NewQuery(table string, alias string) *sqlData {\n\treturn &sqlData{table: table, alias: alias, columns: make([]string, 0)}\n}", "func NewQuery(mods ...qm.QueryMod) *queries.Query {\n\tq := &queries.Query{}\n\tqueries.SetDialect(q, &dialect)\n\tqm.Apply(q, mods...)\n\n\treturn q\n}", "func NewQuery(modelInterface ModelInterface) *Query {\n\treturn &Query{\n\t\tmodelInterface: modelInterface,\n\t\tsqlBuilder: nil,\n\t}\n}", "func (p *Oracle) ObjectQuery() string {\n\treturn `SELECT * FROM %s WHERE 1=0`\n}", "func NewQuery(opts ...QueryOption) Query {\n\t// default options\n\tqopts := QueryOptions{\n\t\tService: \"*\",\n\t\tGateway: \"*\",\n\t\tNetwork: \"*\",\n\t}\n\n\tfor _, o := range opts {\n\t\to(&qopts)\n\t}\n\n\treturn &query{\n\t\topts: qopts,\n\t}\n}", "func NewQuery(name string, t time.Time) *Query {\n\ttloc := t.Local()\n\n\tif tloc.Hour() < thresholdHour {\n\t\ttloc = tloc.Add(-24 * time.Hour)\n\t}\n\n\treturn &Query{\n\t\tname: name,\n\t\tday: date(tloc),\n\t\tsheetName: monthlySheetName(tloc),\n\t}\n}", "func NewQuery() Query {\n\tq := &BasicQuery{\n\t\tConds: &BasicConds{},\n\t\tSorts: &BasicSorts{},\n\t}\n\treturn q\n}", "func NewQuery(query string) (*Query, error) {\n\tif query == \"\" {\n\t\treturn nil, errors.New(\"USQL query should not be empty\")\n\t}\n\treturn &Query{\n\t\tquery: query,\n\t}, nil\n}", "func NewQuery(transport *transport.Transport) *Query {\n\treturn &Query{\n\t\ttransport: transport,\n\t}\n}", "func createQuery() *graphql.Object {\n\treturn graphql.NewObject(graphql.ObjectConfig{\n\t\tName: \"Query\",\n\t\tFields: graphql.Fields{\n\t\t\t\"actors\": loadActorsField(),\n\t\t\t\"movie\": loadMovieField(),\n\t\t},\n\t\tDescription: \"A movie query with information of most famous movies and actors\",\n\t})\n}", "func NewQuery(svcs QueryServices) Query {\n\treturn Query{\n\t\tTransit: transgql.NewQuery(svcs.Transit),\n\t}\n}", "func NewQuery(words []string) {\n\n\tvar animal Animal\n\n\tname := strings.ToLower(words[0])\n\tact := strings.ToLower(words[1])\n\n\tanimalType, ok := types[name]\n\tif !ok {\n\t\tfmt.Printf(\"Could not find an animal with Name %s\\n\", words[0])\n\t\treturn\n\t}\n\n\t// If types map has the name then it MUST be present in one of 3 maps.\n\t// cows or birds or snakes.\n\tswitch animalType {\n\t\tcase \"cow\": animal, _ = cows[name]\n\t\tcase \"bird\": animal, _ = birds[name]\n\t\tcase \"snake\": animal, _ = snakes[name]\n\t}\n\n\tProcessQuery(animal, act)\n}", "func NewRegQuery(sess *session.Session) RegQuery {\n\treturn RegQuery{\n\t\tregions: sets.Empty(),\n\t\tsess: sess,\n\t}\n}", "func New(db *gorm.DB) *Query {\n\tq := &Query{\n\t\tdb: db,\n\t}\n\n\treturn q\n}", "func NewViewQuery(dbcon DBConn, tablename string, model interface{}) ViewQuery {\n\treturn ViewQuery{\n\t\tNewQuery(dbcon, tablename, model),\n\t}\n}", "func NewQuery(qt types.QueryType, c runner.Client) *Query {\n\treturn &Query{\n\t\tqueryType: qt,\n\t\trunner: runner.New(c),\n\t\targs: make([]interface{}, 0),\n\t}\n}", "func New(context context.Context, database *gorm.DB, dbName string) *PSQL {\n\treturn &PSQL{database, dbName, context}\n}", "func (sq *ShopQuery) Clone() *ShopQuery {\n\treturn &ShopQuery{\n\t\tconfig: sq.config,\n\t\tlimit: sq.limit,\n\t\toffset: sq.offset,\n\t\torder: append([]Order{}, sq.order...),\n\t\tunique: append([]string{}, sq.unique...),\n\t\tpredicates: append([]predicate.Shop{}, sq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: sq.sql.Clone(),\n\t}\n}", "func NewQuery(file *File, fields *Fields, q *annotations.Query) *Query {\n\treturn AsQuery(generator.NewQuery(file.Generator(), fields.Generator(), q))\n}", "func NewQuery(req *jsonrpc.RPCRequest, walletID string) (*Query, error) {\n\tif strings.TrimSpace(req.Method) == \"\" {\n\t\treturn nil, errors.Err(\"no method in request\")\n\t}\n\n\tq := &Query{Request: req, WalletID: walletID}\n\n\tif !methodInList(q.Method(), relaxedMethods) && !methodInList(q.Method(), walletSpecificMethods) {\n\t\treturn nil, rpcerrors.NewMethodNotAllowedError(errors.Err(\"forbidden method\"))\n\t}\n\n\tif q.ParamsAsMap() != nil {\n\t\tfor _, p := range forbiddenParams {\n\t\t\tif _, ok := q.ParamsAsMap()[p]; ok {\n\t\t\t\treturn nil, rpcerrors.NewInvalidParamsError(fmt.Errorf(\"forbidden parameter supplied: %v\", p))\n\t\t\t}\n\t\t}\n\t}\n\n\tif MethodAcceptsWallet(q.Method()) {\n\t\tif q.IsAuthenticated() {\n\t\t\tif p := q.ParamsAsMap(); p != nil {\n\t\t\t\tp[ParamWalletID] = q.WalletID\n\t\t\t\tq.Request.Params = p\n\t\t\t} else {\n\t\t\t\tq.Request.Params = map[string]interface{}{ParamWalletID: q.WalletID}\n\t\t\t}\n\t\t} else if MethodRequiresWallet(q.Method(), q.Params()) {\n\t\t\treturn nil, rpcerrors.NewAuthRequiredError()\n\t\t}\n\t}\n\n\treturn q, nil\n}", "func New(typ uint8, path string, start int64, end int64) (*Query, error) {\n\trang := queryRange{\n\t\tStart: start,\n\t\tEnd: end,\n\t}\n\tquery := &Query{\n\t\tdbPath: path,\n\t\trang: rang,\n\t\ttyp: typ,\n\t}\n\terr := query.Validate()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"validation error: %s\", err)\n\t}\n\treturn query, nil\n}", "func New(addr string) (*Query, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\tdefer cancel()\n\n\tconn, err := grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect with the jaeger-query service: %w\", err)\n\t}\n\n\treturn &Query{\n\t\tclient: api_v2.NewQueryServiceClient(conn),\n\t\tconn: conn,\n\t}, nil\n}", "func (gq *GoodsQuery) Clone() *GoodsQuery {\n\tif gq == nil {\n\t\treturn nil\n\t}\n\treturn &GoodsQuery{\n\t\tconfig: gq.config,\n\t\tlimit: gq.limit,\n\t\toffset: gq.offset,\n\t\torder: append([]OrderFunc{}, gq.order...),\n\t\tunique: append([]string{}, gq.unique...),\n\t\tpredicates: append([]predicate.Goods{}, gq.predicates...),\n\t\t// clone intermediate query.\n\t\tgremlin: gq.gremlin.Clone(),\n\t\tpath: gq.path,\n\t}\n}", "func New() *QueryProcessor {\n\treturn &QueryProcessor{}\n}", "func NewPetQuery() *PetQuery {\n\treturn &PetQuery{\n\t\tBaseQuery: kallax.NewBaseQuery(Schema.Pet.BaseSchema),\n\t}\n}", "func (ng *Engine) NewInstantQuery(qs string, ts model.Time) (Query, error) {\n\texpr, err := ParseExpr(qs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqry := ng.newQuery(expr, ts, ts, 0)\n\tqry.q = qs\n\n\treturn qry, nil\n}", "func (fdq *FurnitureDetailQuery) Clone() *FurnitureDetailQuery {\n\treturn &FurnitureDetailQuery{\n\t\tconfig: fdq.config,\n\t\tlimit: fdq.limit,\n\t\toffset: fdq.offset,\n\t\torder: append([]OrderFunc{}, fdq.order...),\n\t\tunique: append([]string{}, fdq.unique...),\n\t\tpredicates: append([]predicate.FurnitureDetail{}, fdq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: fdq.sql.Clone(),\n\t\tpath: fdq.path,\n\t}\n}", "func (b *Backend) newOp() *Op {\n\tsession := b.session.Copy()\n\treturn &Op{\n\t\tsession: session,\n\t\ttasksCollection: session.DB(\"\").C(\"tasks\"),\n\t\tgroupMetasCollection: session.DB(\"\").C(\"group_metas\"),\n\t}\n}", "func (deq *DentalExpenseQuery) Clone() *DentalExpenseQuery {\n\treturn &DentalExpenseQuery{\n\t\tconfig: deq.config,\n\t\tlimit: deq.limit,\n\t\toffset: deq.offset,\n\t\torder: append([]OrderFunc{}, deq.order...),\n\t\tunique: append([]string{}, deq.unique...),\n\t\tpredicates: append([]predicate.DentalExpense{}, deq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: deq.sql.Clone(),\n\t\tpath: deq.path,\n\t}\n}", "func NewQueryable(distributor Querier, chunkStore ChunkStore) Queryable {\n\treturn Queryable{\n\t\tQ: MergeQuerier{\n\t\t\tQueriers: []Querier{\n\t\t\t\tdistributor,\n\t\t\t\t&ChunkQuerier{\n\t\t\t\t\tStore: chunkStore,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func newQuery(t reflect.Type, itself goshua.Variable, readerValues map[string]interface{}) goshua.Query {\n\tq := query{\n\t\tstructType: t,\n\t\titself: itself,\n\t\tmatchers: make(map[string]interface{}),\n\t}\n\tfor name, val := range readerValues {\n\t\tif method, ok := t.MethodByName(name); ok {\n\t\t\tq.matchers[matchersKey(method)] = val\n\t\t} else {\n\t\t\t/* Show available methods\n\t\t\tfor i := 0; i < t.NumMethod(); i++ {\n\t\t\t\tm := t.Method(i)\n\t\t\t\tlog.Printf(\"%d: method %s.%s\", i, m.PkgPath, m.Name)\n\t\t\t}\n\t\t\t*/\n\t\t\tpanic(fmt.Sprintf(\"No method %s for type %v\", name, t))\n\t\t}\n\t}\n\treturn &q\n}", "func (vq *VehicleQuery) Clone() *VehicleQuery {\n\tif vq == nil {\n\t\treturn nil\n\t}\n\treturn &VehicleQuery{\n\t\tconfig: vq.config,\n\t\tlimit: vq.limit,\n\t\toffset: vq.offset,\n\t\torder: append([]OrderFunc{}, vq.order...),\n\t\tpredicates: append([]predicate.Vehicle{}, vq.predicates...),\n\t\twithMetadata: vq.withMetadata.Clone(),\n\t\twithRegistrations: vq.withRegistrations.Clone(),\n\t\twithMake: vq.withMake.Clone(),\n\t\twithModel: vq.withModel.Clone(),\n\t\twithMajorColor: vq.withMajorColor.Clone(),\n\t\twithMinorColor: vq.withMinorColor.Clone(),\n\t\twithClass: vq.withClass.Clone(),\n\t\t// clone intermediate query.\n\t\tsql: vq.sql.Clone(),\n\t\tpath: vq.path,\n\t}\n}", "func New(db *mgo.Database, coll string, query interface{}) MinQuery {\n\treturn NewWithHint(db, coll, query, nil)\n}", "func NewQueryBuilder(translator *Translator, metricName string) QueryBuilder {\n\treturn QueryBuilder{\n\t\ttranslator: translator,\n\t\tmetricName: metricName,\n\t}\n}", "func (s *Schema) Query() *Object {\n\treturn s.Object(\"Query\", query{})\n}", "func (roq *RestaurantOwnerQuery) Clone() *RestaurantOwnerQuery {\n\treturn &RestaurantOwnerQuery{\n\t\tconfig: roq.config,\n\t\tlimit: roq.limit,\n\t\toffset: roq.offset,\n\t\torder: append([]OrderFunc{}, roq.order...),\n\t\tunique: append([]string{}, roq.unique...),\n\t\tpredicates: append([]predicate.RestaurantOwner{}, roq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: roq.sql.Clone(),\n\t\tpath: roq.path,\n\t}\n}", "func (c *OperativerecordClient) Query() *OperativerecordQuery {\n\treturn &OperativerecordQuery{config: c.config}\n}", "func NewFromRawQuery(rawQuery string) *QueryString {\n\tqs := new(QueryString)\n\tqs.fields = make(map[string]string)\n\n\tfor {\n\t\ti := strings.IndexRune(rawQuery, '=')\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t\tname := rawQuery[:i]\n\t\trawQuery = rawQuery[i+1:]\n\n\t\ti = strings.IndexFunc(rawQuery, charClassDetector(1, 1))\n\t\tvar value string\n\t\tif i == -1 {\n\t\t\tvalue = rawQuery\n\t\t} else {\n\t\t\tvalue = rawQuery[:i]\n\t\t\trawQuery = rawQuery[i+1:]\n\t\t}\n\n\t\tqs.fields[name] = value\n\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn qs\n}", "func (epdq *EquipmentPortDefinitionQuery) Clone() *EquipmentPortDefinitionQuery {\n\treturn &EquipmentPortDefinitionQuery{\n\t\tconfig: epdq.config,\n\t\tlimit: epdq.limit,\n\t\toffset: epdq.offset,\n\t\torder: append([]Order{}, epdq.order...),\n\t\tunique: append([]string{}, epdq.unique...),\n\t\tpredicates: append([]predicate.EquipmentPortDefinition{}, epdq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: epdq.sql.Clone(),\n\t}\n}", "func NewCustomQueries(values map[string]string) *CustomQueries {\n\treturn &CustomQueries{\n\t\tvalues: values,\n\t}\n}", "func NewScanOp(obj DomainObject) *ScanOp {\n\treturn &ScanOp{object: obj}\n}", "func NewQueryBuilder(raw *tg.Client) *QueryBuilder {\n\treturn &QueryBuilder{raw: raw}\n}", "func (mvq *ModuleVersionQuery) Clone() *ModuleVersionQuery {\n\treturn &ModuleVersionQuery{\n\t\tconfig: mvq.config,\n\t\tlimit: mvq.limit,\n\t\toffset: mvq.offset,\n\t\torder: append([]Order{}, mvq.order...),\n\t\tunique: append([]string{}, mvq.unique...),\n\t\tpredicates: append([]predicate.ModuleVersion{}, mvq.predicates...),\n\t\t// clone intermediate queries.\n\t\tsql: mvq.sql.Clone(),\n\t}\n}", "func NewQueryx(q QueryI, names []string) QueryxI {\n\treturn &Queryx{\n\t\tquery: q,\n\t\tColumnNames: names,\n\t}\n}", "func NewGCPQuery(c client.Client, credsSecretName string) Query {\n\treturn &gcpQuery{\n\t\tgetGCPClient: func() (gcpclient.Client, error) {\n\t\t\tsecret := &corev1.Secret{}\n\t\t\tif err := c.Get(\n\t\t\t\tcontext.Background(),\n\t\t\t\tclient.ObjectKey{Namespace: constants.HiveNamespace, Name: credsSecretName},\n\t\t\t\tsecret,\n\t\t\t); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"could not get the creds secret\")\n\t\t\t}\n\t\t\tauthJSON, ok := secret.Data[constants.GCPCredentialsName]\n\t\t\tif !ok {\n\t\t\t\treturn nil, errors.New(\"creds secret does not contain \\\"\" + constants.GCPCredentialsName + \"\\\" data\")\n\t\t\t}\n\t\t\tgcpClient, err := gcpclient.NewClientWithDefaultProject(authJSON)\n\t\t\treturn gcpClient, errors.Wrap(err, \"error creating GCP client\")\n\t\t},\n\t}\n}", "func NewDropQuery() filters.Spec { return &modQuery{behavior: drop} }", "func (txmgr *LockBasedTxMgr) NewQueryExecutor(txid string) (ledger.QueryExecutor, error) {\n\tqe := newQueryExecutor(txmgr, txid, nil, true, txmgr.hashFunc)\n\ttxmgr.commitRWLock.RLock()\n\treturn qe, nil\n}", "func NewQueryCondition()(*QueryCondition) {\n m := &QueryCondition{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func (c *OperativeClient) Query() *OperativeQuery {\n\treturn &OperativeQuery{config: c.config}\n}", "func NewQuery(table *Table, factors *Factors) *Query {\n\treturn &Query{\n\t\ttable: table,\n\t\tfactors: factors,\n\t\tSteps: make(QueryStepList, 0),\n\t}\n}", "func NewNamedParameterQuery(queryText string) (*NamedParameterQuery) {\n\n\tvar ret *NamedParameterQuery\n\n\t// TODO: I don't like using a map for such a small amount of elements.\n\t// If this becomes a bottleneck for anyone, the first thing to do would\n\t// be to make a slice and search routine for parameter positions.\n\tret = new(NamedParameterQuery)\n\tret.positions = make(map[string][]int, 8)\n\tret.setQuery(queryText)\n\n\treturn ret\n}", "func (ouq *OrgUnitQuery) Clone() *OrgUnitQuery {\n\tif ouq == nil {\n\t\treturn nil\n\t}\n\treturn &OrgUnitQuery{\n\t\tconfig: ouq.config,\n\t\tlimit: ouq.limit,\n\t\toffset: ouq.offset,\n\t\torder: append([]OrderFunc{}, ouq.order...),\n\t\tpredicates: append([]predicate.OrgUnit{}, ouq.predicates...),\n\t\twithCreateBy: ouq.withCreateBy.Clone(),\n\t\twithUpdateBy: ouq.withUpdateBy.Clone(),\n\t\twithMembers: ouq.withMembers.Clone(),\n\t\twithPositions: ouq.withPositions.Clone(),\n\t\twithSupUnit: ouq.withSupUnit.Clone(),\n\t\twithSubUnits: ouq.withSubUnits.Clone(),\n\t\twithBelongToOrg: ouq.withBelongToOrg.Clone(),\n\t\t// clone intermediate query.\n\t\tsql: ouq.sql.Clone(),\n\t\tpath: ouq.path,\n\t}\n}", "func NewViewQueryCustom(dbcon DBConn) ViewQuery {\n\treturn ViewQuery{\n\t\tNewQueryCustom(dbcon),\n\t}\n}", "func (c *Client) NewQuery(params map[string]string) (*http.Request, error) {\n\tu := *c.baseURL\n\n\tq, err := url.ParseQuery(u.RawQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor key, value := range params {\n\t\tq.Add(key, value)\n\t}\n\tq.Add(\"apikey\", c.apiKey)\n\n\tu.RawQuery = q.Encode()\n\n\treq, err := http.NewRequest(\"GET\", u.String(), http.NoBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a request specific headers map.\n\treqHeaders := make(http.Header)\n\treqHeaders.Set(\"Accept\", \"application/json\")\n\n\tfor k, v := range reqHeaders {\n\t\treq.Header[k] = v\n\t}\n\n\treturn req, nil\n}", "func (evsq *ExValueScanQuery) Clone() *ExValueScanQuery {\n\tif evsq == nil {\n\t\treturn nil\n\t}\n\treturn &ExValueScanQuery{\n\t\tconfig: evsq.config,\n\t\tctx: evsq.ctx.Clone(),\n\t\torder: append([]exvaluescan.OrderOption{}, evsq.order...),\n\t\tinters: append([]Interceptor{}, evsq.inters...),\n\t\tpredicates: append([]predicate.ExValueScan{}, evsq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: evsq.sql.Clone(),\n\t\tpath: evsq.path,\n\t}\n}", "func NewGetObjectRequest(bucketName, objectName string) *GetObjectRequest {\n\treturn &GetObjectRequest{bucketName, objectName, nil, nil}\n}", "func (rq *RentQuery) Clone() *RentQuery {\n\treturn &RentQuery{\n\t\tconfig: rq.config,\n\t\tlimit: rq.limit,\n\t\toffset: rq.offset,\n\t\torder: append([]OrderFunc{}, rq.order...),\n\t\tunique: append([]string{}, rq.unique...),\n\t\tpredicates: append([]predicate.Rent{}, rq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: rq.sql.Clone(),\n\t\tpath: rq.path,\n\t}\n}", "func NewSessionQuery() *SessionQuery {\n\treturn &SessionQuery{\n\t\tBaseQuery: kallax.NewBaseQuery(Schema.Session.BaseSchema),\n\t}\n}", "func New(db *sql.DB, q query.Query) (Executor, error) {\n\tif q.Prepare {\n\t\treturn newPreparer(db, q)\n\t}\n\treturn newExecer(db, q)\n}", "func buildQuery(op ops.Operator, qb *queryBuilder) error {\n\tswitch op := op.(type) {\n\tcase *Table:\n\t\tbuildTable(op, qb)\n\tcase *Projection:\n\t\treturn buildProjection(op, qb)\n\tcase *ApplyJoin:\n\t\treturn buildApplyJoin(op, qb)\n\tcase *Filter:\n\t\treturn buildFilter(op, qb)\n\tcase *Horizon:\n\t\tif op.TableId != nil {\n\t\t\treturn buildDerived(op, qb)\n\t\t}\n\t\treturn buildHorizon(op, qb)\n\tcase *Limit:\n\t\treturn buildLimit(op, qb)\n\tcase *Ordering:\n\t\treturn buildOrdering(op, qb)\n\tcase *Aggregator:\n\t\treturn buildAggregation(op, qb)\n\tdefault:\n\t\treturn vterrors.VT13001(fmt.Sprintf(\"do not know how to turn %T into SQL\", op))\n\t}\n\treturn nil\n}", "func (rq *RemedyQuery) Clone() *RemedyQuery {\n\tif rq == nil {\n\t\treturn nil\n\t}\n\treturn &RemedyQuery{\n\t\tconfig: rq.config,\n\t\tlimit: rq.limit,\n\t\toffset: rq.offset,\n\t\torder: append([]OrderFunc{}, rq.order...),\n\t\tpredicates: append([]predicate.Remedy{}, rq.predicates...),\n\t\twithBonedisease: rq.withBonedisease.Clone(),\n\t\t// clone intermediate query.\n\t\tsql: rq.sql.Clone(),\n\t\tpath: rq.path,\n\t}\n}", "func (ksq *KqiSourceQuery) Clone() *KqiSourceQuery {\n\tif ksq == nil {\n\t\treturn nil\n\t}\n\treturn &KqiSourceQuery{\n\t\tconfig: ksq.config,\n\t\tlimit: ksq.limit,\n\t\toffset: ksq.offset,\n\t\torder: append([]OrderFunc{}, ksq.order...),\n\t\tunique: append([]string{}, ksq.unique...),\n\t\tpredicates: append([]predicate.KqiSource{}, ksq.predicates...),\n\t\twithKqiSourceFk: ksq.withKqiSourceFk.Clone(),\n\t\t// clone intermediate query.\n\t\tsql: ksq.sql.Clone(),\n\t\tpath: ksq.path,\n\t}\n}", "func (wfq *WithFieldsQuery) Clone() *WithFieldsQuery {\n\tif wfq == nil {\n\t\treturn nil\n\t}\n\treturn &WithFieldsQuery{\n\t\tconfig: wfq.config,\n\t\tlimit: wfq.limit,\n\t\toffset: wfq.offset,\n\t\torder: append([]OrderFunc{}, wfq.order...),\n\t\tpredicates: append([]predicate.WithFields{}, wfq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: wfq.sql.Clone(),\n\t\tpath: wfq.path,\n\t}\n}", "func (osq *OfflineSessionQuery) Clone() *OfflineSessionQuery {\n\tif osq == nil {\n\t\treturn nil\n\t}\n\treturn &OfflineSessionQuery{\n\t\tconfig: osq.config,\n\t\tlimit: osq.limit,\n\t\toffset: osq.offset,\n\t\torder: append([]OrderFunc{}, osq.order...),\n\t\tpredicates: append([]predicate.OfflineSession{}, osq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: osq.sql.Clone(),\n\t\tpath: osq.path,\n\t\tunique: osq.unique,\n\t}\n}", "func (c *OperationClient) Query() *OperationQuery {\n\treturn &OperationQuery{config: c.config}\n}", "func NewQueryMessage(name, context string, expTime int64, objType []ObjectType,\n\tqueryOptions []QueryOption, token Token) RainsMessage {\n\tquery := QuerySection{\n\t\tContext: context,\n\t\tName: name,\n\t\tExpiration: expTime,\n\t\tTypes: objType,\n\t\tOptions: queryOptions,\n\t}\n\treturn RainsMessage{Token: token, Content: []MessageSection{&query}}\n}", "func (irq *InstanceRuntimeQuery) Clone() *InstanceRuntimeQuery {\n\tif irq == nil {\n\t\treturn nil\n\t}\n\treturn &InstanceRuntimeQuery{\n\t\tconfig: irq.config,\n\t\tlimit: irq.limit,\n\t\toffset: irq.offset,\n\t\torder: append([]OrderFunc{}, irq.order...),\n\t\tpredicates: append([]predicate.InstanceRuntime{}, irq.predicates...),\n\t\twithInstance: irq.withInstance.Clone(),\n\t\twithCaller: irq.withCaller.Clone(),\n\t\t// clone intermediate query.\n\t\tsql: irq.sql.Clone(),\n\t\tpath: irq.path,\n\t}\n}", "func New(agent string) (*Operator, error) {\n\tcli, err := client.New(agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Operator{cli: cli}, nil\n}", "func NewOnlineSqlTaskQueryRequestWithoutParam() *OnlineSqlTaskQueryRequest {\n\n return &OnlineSqlTaskQueryRequest{\n JDCloudRequest: core.JDCloudRequest{\n URL: \"/regions/{regionId}/sqltask:query\",\n Method: \"POST\",\n Header: nil,\n Version: \"v1\",\n },\n }\n}", "func newQueryGate(length int) *queryGate {\n\treturn &queryGate{\n\t\tch: make(chan struct{}, length),\n\t}\n}", "func NewOperator(kind string, in, out reflect.Type, f func(ctx context.Context, field string, object interface{}) (interface{}, error)) Operator {\n\treturn &operator{\n\t\tkind: kind,\n\t\tin: in,\n\t\tout: out,\n\t\tf: f,\n\t}\n}", "func (klq *K8sLabelQuery) Clone() *K8sLabelQuery {\n\tif klq == nil {\n\t\treturn nil\n\t}\n\treturn &K8sLabelQuery{\n\t\tconfig: klq.config,\n\t\tlimit: klq.limit,\n\t\toffset: klq.offset,\n\t\torder: append([]OrderFunc{}, klq.order...),\n\t\tpredicates: append([]predicate.K8sLabel{}, klq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: klq.sql.Clone(),\n\t\tpath: klq.path,\n\t}\n}", "func NewBoolQuery() *BoolQuery {\n\treturn &BoolQuery{Filters: make([]Filter, 0)}\n}", "func MakeQuery(Type operationType) *Query {\n\treturn &Query{Type: Type}\n}", "func Pooled() *Query {\n\tif v := queryPool.Get(); v != nil {\n\t\tq := v.(*Query)\n\t\tq.Reset()\n\t\treturn q\n\t}\n\treturn new(Query)\n}", "func (i *Inventory) NewDeviceQuery() *models.DeviceQuery {\n\treturn models.NewDeviceQuery()\n}", "func NewQueryable(upstream storage.Queryable) storage.Queryable {\n\treturn &mergeQueryable{\n\t\tupstream: upstream,\n\t}\n}", "func NewRequestQuery() *RequestQuery {\n\treturn &RequestQuery{\n\t\tPage: 0,\n\t\tLimit: 100,\n\t}\n}", "func (obj *Device) CreateQuery(typ QUERYTYPE) (query *Query, err Error) {\n\tret, _, _ := syscall.Syscall(\n\t\tobj.vtbl.CreateQuery,\n\t\t3,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(typ),\n\t\tuintptr(unsafe.Pointer(&query)),\n\t)\n\terr = toErr(ret)\n\treturn\n}", "func newQueryPlan(ctx context.Context, store storage.Store, stm *semantic.Statement, chanSize int, w io.Writer) (*queryPlan, error) {\n\tt, err := table.New([]string{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &queryPlan{\n\t\tstm: stm,\n\t\tstore: store,\n\t\tbndgs: stm.Bindings(),\n\t\tgrfsNames: stm.InputGraphNames(),\n\t\tclauses: stm.GraphPatternClauses(),\n\t\tfilters: stm.FilterClauses(),\n\t\ttbl: t,\n\t\tchanSize: chanSize,\n\t\ttracer: w,\n\t}, nil\n}", "func (osq *OfflineSessionQuery) Clone() *OfflineSessionQuery {\n\tif osq == nil {\n\t\treturn nil\n\t}\n\treturn &OfflineSessionQuery{\n\t\tconfig: osq.config,\n\t\tctx: osq.ctx.Clone(),\n\t\torder: append([]offlinesession.OrderOption{}, osq.order...),\n\t\tinters: append([]Interceptor{}, osq.inters...),\n\t\tpredicates: append([]predicate.OfflineSession{}, osq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: osq.sql.Clone(),\n\t\tpath: osq.path,\n\t}\n}", "func (pq *PersonQuery) Clone() *PersonQuery {\n\treturn &PersonQuery{\n\t\tconfig: pq.config,\n\t\tlimit: pq.limit,\n\t\toffset: pq.offset,\n\t\torder: append([]Order{}, pq.order...),\n\t\tunique: append([]string{}, pq.unique...),\n\t\tpredicates: append([]predicate.Person{}, pq.predicates...),\n\t\t// clone intermediate query.\n\t\tsql: pq.sql.Clone(),\n\t\tpath: pq.path,\n\t}\n}" ]
[ "0.6429491", "0.6319228", "0.6145101", "0.6085631", "0.60563207", "0.60545856", "0.5890437", "0.58600295", "0.5855261", "0.5772147", "0.5764213", "0.57355213", "0.57117575", "0.5668293", "0.56658304", "0.56325763", "0.5594233", "0.55472946", "0.5546636", "0.5518794", "0.5478456", "0.5447616", "0.542502", "0.53993016", "0.53723603", "0.53634346", "0.5349246", "0.5300516", "0.5293788", "0.52643746", "0.5230175", "0.5216555", "0.51860726", "0.5180837", "0.51228946", "0.5113907", "0.50770015", "0.5049061", "0.50324434", "0.500997", "0.49917078", "0.498466", "0.49384913", "0.49279106", "0.49231583", "0.49170914", "0.4916186", "0.4900433", "0.48929638", "0.48892725", "0.48703468", "0.48537704", "0.4847071", "0.48446855", "0.48346364", "0.48299715", "0.4790289", "0.478005", "0.47791252", "0.47627863", "0.47595304", "0.47476155", "0.47467893", "0.4744464", "0.47369125", "0.4735915", "0.47265756", "0.4719942", "0.4719877", "0.47178048", "0.47155285", "0.47130507", "0.4712156", "0.4709628", "0.4707997", "0.46956548", "0.4691499", "0.46823663", "0.46812382", "0.46748716", "0.46735436", "0.46716693", "0.46578708", "0.4649902", "0.4647735", "0.4643165", "0.4630602", "0.4629866", "0.46293238", "0.46177912", "0.4616628", "0.46130747", "0.46085235", "0.46017575", "0.46002206", "0.45896202", "0.4579339", "0.45714906", "0.45700505", "0.45693165" ]
0.8440395
0
Handler to get the program build information (GET /).
func (h *handler) getBuild(w http.ResponseWriter, r *http.Request) { _, responseContentType, err := contenttype.APICheck(r.Header) w.Header().Set("Content-Type", responseContentType) errResponder := httperr.NewResponder(responseContentType, h.logger) if err != nil { errResponder.Respond(w, http.StatusNotAcceptable, err.Error()) return } err = json.NewEncoder(w).Encode(h.build) if err != nil { h.logger.Error(err.Error()) errResponder.Respond(w, http.StatusInternalServerError, "") return } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetBuildInfoPerASIC() {\n\n url := \"http://10.67.69.71:8080/job/amd-staging-dkms-sustaining-dGPU/job/sanity-test/job/bare-metal-pro-gfx/api/xml?tree=allBuilds[description,fullDisplayName,id,timestamp]&exclude=//allBuild[not(contains(description,%22navi10%22))]\"\n\tfilepath := \"./navi10_buildinfo\" + \".xml\"\n\tif err := wget(url, filepath); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}", "func (client *Client) ApplicationBuildInformation() (*ApplicationBuildInfo, error) {\n var buildInformation ApplicationBuildInfo\n result, err := client.get(&buildInformation, ENDPOINT_APPLICATION_BUILD_INFO, nil)\n return result.(*ApplicationBuildInfo), err\n}", "func GetBuild() string {\n\treturn Build\n}", "func buildInfo(c *cli.Context) error {\n\trepo := c.Args().First()\n\towner, name, err := parseRepo(repo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnumber, err := strconv.Atoi(c.Args().Get(1))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := newClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuild, err := client.Build(owner, name, number)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tmpl.Execute(os.Stdout, build)\n}", "func (c *Client) BuildInfo(ctx context.Context) (*buildinfoRpc.BuildInfoResponse, error) {\n\treturn c.buildInfoClient.BuildInfo(ctx, &buildinfoRpc.BuildInfoRequest{})\n}", "func GetBuild(settings *playfab.Settings, postData *GetBuildRequestModel, entityToken string) (*GetBuildResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/MultiplayerServer/GetBuild\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &GetBuildResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func getBuild(c *config, job string, number int) (int, Build) {\n\turl := fmt.Sprintf(jobBuildURL, c.Jenkins.Url, job, number)\n\tbuild := Build{}\n\n\tcode, b := jenkinsGet(url, c.Jenkins.User, c.Jenkins.Password, c.Jenkins.Verify)\n\tif code != 200 {\n\t\treturn code, build\n\t}\n\n\te := json.Unmarshal(b, &build)\n\tlogFatal(\"Get build: json\", e)\n\n\treturn code, build\n}", "func Get() BuildInfo {\n\treturn BuildInfo{\n\t\tVersion: getVersion(),\n\t\tGitCommit: gitCommit,\n\t\tGoVersion: runtime.Version(),\n\t}\n}", "func (gw2 *GW2Api) Build() (v int, err error) {\n\tver := \"v2\"\n\ttag := \"build\"\n\n\tvar res version\n\tif err = gw2.fetchEndpoint(ver, tag, nil, &res); err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.ID, nil\n}", "func (o *OSInfo) GetBuild() string {\n\treturn fmt.Sprintf(\"%d.%d.%s\", o.MajorVersion, o.MinorVersion, o.BuildNumber)\n}", "func (b Build) Get(c *gin.Context) {\n\tbuild, err := b.ByID(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsugar.SuccessResponse(c, 200, build)\n}", "func GetBuildDetails(build model.Build, db *db.Db) string {\n\tjsonPath := \"cloudsloutions-fd422e010b14.json\"\n\tcloudService := authenticateCloudBuild(jsonPath)\n\tbuild = getBuildList(build, cloudService)\n\tif build.BuildID == \"0\" {\n\t\treturn \"Failed\"\n\t}\n\tbuild.BuildSeq = db.ReadBuildSeq(build)\n\tupdated, err := db.UpdateCloudBuild(build)\n\tif !updated {\n\t\tfmt.Println(\"error\", err.Error())\n\t\treturn \"Failed\"\n\t}\n\treturn \"Success\"\n}", "func Build() BuildResponse {\n\treturn BuildResponse{\n\t\tVersion: version,\n\t\tCommit: commit,\n\t\tBuiltAt: date,\n\t\tBuiltBy: builtBy,\n\t}\n}", "func (cli *KodderClient) Build(flags []string, context string) error {\n\targs := append(flags, context)\n\tcontent, _ := json.Marshal(args)\n\tlog.Infof(\"Sending build request to kodderd with args %v\", args)\n\n\treader := bytes.NewBuffer(content)\n\treq, err := http.NewRequest(\"POST\", \"http://localhost/build\", reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := cli.HTTPDo(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cli.readLines(resp.Body); err != nil {\n\t\treturn err\n\t} else if resp.StatusCode == http.StatusOK {\n\t\treturn nil\n\t} else if resp.StatusCode == http.StatusConflict {\n\t\treturn ErrWorkerBusy\n\t}\n\treturn fmt.Errorf(\"bad http status code from Kodder worker: %v\", resp.StatusCode)\n}", "func (a *API) health(w http.ResponseWriter, r *http.Request) {\n\tinfo := buildinfo.Get()\n\ta.writeJSON(w, r, http.StatusOK, httputil.HealthCheckResponse{\n\t\tBuildInfo: info,\n\t\tStartedAt: a.startedAt,\n\t})\n}", "func getCurrentBuild(bMap buildMap, builder string, buildNum int) *resp.BuildRef {\n\tb := bMap[builderRef{builder, buildNum}]\n\treturn &resp.BuildRef{\n\t\tBuild: &resp.MiloBuild{\n\t\t\tSummary: summary(b),\n\t\t\tComponents: components(b),\n\t\t\tPropertyGroup: properties(b),\n\t\t\tBlame: []*resp.Commit{},\n\t\t},\n\t\tURL: fmt.Sprintf(\"%d\", buildNum),\n\t}\n}", "func BuildInfo() *build.Info {\n\treturn util.BuildInfo()\n}", "func BuildInfo() *build.Info {\n\treturn util.BuildInfo()\n}", "func (c Client) GetProgramInfo(programIDs []string) ([]ProgramInfo, error) {\n\turl := fmt.Sprint(DefaultBaseURL, APIVersion, \"/programs\")\n\tfmt.Println(\"URL:>\", url)\n\n\t// buffer to store the json request\n\tvar buffer bytes.Buffer\n\n\t// creating the request\n\tbuffer.WriteString(\"[\")\n\tfor index, program := range programIDs {\n\t\t//fmt.Println(program) //debug\n\t\tif(program != \"\") {\n\t\tbuffer.WriteString(`\"`)\n\t\tbuffer.WriteString(program)\n\t\tbuffer.WriteString(`\"`)\n\t\tif index != len(programIDs)-1 {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\t}\n\t}\n\tbuffer.WriteString(\"]\")\n\n\t// setup the request\n\treq, err := http.NewRequest(\"POST\", url, &buffer)\n\t//req.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept-Encoding\", \"deflate,gzip\")\n\treq.Header.Set(\"token\", c.Token)\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\tlog.Fatal(resp.Status)\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close() //resp.Body.Close() will run when we're finished.\n\n\t// Copy the body to Stdout\n\t//_, err = io.Copy(os.Stdout, resp.Body)\n // debug code\t\n //body, _ := ioutil.ReadAll(resp.Body)\n\t //fmt.Println(string(body))\n\n\t// create the programs slice\n\tvar allPrograms []ProgramInfo\n\n \n\t// // decode the body\n\t// err = json.NewDecoder(resp.Body).Decode(&allPrograms)\n\t// if err != nil {\n\t// \tfmt.Println(\"Error parsing programs response\")\n\t// \tlog.Fatal(err)\n\t// \treturn nil, err\n\t// }\n\n\t//readbuffer := bytes.NewBuffer(resp.Body)\n\treader := bufio.NewReader(resp.Body)\n\n\t// we need to increase the default reader size to get this in one shot\n\tbufio.NewReaderSize(reader, 65536)\n\t// there are a few possible loop termination\n\t// conditions, so just start with an infinite loop.\n\tfor {\n\t\t// ReadString because Schedules Direct puts each schedule on it's own line\n\t\t// each line is a complete json object but not the whole response.\n\t\tline, err := reader.ReadString('\\n')\n\n\t\t//debug\n\t\t//fmt.Println(line)\n\n\t\t// loop termination condition 1: EOF.\n\t\t// this is the normal loop termination condition.\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\t// loop termination condition 2: some other error.\n\t\t// Errors happen, so check for them and do something with them.\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t// create a Schedule variable\n\t\t//var s ProgramInfo\n\n\t\t// decode the scanner bytes into the schedule\n\t\terrUnmarshal := json.Unmarshal([]byte(line), &allPrograms)\n\t\tif errUnmarshal != nil {\n\t\t\tlog.Printf(\"error unmarshaling program: %s\\n\", errUnmarshal)\n\t\t} else {\n\t\t\t//allPrograms = append(allPrograms, s)\n\t\t}\n\t}\n\n\treturn allPrograms, err\n}", "func (api *API) fetchInfo(w http.ResponseWriter, r *http.Request) {\n\tdata := struct {\n\t\tAppVersion string `json:\"app_version\"`\n\t}{\n\t\tAppVersion: api.AppVersion,\n\t}\n\trenderJSON(w, data, http.StatusOK)\n}", "func (b *Build) Get() error {\n\tappendum := \"/builds('\" + b.BuildID + \"')\"\n\tbody, err := b.Connector.Get(appendum)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar jBuild jsonBuild\n\tjson.Unmarshal(body, &jBuild)\n\tb.RunState = jBuild.Build.RunState\n\tb.ResultState = jBuild.Build.ResultState\n\tb.Phase = jBuild.Build.Phase\n\tb.Entitytype = jBuild.Build.Entitytype\n\tb.Startedby = jBuild.Build.Startedby\n\tb.StartedAt = jBuild.Build.StartedAt\n\tb.FinishedAt = jBuild.Build.FinishedAt\n\treturn nil\n}", "func GetBuildInfo() Info {\n\treturn Info{Version: buildInfoVersion,\n\t\tRepo: \"https://github.com/cbuschka/versioner\",\n\t\tAuthor: \"Cornelius Buschka <[email protected]>, https://github.com/cbuschka\",\n\t\tCommitish: buildInfoCommitish,\n\t\tBuildTime: strings.Replace(buildInfoBuildTime, \"_\", \" \", -1),\n\t\tArch: buildInfoArch,\n\t\tOS: buildInfoOs}\n}", "func main() {\n\tlog.Printf(\"Build var 'version' is: %s\", version)\n\tlog.Printf(\"Build var 'time' is: %s\", buildDate)\n\tcmd.Execute()\n}", "func (handler *Handler) BuildGetAllHandler(w http.ResponseWriter, r *http.Request) {\n\n\tbuilds, err := data.BuildGetAll()\n\n\tif err != nil {\n\t\trespondWithError(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\trespondWithJSON(w, http.StatusOK, builds)\n}", "func GetVersion(w http.ResponseWriter, r *http.Request) {\n\t\n\tvar softwareVersion string\n\ttype data struct {\n\t\tVersion string\n\t}\n\n\tif r.Body == nil {\n\t\tfmt.Println(\"EMPTY\")\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\n\tvar t data\n\terr := decoder.Decode(&t)\n\n\tif err == io.EOF {\n\t\tsoftwareVersion = \"\"\n\t} else if err != nil {\n\t\tpanic(err)\n\t}\n\n\tif t.Version != \"\" {\n\t\tsoftwareVersion = t.Version\n\t}\n\n\tparams := mux.Vars(r)\n\tsoftwareName := params[\"software\"]\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\tfor _, yamlFile := range listYamlFiles(\".\") {\n\t\tif strings.Split(yamlFile, \".\")[0] == softwareName {\n\t\t\tc := parseYaml(yamlFile)\n\t\t\t_, body, _ := gorequest.New().Get(c.URL).End()\n\t\t\t\n\t\t\tarray := strings.Split(body, \"\\n\")\n\n\t\t\tvar availableVersions []string\n\t\t\tvar av []string\n\n\t\t\tfor _, version := range array {\n\t\t\t\tav = append(av, version)\n\t\t\t}\n\n\t\t\tsort.Strings(av)\n\n\t\t\tfor _, v := range av {\n\t\t\t\tif strings.Contains(v, c.Matcher) {\n\t\t\t\t\tavailableVersions = append(availableVersions, v)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlatestVersion := availableVersions[len(availableVersions)-1]\n\t\t\tr, _ := regexp.Compile(\"(\\\\d+)(?:\\\\.(\\\\d+))*\")\n\t\t\tif softwareVersion == \"\" {\n\t\t\t\tif err := json.NewEncoder(w).Encode(r.FindString(latestVersion)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\tlatestVersionInt64 := parseVersion(r.FindString(latestVersion), 4)\n\t\t\t\tsoftwareVersionInt64 := parseVersion(softwareVersion, 4)\n\n\t\t\t\tif latestVersionInt64 > softwareVersionInt64 {\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tif err := json.NewEncoder(w).Encode(r.FindString(latestVersion)); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func BuildVersion() int {\n\treturn int(C.getBuildVersion())\n\n}", "func buildPackageVersionRequest(name, branchName string) string {\n\tpackageVersionRequest := path.Join(name, \"@v\")\n\tif branchName != \"\" {\n\t\t// A branch name was given by the user\n\t\treturn path.Join(packageVersionRequest, branchName+\".info\")\n\t}\n\t// No version was given to \"go get\" command, so the latest version should be requested\n\treturn path.Join(packageVersionRequest, \"latest.info\")\n}", "func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n var CIVersion, CISHA, CIDescription string\n if os.Getenv(\"CI\") == \"\" {\n // this is local dev mode\n CIVersion = \"localdev\"\n CIDescription = getCommandOutput(\"git\", \"log\", \"-1\", \"--pretty=%B\")\n CISHA = getCommandOutput(\"git\", \"rev-parse\", \"HEAD\")\n }else{\n CIVersion = os.Getenv(\"CI_VERSION\")\n CIDescription = os.Getenv(\"CI_DESCRIPTION\")\n CISHA = os.Getenv(\"CI_SHA\")\n }\n jsonResp, _ := json.MarshalIndent(HealthCheckInfo{\n []AppInfo{\n {\n CIVersion,\n \t\tCIDescription,\n CISHA,\n },\n },\n\t}, \"\", \" \")\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tfmt.Fprintf(w, string(jsonResp))\n}", "func infohandler(w http.ResponseWriter, r *http.Request) {\n\n\t// Get the hostname using a call to os package\n\thostname, _ := os.Hostname()\n\tfmt.Fprintf(w, \"Hostname: %s \\n\", hostname)\n\tfmt.Fprintf(w, \"Version: %s\", version)\n\n}", "func (p *BuildInfoProvider) GetBuildInfo(c context.Context, req *milo.BuildInfoRequest_Swarming,\n\tprojectHint string) (*milo.BuildInfoResponse, error) {\n\n\t// Load the Swarming task (no log content).\n\tsf, err := p.newSwarmingService(c, req.Host)\n\tif err != nil {\n\t\tlogging.WithError(err).Errorf(c, \"Failed to create Swarming fetcher.\")\n\t\treturn nil, grpcutil.Internal\n\t}\n\n\t// Use default Swarming host.\n\thost := sf.GetHost()\n\tlogging.Infof(c, \"Loading build info for Swarming host %s, task %s.\", host, req.Task)\n\n\tfr, err := swarmingFetch(c, sf, req.Task, swarmingFetchParams{})\n\tif err != nil {\n\t\tif err == ErrNotMiloJob {\n\t\t\tlogging.Warningf(c, \"User requested nonexistent task or does not have permissions.\")\n\t\t\treturn nil, grpcutil.NotFound\n\t\t}\n\n\t\tlogging.WithError(err).Errorf(c, \"Failed to load Swarming task.\")\n\t\treturn nil, grpcutil.Internal\n\t}\n\n\t// Determine the LogDog annotation stream path for this Swarming task.\n\t//\n\t// On failure, will return a gRPC error.\n\tstream, err := resolveLogDogAnnotations(c, fr.res.Tags)\n\tif err != nil {\n\t\tlogging.WithError(err).Warningf(c, \"Failed to get annotation stream parameters.\")\n\t\treturn nil, err\n\t}\n\n\tlogging.Fields{\n\t\t\"host\": stream.Host,\n\t\t\"project\": stream.Project,\n\t\t\"path\": stream.Path,\n\t}.Infof(c, \"Resolved LogDog annotation stream.\")\n\n\tstep, err := rawpresentation.ReadAnnotations(c, stream)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to read annotations\").Err()\n\t}\n\n\t// Add Swarming task parameters to the Milo step.\n\tif err := addTaskToMiloStep(c, sf.GetHost(), fr.res, step); err != nil {\n\t\treturn nil, err\n\t}\n\n\tprefix, name := stream.Path.Split()\n\treturn &milo.BuildInfoResponse{\n\t\tProject: string(stream.Project),\n\t\tStep: step,\n\t\tAnnotationStream: &miloProto.LogdogStream{\n\t\t\tServer: stream.Host,\n\t\t\tPrefix: string(prefix),\n\t\t\tName: string(name),\n\t\t},\n\t}, nil\n}", "func BuildGet(key string) *Cmd {\n\treturn Build(key, \"GET\", key)\n}", "func (c Builds) Get(id int) revel.Result {\n\treturn c.Redirect(\"/\")\n}", "func (ta *AppVersion) GetVersion(rw http.ResponseWriter, r *http.Request) {\n\tappVersion, err := ta.db.QueryAppVersion()\n\tif err != nil {\n\t\tta.l.Printf(\"failed to query AppVersion : %s\", err)\n\t\treturn\n\t}\n\t//fmt.Println(appVersion.ID, appVersion.Version, appVersion.DownloadURL, \"hello\")\n\tutils.Respond(rw, models.ResultVersion{appVersion.Version, appVersion.DownloadURL})\n\treturn\n}", "func API(build string, shutdown chan os.Signal, log *log.Logger) *web.App {\n\tapp := web.NewApp(shutdown, middleware.Logger(log), middleware.Errors(log), middleware.Metrics(), middleware.Panics(log))\n\n\tcheck := check{\n\t\tlog: log,\n\t}\n\n\tapp.Handle(http.MethodGet, \"/readiness\", check.readiness)\n\treturn app\n}", "func getAppVersionHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tversionid := vars[\"versionid\"]\n\n\tmongoSession := getMongoSession()\n defer mongoSession.Close()\n\n\tdb := mongoSession.DB(\"control\")\n\tfile, err := db.GridFS(\"appfiles\").Open(versionid)\n\tcheck(err)\n\tdata, err := ioutil.ReadAll(file)\n\tw.Write(data)\n}", "func (l *Logger) BuildInfoString() string {\n\treturn l.staticOptions.BuildInfoString()\n}", "func BuildInfo() *build.Info {\n\treturn &build.Info{}\n}", "func GetVersion(rw http.ResponseWriter) error {\n\tinfostat, err := host.Info()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn share.JSONResponse(infostat, rw)\n}", "func AppVersion() {\n\tif appver != \"\" {\n\t\tfmt.Printf(\"App-Version: %s\\n\", appver)\n\t}\n\tif gitref != \"\" {\n\t\tfmt.Printf(\"Git-Ref: %s\\n\", gitref)\n\t}\n\tif builtby != \"\" {\n\t\tfmt.Printf(\"Built-By: %s\\n\", builtby)\n\t}\n}", "func GetBuildName() error {\n\tmg.Deps(getEnvironment, Clean)\n\tfmt.Println(fmt.Sprintf(\"Create gpsa Version files...\"))\n\tfmt.Println(\"# ########################################################################################\")\n\n\tbuildNumber := gpsaBuildContext.ProgramVersion\n\tif os.Getenv(\"BUILD_NUMBER\") != \"\" {\n\t\tbuildNumber = fmt.Sprintf(\"%s-%s\", gpsaBuildContext.ProgramVersion, os.Getenv(\"BUILD_NUMBER\"))\n\t}\n\n\tif err := gobuildhelpers.EnsureDirectoryExists(gpsaBuildContext.LogDir); err != nil {\n\t\treturn err\n\t}\n\n\terrNr := ioutil.WriteFile(filepath.Join(gpsaBuildContext.LogDir, \"BuildName.txt\"), []byte(buildNumber), 0644)\n\tif errNr != nil {\n\t\treturn errNr\n\t}\n\n\terrVersion := ioutil.WriteFile(filepath.Join(gpsaBuildContext.LogDir, \"Version.txt\"), []byte(gpsaBuildContext.ProgramVersionNumber), 0644)\n\tif errVersion != nil {\n\t\treturn errVersion\n\t}\n\n\terrDum := ioutil.WriteFile(filepath.Join(gpsaBuildContext.LogDir, \"dummy.json\"), []byte(\"{\\\"key\\\":\\\"value\\\"}\"), 0644)\n\tif errDum != nil {\n\t\treturn errDum\n\t}\n\n\tfmt.Println(\"# ########################################################################################\")\n\treturn nil\n}", "func GetVersionHandler() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tversionInfo := GetInfo()\n\n\t\tif jsonVersionInfo, err := json.Marshal(versionInfo); err != nil {\n\t\t\tlog.Error().Err(err).Msgf(\"Error marshaling version info struct: %+v\", versionInfo)\n\t\t} else {\n\t\t\t_, _ = fmt.Fprint(w, string(jsonVersionInfo))\n\t\t}\n\t})\n}", "func Build(router *web.Router) *web.Router {\n\trouter.Get(\"/\", Status)\n\n\treturn todo.Build(router)\n}", "func GetBuildInfo() BuildInfo {\n\ti := BuildInfo{\n\t\tVersion: version,\n\t\tGitBranch: gitBranch,\n\t\tGitHash: gitHash,\n\t\tGitState: \"clean\",\n\t\tBuildTimestamp: buildTimestamp,\n\t\tGoVersion: runtime.Version(),\n\t}\n\n\tif strings.HasSuffix(i.Version, gitStateDirtySuffix) {\n\t\ti.Version = strings.TrimSuffix(i.Version, gitStateDirtySuffix)\n\t\ti.GitState = \"dirty\"\n\t}\n\n\treturn i\n}", "func (ctl *APIController) GetInfo(w http.ResponseWriter, r *http.Request) {\n\n\t// transform\n\ttr := transformers.APITransformer{\n\t\tName: \"Catalyst\",\n\t\tVersion: \"v2.5.1\",\n\t\tPurpose: \"A REST API base written in Golang\",\n\t}\n\n\t// send response\n\tctl.sendResponse(r.Context(), w, http.StatusOK, tr)\n}", "func (app *App) HandleDetectBuildpack(w http.ResponseWriter, r *http.Request) {\n\n\tclient, err := app.githubAppClientFromRequest(r)\n\n\tif err != nil {\n\t\tapp.handleErrorInternal(err, w)\n\t\treturn\n\t}\n\n\tqueryParams, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\tapp.handleErrorFormDecoding(err, ErrReleaseDecode, w)\n\t\treturn\n\t}\n\n\towner := chi.URLParam(r, \"owner\")\n\tname := chi.URLParam(r, \"name\")\n\tbranch := chi.URLParam(r, \"branch\")\n\n\trepoContentOptions := github.RepositoryContentGetOptions{}\n\trepoContentOptions.Ref = branch\n\t_, directoryContents, _, err := client.Repositories.GetContents(context.Background(), owner, name, queryParams[\"dir\"][0], &repoContentOptions)\n\tif err != nil {\n\t\tapp.handleErrorInternal(err, w)\n\t\treturn\n\t}\n\n\tvar BREQS = map[string]string{\n\t\t\"requirements.txt\": \"Python\",\n\t\t\"Gemfile\": \"Ruby\",\n\t\t\"package.json\": \"Node.js\",\n\t\t\"pom.xml\": \"Java\",\n\t\t\"composer.json\": \"PHP\",\n\t}\n\n\tres := AutoBuildpack{\n\t\tValid: true,\n\t}\n\tmatches := 0\n\n\tfor i := range directoryContents {\n\t\tname := *directoryContents[i].Name\n\n\t\tbname, ok := BREQS[name]\n\t\tif ok {\n\t\t\tmatches++\n\t\t\tres.Name = bname\n\t\t}\n\t}\n\n\tif matches != 1 {\n\t\tres.Valid = false\n\t\tres.Name = \"\"\n\t}\n\n\tjson.NewEncoder(w).Encode(res)\n}", "func getBuildModule() *debug.Module {\n\tbi, ok := debug.ReadBuildInfo()\n\tif ok {\n\t\t// The recommended way to build Caddy involves\n\t\t// creating a separate main module, which\n\t\t// preserves caddy a read-only dependency\n\t\t// TODO: track related Go issue: https://github.com/golang/go/issues/29228\n\t\tfor _, mod := range bi.Deps {\n\t\t\tif mod.Path == \"github.com/caddyserver/caddy\" {\n\t\t\t\treturn mod\n\t\t\t}\n\t\t}\n\t}\n\treturn &debug.Module{Version: \"unknown\"}\n}", "func getAppVersionsHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tappid := vars[\"appid\"]\n\tvar app App\n\terr := getApp(appid, &app)\n\tcheck(err)\n\trespondWithResult(w, app.Versions)\n}", "func GetReleaseInformation(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tc := ReleaseInformation{\"relid\", \"app\", \"stream\", \"something\", \"xebia\", \"1234\"}\n\toutgoingJSON, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tres.WriteHeader(http.StatusCreated)\n\tfmt.Fprint(res, string(outgoingJSON))\n}", "func (h *Handler) Get(res http.ResponseWriter, req *http.Request) {\n\tquery := req.URL.Query()\n\tproject := query.Get(\"project\")\n\tif len(project) == 0 {\n\t\th.getAll(res, req)\n\t} else {\n\t\th.getOne(res, req, query, project)\n\t}\n}", "func (r *REST) Get(ctx kapi.Context, name string, opts runtime.Object) (runtime.Object, error) {\n\tbuildLogOpts, ok := opts.(*api.BuildLogOptions)\n\tif !ok {\n\t\treturn nil, errors.NewBadRequest(\"did not get an expected options.\")\n\t}\n\tbuild, err := r.BuildRegistry.GetBuild(ctx, name)\n\tif err != nil {\n\t\treturn nil, errors.NewNotFound(\"build\", name)\n\t}\n\tswitch build.Status.Phase {\n\t// Build has not launched, wait til it runs\n\tcase api.BuildPhaseNew, api.BuildPhasePending:\n\t\tif buildLogOpts.NoWait {\n\t\t\tglog.V(4).Infof(\"Build %s/%s is in %s state. No logs to retrieve yet.\", build.Namespace, name, build.Status.Phase)\n\t\t\t// return empty content if not waiting for build\n\t\t\treturn &genericrest.LocationStreamer{}, nil\n\t\t}\n\t\tglog.V(4).Infof(\"Build %s/%s is in %s state, waiting for Build to start\", build.Namespace, name, build.Status.Phase)\n\t\terr := r.waitForBuild(ctx, build)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t// The build was cancelled\n\tcase api.BuildPhaseCancelled:\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"build %s/%s was cancelled. %s\", build.Namespace, build.Name, buildutil.NoBuildLogsMessage))\n\n\t// An error occurred launching the build, return an error\n\tcase api.BuildPhaseError:\n\t\treturn nil, errors.NewBadRequest(fmt.Sprintf(\"build %s/%s is in an error state. %s\", build.Namespace, build.Name, buildutil.NoBuildLogsMessage))\n\t}\n\t// The container should be the default build container, so setting it to blank\n\tbuildPodName := buildutil.GetBuildPodName(build)\n\tlogOpts := &kapi.PodLogOptions{\n\t\tFollow: buildLogOpts.Follow,\n\t}\n\tlocation, transport, err := pod.LogLocation(r.PodGetter, r.ConnectionInfo, ctx, buildPodName, logOpts)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn nil, errors.NewNotFound(\"pod\", buildPodName)\n\t\t}\n\t\treturn nil, errors.NewBadRequest(err.Error())\n\t}\n\treturn &genericrest.LocationStreamer{\n\t\tLocation: location,\n\t\tTransport: transport,\n\t\tContentType: \"text/plain\",\n\t\tFlush: buildLogOpts.Follow,\n\t}, nil\n}", "func OnlineBuild(request *http.Request) (string, interface{}) {\n\tdecoder := json.NewDecoder(request.Body)\n\tbuilder := &build.Build{}\n\terr := decoder.Decode(builder)\n\tif err != nil {\n\t\tlog.Errorf(\"decode the request body err:%v\", err)\n\t\treturn r.StatusBadRequest, \"json format error\"\n\t}\n\t//TODO\n\treturn r.StatusCreated, nil\n}", "func GetInfo(hostURL string, hostPort int) *bytes.Buffer {\n\treturn makeGetRequest(\"getinfo\", hostURL, hostPort)\n}", "func (c *HTTPDebuginfodClient) Get(ctx context.Context, buildID string) (io.ReadCloser, error) {\n\treturn c.request(ctx, c.upstreamServer, buildID)\n}", "func main() {\n\tcl := flag.Bool(\"clean\", false, \"don't build, just clean the generated pages\")\n\t//run := flag.Bool(\"run\", false, \"run the generated executable after build\")\n\tflag.Parse()\n\tif *cl {\n\t\terr := clean()\n\t\tif err != nil {\n\t\t\tprintln(err.Error())\n\t\t}\n\t\treturn\n\t}\n\tsettings, err := util.LoadSettings() //inits the settings and generates the .go source files\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\tutil.Config = settings.Data //stores settings to accessible variable\n\tprintln(\"generated\", len(settings.Data[\"pages\"]), \"gopages\")\n\tprintln()\n\terr = util.AddHandlers(settings.Data[\"pages\"]) //add all handlers\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\treturn\n\t}\n\tif len(os.Args) > 1 && os.Args[1] == \"get\" {\n\t\tbuild(\"\")\n\t} else if len(os.Args) > 1 {\n\t\tprintln(\"unrecognized \", \"'\"+os.Args[1]+\"'\")\n\t\tprintln(\" gopages get - build project with go get after generating pages\")\n\t} else {\n\t\tbuild(\"pages\")\n\t\tprintln(\"run \\\"gopages get\\\" to build project with go get after generating pages\")\n\t}\n}", "func GetProgramInfoLog(program uint32, bufSize int32, length *int32, infoLog *uint8) {\n\tC.glowGetProgramInfoLog(gpGetProgramInfoLog, (C.GLuint)(program), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLchar)(unsafe.Pointer(infoLog)))\n}", "func GetProgramInfoLog(program uint32, bufSize int32, length *int32, infoLog *uint8) {\n\tC.glowGetProgramInfoLog(gpGetProgramInfoLog, (C.GLuint)(program), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLchar)(unsafe.Pointer(infoLog)))\n}", "func showApplicationInfo(app, ver, gitRev string) {\n\tfmtutil.Separator(false, \"APPLICATION INFO\")\n\n\tprintInfo(7, \"Name\", app)\n\tprintInfo(7, \"Version\", ver)\n\n\tprintInfo(7, \"Go\", fmtc.Sprintf(\n\t\t\"%s {s}(%s/%s){!}\",\n\t\tstrings.TrimLeft(runtime.Version(), \"go\"),\n\t\truntime.GOOS, runtime.GOARCH,\n\t))\n\n\tif gitRev != \"\" {\n\t\tif !fmtc.DisableColors && fmtc.IsTrueColorSupported() {\n\t\t\tprintInfo(7, \"Git SHA\", gitRev+getHashColorBullet(gitRev))\n\t\t} else {\n\t\t\tprintInfo(7, \"Git SHA\", gitRev)\n\t\t}\n\t}\n\n\tbin, _ := os.Executable()\n\tbinSHA := hash.FileHash(bin)\n\n\tif binSHA != \"\" {\n\t\tbinSHA = strutil.Head(binSHA, 7)\n\t\tif !fmtc.DisableColors && fmtc.IsTrueColorSupported() {\n\t\t\tprintInfo(7, \"Bin SHA\", binSHA+getHashColorBullet(binSHA))\n\t\t} else {\n\t\t\tprintInfo(7, \"Bin SHA\", binSHA)\n\t\t}\n\t}\n}", "func ProgramHandler(w http.ResponseWriter, r *http.Request) {\n\tt, _ := template.ParseFiles(\"html/applications.html\")\n\tlsUsr := exec.Command(\"ls\", \"/usr/bin\")\n\tlsOutput, stderr := lsUsr.Output()\n\tp := Programs{Progs: make([]string, 1)}\n\tvar count int = 0\n\n\tif stderr != nil {\n\t\tfmt.Println(stderr)\n\t}\n\tfor i := 0; i < len(lsOutput); i++ {\n\t\tif lsOutput[i] != 10 {\n\t\t\tp.Progs[count] += string(lsOutput[i])\n\t\t} else {\n\t\t\tcount++\n\t\t\tp.Progs = append(p.Progs, \"\")\n\t\t}\n\t}\n\n\tt.Execute(w, p)\n}", "func GetProgramInfoLog(program uint32, bufSize int32, length *int32, infoLog *uint8) {\n\tsyscall.Syscall6(gpGetProgramInfoLog, 4, uintptr(program), uintptr(bufSize), uintptr(unsafe.Pointer(length)), uintptr(unsafe.Pointer(infoLog)), 0, 0)\n}", "func Build() (app *App, compileError *revel.Error) {\n\t// First, clear the generated files (to avoid them messing with ProcessSource).\n\tcleanSource(\"tmp\", \"routes\")\n\n\tsourceInfo, compileError := ProcessSource(revel.CodePaths)\n\tif compileError != nil {\n\t\treturn nil, compileError\n\t}\n\n\t// Add the db.import to the import paths.\n\tif dbImportPath, found := revel.Config.String(\"db.import\"); found {\n\t\tsourceInfo.InitImportPaths = append(sourceInfo.InitImportPaths, dbImportPath)\n\t}\n\n\t// Generate two source files.\n\ttemplateArgs := map[string]interface{}{\n\t\t\"Controllers\": sourceInfo.ControllerSpecs(),\n\t\t\"ValidationKeys\": sourceInfo.ValidationKeys,\n\t\t\"ImportPaths\": calcImportAliases(sourceInfo),\n\t\t\"TestSuites\": sourceInfo.TestSuites(),\n\t}\n\tgenSource(\"tmp\", \"main.go\", MAIN, templateArgs)\n\tgenSource(\"routes\", \"routes.go\", ROUTES, templateArgs)\n\n\t// Read build config.\n\tbuildTags := revel.Config.StringDefault(\"build.tags\", \"\")\n\n\t// Build the user program (all code under app).\n\t// It relies on the user having \"go\" installed.\n\tgoPath, err := exec.LookPath(\"go\")\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Go executable not found in PATH.\")\n\t}\n\n\tpkg, err := build.Default.Import(revel.ImportPath, \"\", build.FindOnly)\n\tif err != nil {\n\t\trevel.ERROR.Fatalln(\"Failure importing\", revel.ImportPath)\n\t}\n\tbinName := path.Join(pkg.BinDir, path.Base(revel.BasePath))\n\tif runtime.GOOS == \"windows\" {\n\t\tbinName += \".exe\"\n\t}\n\n\tgotten := make(map[string]struct{})\n\tfor {\n\t\tappVersion := getAppVersion()\n\t\tversionLinkerFlags := fmt.Sprintf(\"-X %s/app.APP_VERSION \\\"%s\\\"\", revel.ImportPath, appVersion)\n\n\t\tbuildCmd := exec.Command(goPath, \"build\",\n\t\t\t\"-ldflags\", versionLinkerFlags,\n\t\t\t\"-tags\", buildTags,\n\t\t\t\"-o\", binName, path.Join(revel.ImportPath, \"app\", \"tmp\"))\n\t\trevel.TRACE.Println(\"Exec:\", buildCmd.Args)\n\t\toutput, err := buildCmd.CombinedOutput()\n\n\t\t// If the build succeeded, we're done.\n\t\tif err == nil {\n\t\t\treturn NewApp(binName), nil\n\t\t}\n\t\trevel.ERROR.Println(string(output))\n\n\t\t// See if it was an import error that we can go get.\n\t\tmatches := importErrorPattern.FindStringSubmatch(string(output))\n\t\tif matches == nil {\n\t\t\treturn nil, newCompileError(output)\n\t\t}\n\n\t\t// Ensure we haven't already tried to go get it.\n\t\tpkgName := matches[1]\n\t\tif _, alreadyTried := gotten[pkgName]; alreadyTried {\n\t\t\treturn nil, newCompileError(output)\n\t\t}\n\t\tgotten[pkgName] = struct{}{}\n\n\t\t// Execute \"go get <pkg>\"\n\t\tgetCmd := exec.Command(goPath, \"get\", pkgName)\n\t\trevel.TRACE.Println(\"Exec:\", getCmd.Args)\n\t\tgetOutput, err := getCmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\trevel.ERROR.Println(string(getOutput))\n\t\t\treturn nil, newCompileError(output)\n\t\t}\n\n\t\t// Success getting the import, attempt to build again.\n\t}\n\trevel.ERROR.Fatalf(\"Not reachable\")\n\treturn nil, nil\n}", "func (*Builds) GetBuild(ctx context.Context, req *pb.GetBuildRequest) (*pb.Build, error) {\n\tif err := validateGet(req); err != nil {\n\t\treturn nil, appstatus.BadRequest(err)\n\t}\n\tm, err := model.NewBuildMask(\"\", req.Fields, req.Mask)\n\tif err != nil {\n\t\treturn nil, appstatus.BadRequest(errors.Annotate(err, \"invalid mask\").Err())\n\t}\n\tif req.Id == 0 {\n\t\treq.Id, err = getBuildIDByBuildNumber(ctx, req.Builder, req.BuildNumber)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbld, err := getBuild(ctx, req.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// User needs BuildsGet or BuildsGetLimited permission to call this endpoint.\n\treadPerm, err := perm.GetFirstAvailablePerm(ctx, bld.Proto.Builder, bbperms.BuildsGet, bbperms.BuildsGetLimited)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbp, err := bld.ToProto(ctx, m, func(b *pb.Build) error {\n\t\tif readPerm == bbperms.BuildsGet {\n\t\t\treturn nil\n\t\t}\n\t\treturn perm.RedactBuild(ctx, nil, b)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbp.SummaryMarkdown = protoutil.CombineCancelSummary(bp)\n\n\treturn bp, nil\n\n}", "func getBuildMatrix() (map[string][]string, error) {\n\tjsonData, err := sh.Output(\"go\", \"tool\", \"dist\", \"list\", \"-json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []struct {\n\t\tGoos string\n\t\tGoarch string\n\t}\n\tif err := json.Unmarshal([]byte(jsonData), &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatrix := map[string][]string{}\n\tfor _, v := range data {\n\t\tif val, ok := matrix[v.Goos]; ok {\n\t\t\tmatrix[v.Goos] = append(val, v.Goarch)\n\t\t} else {\n\t\t\tmatrix[v.Goos] = []string{v.Goarch}\n\t\t}\n\t}\n\n\treturn matrix, nil\n}", "func GetProgramInfoLog(program uint32, bufSize int32, length *int32, infoLog *int8) {\n C.glowGetProgramInfoLog(gpGetProgramInfoLog, (C.GLuint)(program), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLchar)(unsafe.Pointer(infoLog)))\n}", "func (s *service) getExecutable(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tf, err := s.store.Executable(p.ByName(\"hash\"))\n\tif err != nil {\n\t\twriteError(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t// We ignore the error here, because the zero-value is fine in case of\n\t// error.\n\tinfo, _ := f.Stat()\n\thttp.ServeContent(w, r, info.Name(), info.ModTime(), f)\n}", "func (b *Build) Run(c *router.Control) {\n\trequestID := uuid.NewV4().String()\n\tb.log = b.log.WithField(\"requestID\", requestID)\n\tb.log.Infof(\"Processing request...\")\n\n\treq := new(cicd.BuildRequest)\n\terr := json.NewDecoder(c.Request.Body).Decode(&req)\n\n\tif err != nil {\n\t\tc.Code(http.StatusBadRequest).Body(\"Couldn't parse request body.\")\n\t\treturn\n\t}\n\n\tif len(req.Username) == 0 || len(req.Repository) == 0 || len(req.CommitHash) == 0 {\n\t\tc.Code(http.StatusBadRequest).Body(\"The fields username, repository and commitHash are required.\")\n\t\treturn\n\t}\n\n\t// TODO: manage amount of goroutines!\n\t// TODO: add max execution time of goroutine!!!! If processing is too slow, we need to stop it\n\tgo b.processBuild(req, requestID)\n\n\tdata := &cicd.Build{RequestID: requestID}\n\tresponse := cicd.BuildResponse{Data: data}\n\tc.Code(http.StatusCreated).Body(response)\n}", "func (o *Options) BuildInfoString() string {\n\treturn fmt.Sprintf(\"(%v v%v, Release: %s)\", o.BinaryName, o.Version, o.Release)\n}", "func (*GetBuildRequest) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_buildbucket_proto_builds_service_proto_rawDescGZIP(), []int{0}\n}", "func CurrProgHandler(w http.ResponseWriter, r *http.Request) {\n\tt, m := ParseHTMLQuery(\"html/choice.html\", r)\n\tversion := exec.Command(m[\"application\"][0], \"--version\")\n\tverOutput, stderr := version.Output()\n\tp := Programs{CurrProg: m[\"application\"][0], Version: \"\"}\n\tif stderr != nil {\n\t\tfmt.Println(stderr)\n\t}\n\tif string(verOutput) != \"\" {\n\t\tfor i := 0; verOutput[i] != 10; i++ {\n\t\t\tp.Version += string(verOutput[i])\n\t\t}\n\t}\n\tt.Execute(w, p)\n}", "func getBuildLog(url string) string {\n\tresponse, err := http.Get(url)\n\tif url == \"\" {\n\t\treturn \"\"\n\t}\n\n\tdefer response.Body.Close()\n\n\tb, err := ioutil.ReadAll(response.Body)\n\tcheck(err)\n\n\t//only the last part of the log is relevant\n\te := len(b) - 1\n\ts := 0\n\tif e > lastBytes {\n\t\ts = e - lastBytes\n\t}\n\n\t//drop anything after the error message\n\tres := strings.SplitN(string(b[s:e]), endOfLog, 2)\n\n\t//keep only last 200 lines\n\tsplit := strings.Split(res[0], \"\\n\")\n\n\te = len(split) - 1\n\ts = 0\n\tif e > 200 {\n\t\ts = e - 200\n\t}\n\n\treturn strings.Join(split[s:e], \"\\n\")\n}", "func (debugging *debuggingOpenGL) GetProgramInfoLog(program uint32) string {\n\tdebugging.recordEntry(\"GetProgramInfoLog\", program)\n\tresult := debugging.gl.GetProgramInfoLog(program)\n\tdebugging.recordExit(\"GetProgramInfoLog\", result)\n\treturn result\n}", "func (p *Pvr) GetApplicationInfo(appname string) error {\n\tsrcFilePath := filepath.Join(p.Dir, appname, \"src.json\")\n\tif _, err := os.Stat(srcFilePath); err != nil {\n\t\treturn errors.New(\"App '\" + appname + \"' doesn't exist\")\n\t}\n\tsrc, _ := ioutil.ReadFile(srcFilePath)\n\tvar fileData interface{}\n\terr := pvjson.Unmarshal(src, &fileData)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonData, err := json.MarshalIndent(fileData, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(string(jsonData))\n\treturn nil\n}", "func (mc *MainController) Get() {\n\tmc.Ctx.WriteString(`\n\t<!doctype html>\n\t<html>\n\t<head>\n\t <title>Port Scanner</title>\n\t <script>\n\t </script>\n\t</head>\n\t<body>\n\t<form action=\"/portscan\" method=\"post\">\n\t<p>IP or Hostname for Port Scan</p>\n\t<p><input type=\"text\" name=\"address\" autofocus></p>\n\t<button type=\"submit\">Scan Ports</button>\n\t</form>\n\t</body>\n\t</html>\n\t`)\n}", "func buildVersion(short bool) string {\n\tvar b bytes.Buffer\n\tb.WriteString(\"MicroService-UserPowerManager v\" + MajorVersion + \".\" + MinorVersion)\n\t// versionStr := fmt.Sprintf(\"MicroService-UserPowerManager v%s.%s\",\n\t// \tMajorVersion, MinorVersion)\n\tif !IsRelease {\n\t\tb.WriteString(\" pre-release.\\n\")\n\t\tif !short {\n\t\t\tb.WriteString(PrereleaseBlurb + \"\\n\")\n\t\t}\n\t} else {\n\t\tb.WriteString(\" release.\\n\")\n\t}\n\tif short {\n\t\treturn b.String()\n\t}\n\tb.WriteString(Copyright + \"\\n\")\n\tb.WriteString(fmt.Sprintf(`Git Commit: %v\nGit Revision: %v\nGolang Build Version: %v\nBuild User: %v@%v\nBuild Status: %v\nBuild Time: %v\n`,\n\t\tbuildGitCommit,\n\t\tbuildGitRevision,\n\t\tbuildGolangVersion,\n\t\tbuildUser,\n\t\tbuildHost,\n\t\tbuildStatus,\n\t\tbuildTime))\n\tb.WriteString(GitHub + \"\\n\")\n\tb.WriteString(Issues + \"\\n\")\n\treturn b.String()\n}", "func Run(srv *server.Server, templatePath string) {\n\t// Register plain ol' http handlers.\n\tr := srv.Routes\n\n\tbaseMW := router.NewMiddlewareChain()\n\tbaseAuthMW := baseMW.Extend(\n\t\tmiddleware.WithContextTimeout(time.Minute),\n\t\tauth.Authenticate(srv.CookieAuth),\n\t)\n\thtmlMW := baseAuthMW.Extend(\n\t\twithGitMiddleware,\n\t\twithBuildbucketBuildsClient,\n\t\twithBuildbucketBuildersClient,\n\t\ttemplates.WithTemplates(getTemplateBundle(templatePath, srv.Options.ImageVersion(), srv.Options.Prod)),\n\t)\n\txsrfMW := htmlMW.Extend(xsrf.WithTokenCheck)\n\tprojectMW := htmlMW.Extend(buildProjectACLMiddleware(false))\n\toptionalProjectMW := htmlMW.Extend(buildProjectACLMiddleware(true))\n\n\tr.GET(\"/\", htmlMW, frontpageHandler)\n\tr.GET(\"/p\", baseMW, movedPermanently(\"/\"))\n\tr.GET(\"/search\", htmlMW, redirect(\"/ui/search\", http.StatusFound))\n\tr.GET(\"/opensearch.xml\", baseMW, searchXMLHandler)\n\n\t// Artifacts.\n\tr.GET(\"/artifact/*path\", baseMW, redirect(\"/ui/artifact/*path\", http.StatusFound))\n\n\t// Invocations.\n\tr.GET(\"/inv/*path\", baseMW, redirect(\"/ui/inv/*path\", http.StatusFound))\n\n\t// Builds.\n\tr.GET(\"/b/:id\", htmlMW, handleError(redirectLUCIBuild))\n\tr.GET(\"/p/:project/builds/b:id\", baseMW, movedPermanently(\"/b/:id\"))\n\n\tbuildPageMW := router.NewMiddlewareChain(func(c *router.Context, next router.Handler) {\n\t\tshouldShowNewBuildPage := getShowNewBuildPageCookie(c)\n\t\tif shouldShowNewBuildPage {\n\t\t\tredirect(\"/ui/p/:project/builders/:bucket/:builder/:numberOrId\", http.StatusFound)(c)\n\t\t} else {\n\t\t\tnext(c)\n\t\t}\n\t}).Extend(optionalProjectMW...)\n\tr.GET(\"/p/:project/builders/:bucket/:builder/:numberOrId\", buildPageMW, handleError(handleLUCIBuild))\n\t// TODO(crbug/1108198): remvoe this route once we turned down the old build page.\n\tr.GET(\"/old/p/:project/builders/:bucket/:builder/:numberOrId\", optionalProjectMW, handleError(handleLUCIBuild))\n\n\t// Only the new build page can take path suffix, redirect to the new build page.\n\tr.GET(\"/b/:id/*path\", baseMW, redirect(\"/ui/b/:id/*path\", http.StatusFound))\n\tr.GET(\"/p/:project/builds/b:id/*path\", baseMW, redirect(\"/ui/b/:id/*path\", http.StatusFound))\n\tr.GET(\"/p/:project/builders/:bucket/:builder/:numberOrId/*path\", baseMW, redirect(\"/ui/p/:project/builders/:bucket/:builder/:numberOrId/*path\", http.StatusFound))\n\n\t// Console\n\tr.GET(\"/p/:project\", projectMW, handleError(func(c *router.Context) error {\n\t\treturn ConsolesHandler(c, c.Params.ByName(\"project\"))\n\t}))\n\tr.GET(\"/p/:project/\", baseMW, movedPermanently(\"/p/:project\"))\n\tr.GET(\"/p/:project/g\", baseMW, movedPermanently(\"/p/:project\"))\n\tr.GET(\"/p/:project/g/:group/console\", projectMW, handleError(ConsoleHandler))\n\tr.GET(\"/p/:project/g/:group\", projectMW, redirect(\"/p/:project/g/:group/console\", http.StatusFound))\n\tr.GET(\"/p/:project/g/:group/\", baseMW, movedPermanently(\"/p/:project/g/:group\"))\n\n\t// Builder list\n\t// Redirects to the lit-element implementation.\n\tr.GET(\"/p/:project/builders\", baseMW, redirect(\"/ui/p/:project/builders\", http.StatusFound))\n\tr.GET(\"/p/:project/g/:group/builders\", baseMW, redirect(\"/ui/p/:project/g/:group/builders\", http.StatusFound))\n\n\t// Swarming\n\tr.GET(swarming.URLBase+\"/:id/steps/*logname\", htmlMW, handleError(HandleSwarmingLog))\n\tr.GET(swarming.URLBase+\"/:id\", htmlMW, handleError(handleSwarmingBuild))\n\t// Backward-compatible URLs for Swarming:\n\tr.GET(\"/swarming/prod/:id/steps/*logname\", htmlMW, handleError(HandleSwarmingLog))\n\tr.GET(\"/swarming/prod/:id\", htmlMW, handleError(handleSwarmingBuild))\n\n\t// Buildbucket\n\t// If these routes change, also change links in common/model/build_summary.go:getLinkFromBuildID\n\t// and common/model/builder_summary.go:SelfLink.\n\tr.GET(\"/p/:project/builders/:bucket/:builder\", optionalProjectMW, handleError(BuilderHandler))\n\n\tr.GET(\"/buildbucket/:bucket/:builder\", baseMW, redirectFromProjectlessBuilder)\n\n\t// LogDog Milo Annotation Streams.\n\t// This mimics the `logdog://logdog_host/project/*path` url scheme seen on\n\t// swarming tasks.\n\tr.GET(\"/raw/build/:logdog_host/:project/*path\", htmlMW, handleError(handleRawPresentationBuild))\n\n\tpubsubMW := router.NewMiddlewareChain(\n\t\tauth.Authenticate(&openid.GoogleIDTokenAuthMethod{\n\t\t\tAudienceCheck: openid.AudienceMatchesHost,\n\t\t}),\n\t\twithBuildbucketBuildsClient,\n\t)\n\tpusherID := identity.Identity(fmt.Sprintf(\"user:buildbucket-pubsub@%s.iam.gserviceaccount.com\", srv.Options.CloudProject))\n\n\t// PubSub subscription endpoints.\n\tr.POST(\"/push-handlers/buildbucket\", pubsubMW, func(ctx *router.Context) {\n\t\tif got := auth.CurrentIdentity(ctx.Context); got != pusherID {\n\t\t\tlogging.Errorf(ctx.Context, \"Expecting ID token of %q, got %q\", pusherID, got)\n\t\t\tctx.Writer.WriteHeader(403)\n\t\t} else {\n\t\t\tbuildbucket.PubSubHandler(ctx)\n\t\t}\n\t})\n\n\tr.POST(\"/actions/cancel_build\", xsrfMW, handleError(cancelBuildHandler))\n\tr.POST(\"/actions/retry_build\", xsrfMW, handleError(retryBuildHandler))\n\n\tr.GET(\"/internal_widgets/related_builds/:id\", htmlMW, handleError(handleGetRelatedBuildsTable))\n\n\t// Config for ResultUI frontend.\n\tr.GET(\"/configs.js\", baseMW, handleError(configsJSHandler))\n\n\tr.GET(\"/auth-state\", baseAuthMW, handleError(getAuthState))\n}", "func (r *ProgramControlRequest) Get(ctx context.Context) (resObj *ProgramControl, 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}", "func getMain(c *gin.Context) {\n\n\tc.HTML(http.StatusOK, \"index.html\", gin.H{\n\t\t\"module\": biModule,\n\t})\n}", "func (h *Handler) Build(name string, params Params) (string, error) {\n\tb, ok := h.router.(Builder)\n\tif !ok {\n\t\treturn \"\", errors.New(\"mux: router is not a Builder\")\n\t}\n\treturn b.Build(name, params)\n}", "func (a *DefaultApiService) ProjectUsernameProjectBuildNumGet(ctx context.Context, username string, project string, buildNum int32) (BuildDetail, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload BuildDetail\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/project/{username}/{project}/{build_num}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", fmt.Sprintf(\"%v\", username), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"project\"+\"}\", fmt.Sprintf(\"%v\", project), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"build_num\"+\"}\", fmt.Sprintf(\"%v\", buildNum), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json; charset=utf-8\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarQueryParams.Add(\"circle-token\", key)\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func BuildVersion() string {\n\tif version == \"\" {\n\t\treturn \"1.0-dev\"\n\t}\n\treturn version\n}", "func GetBuildTime() string {\n\treturn version.GetBuildTime()\n}", "func GetProgramBinary(program uint32, bufSize int32, length *int32, binaryFormat *uint32, binary unsafe.Pointer) {\n C.glowGetProgramBinary(gpGetProgramBinary, (C.GLuint)(program), (C.GLsizei)(bufSize), (*C.GLsizei)(unsafe.Pointer(length)), (*C.GLenum)(unsafe.Pointer(binaryFormat)), binary)\n}", "func (p *Process) BuildVersion() string {\n\treturn p.buildVersion\n}", "func (c *DetaClient) GetProgDetails(req *GetProgDetailsRequest) (*GetProgDetailsResponse, error) {\n\ti := &requestInput{\n\t\tPath: fmt.Sprintf(\"/spaces/%d/projects/%s/programs/%s\", req.Space, req.Project, req.Program),\n\t\tMethod: \"GET\",\n\t\tNeedsAuth: true,\n\t}\n\to, err := c.request(i)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif o.Status != 200 {\n\t\tmsg := o.Error.Message\n\t\tif msg == \"\" {\n\t\t\tmsg = o.Error.Errors[0]\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get details: %v\", msg)\n\t}\n\tvar resp GetProgDetailsResponse\n\terr = json.Unmarshal(o.Body, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func PrintVersion() {\n\tfmt.Println(assets.BuildInfo)\n}", "func GetPipelineBuildStatus(proj, app, pip, env string, buildNumber int64) (PipelineBuild, error) {\n\tvar pb PipelineBuild\n\tvar uri string\n\n\tif buildNumber == 0 {\n\t\turi = fmt.Sprintf(\"/project/%s/application/%s/pipeline/%s/build/last?envName=%s\",\n\t\t\tproj, app, pip, url.QueryEscape(env))\n\t} else {\n\t\turi = fmt.Sprintf(\"/project/%s/application/%s/pipeline/%s/build/%d?envName=%s\",\n\t\t\tproj, app, pip, buildNumber, url.QueryEscape(env))\n\t}\n\n\tdata, _, errr := Request(\"GET\", uri, nil)\n\tif errr != nil {\n\t\treturn pb, errr\n\t}\n\tif err := json.Unmarshal(data, &pb); err != nil {\n\t\treturn pb, err\n\t}\n\n\treturn pb, nil\n}", "func ProgramMeta(pg *ast.CXProgram) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tresp := extractProgramMeta(pg)\n\t\t//httputil.WriteJSON(w, req, http.StatusOK, resp)\n\t\tWriteJSON(w, req, http.StatusOK, resp)\n\t}\n}", "func getRun(request GetRequest) (err error) {\n\treturn repository.InstallRepository(request.RepoUrl)\n}", "func serveIndex(w http.ResponseWriter, r *http.Request, bs buildSpec, br *buildResult) {\n\txreq := request{bs, \"\", pageIndex}\n\txlink := xreq.link()\n\n\ttype versionLink struct {\n\t\tVersion string\n\t\tURLPath string\n\t\tSuccess bool\n\t\tActive bool\n\t}\n\ttype response struct {\n\t\tErr error\n\t\tLatestVersion string\n\t\tVersionLinks []versionLink\n\t}\n\n\t// Do a lookup to the goproxy in the background, to list the module versions.\n\tc := make(chan response, 1)\n\tgo func() {\n\t\tt0 := time.Now()\n\t\tdefer func() {\n\t\t\tmetricGoproxyListDuration.Observe(time.Since(t0).Seconds())\n\t\t}()\n\n\t\tmodPath, err := module.EscapePath(bs.Mod)\n\t\tif err != nil {\n\t\t\tc <- response{fmt.Errorf(\"bad module path: %v\", err), \"\", nil}\n\t\t\treturn\n\t\t}\n\t\tu := fmt.Sprintf(\"%s%s/@v/list\", config.GoProxy, modPath)\n\t\tmreq, err := http.NewRequestWithContext(r.Context(), \"GET\", u, nil)\n\t\tif err != nil {\n\t\t\tc <- response{fmt.Errorf(\"%w: preparing new http request: %v\", errServer, err), \"\", nil}\n\t\t\treturn\n\t\t}\n\t\tmreq.Header.Set(\"User-Agent\", userAgent)\n\t\tresp, err := http.DefaultClient.Do(mreq)\n\t\tif err != nil {\n\t\t\tc <- response{fmt.Errorf(\"%w: http request: %v\", errServer, err), \"\", nil}\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tif resp.StatusCode != 200 {\n\t\t\tmetricGoproxyListErrors.WithLabelValues(fmt.Sprintf(\"%d\", resp.StatusCode)).Inc()\n\t\t\tc <- response{fmt.Errorf(\"%w: http response from goproxy: %v\", errRemote, resp.Status), \"\", nil}\n\t\t\treturn\n\t\t}\n\t\tbuf, err := io.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tc <- response{fmt.Errorf(\"%w: reading versions from goproxy: %v\", errRemote, err), \"\", nil}\n\t\t\treturn\n\t\t}\n\t\tl := []versionLink{}\n\t\tfor _, s := range strings.Split(string(buf), \"\\n\") {\n\t\t\tif s != \"\" {\n\t\t\t\tvbs := bs\n\t\t\t\tvbs.Version = s\n\t\t\t\tsuccess := fileExists(filepath.Join(vbs.storeDir(), \"recordnumber\"))\n\t\t\t\tp := request{vbs, \"\", pageIndex}.link()\n\t\t\t\tlink := versionLink{s, p, success, p == xlink}\n\t\t\t\tl = append(l, link)\n\t\t\t}\n\t\t}\n\t\tsort.Slice(l, func(i, j int) bool {\n\t\t\treturn semver.Compare(l[i].Version, l[j].Version) > 0\n\t\t})\n\t\tvar latestVersion string\n\t\tif len(l) > 0 {\n\t\t\tlatestVersion = l[0].Version\n\t\t}\n\t\tc <- response{nil, latestVersion, l}\n\t}()\n\n\t// Non-emptiness means we'll serve the error page instead of doing a SSE request for events.\n\tvar output string\n\tif br == nil {\n\t\tif buf, err := readGzipFile(filepath.Join(bs.storeDir(), \"log.gz\")); err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tfailf(w, \"%w: reading log.gz: %v\", errServer, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// For not-exist, we'll continue below to build.\n\t\t} else {\n\t\t\toutput = string(buf)\n\t\t}\n\t}\n\n\t// Construct links to other goversions, targets.\n\ttype goversionLink struct {\n\t\tGoversion string\n\t\tURLPath string\n\t\tSuccess bool\n\t\tSupported bool\n\t\tActive bool\n\t}\n\tgoversionLinks := []goversionLink{}\n\tnewestAllowed, supported, remaining := installedSDK()\n\tfor _, goversion := range supported {\n\t\tgvbs := bs\n\t\tgvbs.Goversion = goversion\n\t\tsuccess := fileExists(filepath.Join(gvbs.storeDir(), \"recordnumber\"))\n\t\tp := request{gvbs, \"\", pageIndex}.link()\n\t\tgoversionLinks = append(goversionLinks, goversionLink{goversion, p, success, true, p == xlink})\n\t}\n\tfor _, goversion := range remaining {\n\t\tgvbs := bs\n\t\tgvbs.Goversion = goversion\n\t\tsuccess := fileExists(filepath.Join(gvbs.storeDir(), \"recordnumber\"))\n\t\tp := request{gvbs, \"\", pageIndex}.link()\n\t\tgoversionLinks = append(goversionLinks, goversionLink{goversion, p, success, false, p == xlink})\n\t}\n\n\ttype targetLink struct {\n\t\tGoos string\n\t\tGoarch string\n\t\tURLPath string\n\t\tSuccess bool\n\t\tActive bool\n\t}\n\ttargetLinks := []targetLink{}\n\tfor _, target := range targets.get() {\n\t\ttbs := bs\n\t\ttbs.Goos = target.Goos\n\t\ttbs.Goarch = target.Goarch\n\t\tsuccess := fileExists(filepath.Join(tbs.storeDir(), \"recordnumber\"))\n\t\tp := request{tbs, \"\", pageIndex}.link()\n\t\ttargetLinks = append(targetLinks, targetLink{target.Goos, target.Goarch, p, success, p == xlink})\n\t}\n\n\ttype variantLink struct {\n\t\tVariant string // \"default\" or \"stripped\"\n\t\tTitle string // Displayed on hover in UI.\n\t\tURLPath string\n\t\tSuccess bool\n\t\tActive bool\n\t}\n\tvar variantLinks []variantLink\n\taddVariant := func(v, title string, stripped bool) {\n\t\tvbs := bs\n\t\tvbs.Stripped = stripped\n\t\tsuccess := fileExists(filepath.Join(vbs.storeDir(), \"recordnumber\"))\n\t\tp := request{vbs, \"\", pageIndex}.link()\n\t\tvariantLinks = append(variantLinks, variantLink{v, title, p, success, p == xlink})\n\t}\n\taddVariant(\"default\", \"\", false)\n\taddVariant(\"stripped\", \"Symbol table and debug information stripped, reducing binary size.\", true)\n\n\tpkgGoDevURL := \"https://pkg.go.dev/\" + path.Join(bs.Mod+\"@\"+bs.Version, bs.Dir[1:]) + \"?tab=doc\"\n\n\tresp := <-c\n\n\tvar filesizeGz string\n\tif br == nil {\n\t\tbr = &buildResult{buildSpec: bs}\n\t} else {\n\t\tif info, err := os.Stat(filepath.Join(bs.storeDir(), \"binary.gz\")); err == nil {\n\t\t\tfilesizeGz = fmt.Sprintf(\"%.1f MB\", float64(info.Size())/(1024*1024))\n\t\t}\n\t}\n\n\tprependDir := xreq.Dir\n\tif prependDir == \"/\" {\n\t\tprependDir = \"\"\n\t}\n\n\tvar newerText, newerURL string\n\tif xreq.Goversion != newestAllowed && newestAllowed != \"\" && xreq.Version != resp.LatestVersion && resp.LatestVersion != \"\" {\n\t\tnewerText = \"A newer version of both this module and the Go toolchain is available\"\n\t} else if xreq.Version != resp.LatestVersion && resp.LatestVersion != \"\" {\n\t\tnewerText = \"A newer version of this module is available\"\n\t} else if xreq.Goversion != newestAllowed && newestAllowed != \"\" {\n\t\tnewerText = \"A newer Go toolchain version is available\"\n\t}\n\tif newerText != \"\" {\n\t\tnbs := bs\n\t\tnbs.Version = resp.LatestVersion\n\t\tnbs.Goversion = newestAllowed\n\t\tnewerURL = request{nbs, \"\", pageIndex}.link()\n\t}\n\n\tfavicon := \"/favicon.ico\"\n\tif output != \"\" {\n\t\tfavicon = \"/favicon-error.png\"\n\t} else if br.Sum == \"\" {\n\t\tfavicon = \"/favicon-building.png\"\n\t}\n\targs := map[string]interface{}{\n\t\t\"Favicon\": favicon,\n\t\t\"Success\": br.Sum != \"\",\n\t\t\"Sum\": br.Sum,\n\t\t\"Req\": xreq, // eg \"/\" or \"/cmd/x\"\n\t\t\"DirAppend\": xreq.appendDir(), // eg \"\" or \"cmd/x/\"\n\t\t\"DirPrepend\": prependDir, // eg \"\" or /cmd/x\"\n\t\t\"GoversionLinks\": goversionLinks,\n\t\t\"TargetLinks\": targetLinks,\n\t\t\"VariantLinks\": variantLinks,\n\t\t\"Mod\": resp,\n\t\t\"GoProxy\": config.GoProxy,\n\t\t\"DownloadFilename\": xreq.downloadFilename(),\n\t\t\"PkgGoDevURL\": pkgGoDevURL,\n\t\t\"GobuildVersion\": gobuildVersion,\n\t\t\"GobuildPlatform\": gobuildPlatform,\n\t\t\"VerifierKey\": config.VerifierKey,\n\t\t\"GobuildsOrgVerifierKey\": gobuildsOrgVerifierKey,\n\t\t\"NewerText\": newerText,\n\t\t\"NewerURL\": newerURL,\n\n\t\t// Whether we will do SSE request for updates.\n\t\t\"InProgress\": br.Sum == \"\" && output == \"\",\n\n\t\t// Non-empty on failure.\n\t\t\"Output\": output,\n\n\t\t// Below only meaningful when \"success\".\n\t\t\"Filesize\": fmt.Sprintf(\"%.1f MB\", float64(br.Filesize)/(1024*1024)),\n\t\t\"FilesizeGz\": filesizeGz,\n\t}\n\n\tif br.Sum == \"\" {\n\t\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\t}\n\n\tif err := buildTemplate.Execute(w, args); err != nil {\n\t\tfailf(w, \"%w: executing template: %v\", errServer, err)\n\t}\n}", "func home(version, commit, repo string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, _ *http.Request) {\n\t\tinfo := struct {\n\t\t\tVersion string `json:\"version\"`\n\t\t\tCommit string `json:\"commit\"`\n\t\t\tRepo string `json:\"repo\"`\n\t\t}{\n\t\t\tversion, commit, repo,\n\t\t}\n\n\t\tbody, err := json.Marshal(info)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not encode info data: %v\", err)\n\t\t\thttp.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(body)\n\t}\n}", "func GetProgramInfoLog(program Uint, bufSize Sizei, length *Sizei, infoLog []byte) {\n\tcprogram, _ := (C.GLuint)(program), cgoAllocsUnknown\n\tcbufSize, _ := (C.GLsizei)(bufSize), cgoAllocsUnknown\n\tclength, _ := (*C.GLsizei)(unsafe.Pointer(length)), cgoAllocsUnknown\n\tcinfoLog, _ := (*C.GLchar)(unsafe.Pointer((*sliceHeader)(unsafe.Pointer(&infoLog)).Data)), cgoAllocsUnknown\n\tC.glGetProgramInfoLog(cprogram, cbufSize, clength, cinfoLog)\n}", "func GetProgramPipelineInfoLog(pipeline uint32, bufSize int32, length *int32, infoLog *uint8) {\n\tsyscall.Syscall6(gpGetProgramPipelineInfoLog, 4, uintptr(pipeline), uintptr(bufSize), uintptr(unsafe.Pointer(length)), uintptr(unsafe.Pointer(infoLog)), 0, 0)\n}", "func (self *app) build() {\n\tvar done = make(chan bool)\n\tcmd.Loading(done)\n\n\t// * try build the application into rex-bin(.exe)\n\tcommand := exec.Command(\"go\", \"build\", \"-o\", self.binary)\n\tcommand.Dir = self.dir\n\tif e := command.Run(); e != nil {\n\t\tlog.Fatalf(\"Failed to compile the application: %v\", e)\n\t}\n\n\tdone <- true\n}", "func (c *Controller) BuildDatabase(w http.ResponseWriter, r *http.Request) {\n\n fmt.Fprintf(w, \"Building a database...\")\n c.monitor.buildDB()\n fmt.Fprintf(w, \"Done.\")\n\n}", "func Version() string {\n\treturn buildVersion\n}", "func GetVersion(c echo.Context) error {\n\n\t// This is being managed by config.go file. I don't like using empty interfaces\n\tversion := config.GuitaristReleaseVersion\n\n\tv := &Version{\n\t\tStatus: \"ok\",\n\t\tVersion: version,\n\t}\n\n\treturn c.JSON(http.StatusOK, v)\n}", "func GetBuild(c context.Context, host string, project types.ProjectName, path types.StreamPath) (*ui.MiloBuildLegacy, error) {\n\tas := AnnotationStream{\n\t\tProject: project,\n\t\tPath: path,\n\t}\n\tif err := as.Normalize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Setup our LogDog client.\n\tvar err error\n\tif as.Client, err = NewClient(c, host); err != nil {\n\t\treturn nil, errors.Annotate(err, \"generating LogDog Client\").Err()\n\t}\n\n\t// Load the Milo annotation protobuf from the annotation stream.\n\tswitch _, err := as.Fetch(c); errors.Unwrap(err) {\n\tcase nil, errNoEntries:\n\n\tcase coordinator.ErrNoSuchStream:\n\t\treturn nil, grpcutil.NotFoundTag.Apply(err)\n\n\tcase coordinator.ErrNoAccess:\n\t\treturn nil, grpcutil.PermissionDeniedTag.Apply(err)\n\n\tcase errNotMilo, errNotDatagram:\n\t\t// The user requested a LogDog url that isn't a Milo annotation.\n\t\treturn nil, grpcutil.InvalidArgumentTag.Apply(err)\n\n\tdefault:\n\t\treturn nil, errors.Annotate(err, \"failed to load stream\").Err()\n\t}\n\n\treturn as.toMiloBuild(c), nil\n}", "func versionRequest() {\n\t// if there are no other arguments display the version for sparts.\n\tif len(os.Args[1:]) == 1 {\n\t\t// Display version\n\t\tfmt.Printf(\" %s version: %s\\n\", filepath.Base(os.Args[0]), _VERSION)\n\t\treturn\n\t}\n\t// there is an additional argument\n\tswitch os.Args[2] {\n\tcase \"--help\", \"-help\", \"-h\":\n\t\t// Display help\n\t\tfmt.Println(_VERSION_HELP_CONTENT)\n\tcase \"--all\", \"-a\":\n\t\tfmt.Printf(\"%s version: %s data model: %s\\n\", filepath.Base(os.Args[0]), _VERSION, _DB_Model)\n\tdefault:\n\t\tfmt.Printf(\" '%s' is not a valid version option. Try --help\\n\", os.Args[2])\n\t}\n\n}", "func projectHandler(w http.ResponseWriter, r *http.Request) {\n\n\thelper.GetProjects(w, r)\n\n}", "func GetBuildDate() string {\n\tv := Map[\"buildDate\"]\n\treturn v\n}", "func PrintBuildInfo() string {\n\tbuildInfo := &BuildInfo{Branch, Sha, Version}\n\tout, err := yaml.Marshal(buildInfo)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(out)\n}" ]
[ "0.64320457", "0.6398367", "0.6037579", "0.5929717", "0.58946925", "0.58839583", "0.5821352", "0.5800616", "0.57839584", "0.5774395", "0.57712066", "0.5636525", "0.5602506", "0.55906236", "0.55887514", "0.55836105", "0.5559641", "0.5559641", "0.555559", "0.5506469", "0.5487685", "0.54552495", "0.5402266", "0.54005545", "0.53969365", "0.53873736", "0.53809565", "0.5377902", "0.537733", "0.5374834", "0.5359448", "0.535781", "0.535598", "0.5354829", "0.53512895", "0.53433186", "0.53222096", "0.5316579", "0.5310801", "0.5302861", "0.52977914", "0.5296742", "0.52828336", "0.5281332", "0.5277229", "0.52633756", "0.52583075", "0.52568024", "0.52511454", "0.5237061", "0.52342516", "0.5225736", "0.5208116", "0.52056277", "0.51941586", "0.51941586", "0.5191083", "0.5171137", "0.51697737", "0.5166993", "0.5156803", "0.51536894", "0.51305014", "0.5127809", "0.51275045", "0.51168287", "0.511124", "0.51064676", "0.5100664", "0.5100349", "0.5076235", "0.5074255", "0.5074072", "0.5073556", "0.50593436", "0.5053314", "0.50483155", "0.50362355", "0.50342757", "0.5033278", "0.50256974", "0.50248224", "0.50226647", "0.5014317", "0.50055337", "0.50041556", "0.5001812", "0.5001288", "0.49968722", "0.49954313", "0.499197", "0.4987729", "0.49748513", "0.4972583", "0.4971679", "0.4971133", "0.49690068", "0.4968402", "0.49658298", "0.49648705" ]
0.6375576
2
After proto.Merge called two lists are merged and we cannot be sure of order of the elements and if the element is from the Mesh or from the Dataplane resource.
func (d *DataplaneResource) mergeLists( meshCfg *mesh_proto.PrometheusMetricsBackendConfig, dpCfg *mesh_proto.PrometheusMetricsBackendConfig, ) { aggregate := make(map[string]*mesh_proto.PrometheusAggregateMetricsConfig) for _, conf := range meshCfg.Aggregate { aggregate[conf.Name] = conf } // override Mesh aggregate configuration with Dataplane for _, conf := range dpCfg.Aggregate { aggregate[conf.Name] = conf } // contains all the elements for Dataplane configuration var unduplicatedConfig []*mesh_proto.PrometheusAggregateMetricsConfig for _, value := range aggregate { unduplicatedConfig = append(unduplicatedConfig, value) } // we cannot set the same values because they are going to be appended meshCfg.Aggregate = []*mesh_proto.PrometheusAggregateMetricsConfig{} dpCfg.Aggregate = unduplicatedConfig }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m MessageDescriptorMap) Merge(other MessageDescriptorMap) {\n\tfor id, other := range other {\n\t\tif m[id] == nil {\n\t\t\tm[id] = other\n\t\t} else {\n\t\t\tif other.Translations[defaultLanguage] != m[id].Translations[defaultLanguage] {\n\t\t\t\tm[id].updated = true\n\t\t\t}\n\t\t\tfor language, translation := range other.Translations {\n\t\t\t\tif language == defaultLanguage {\n\t\t\t\t\tcontinue // This one is set from the Define.\n\t\t\t\t}\n\t\t\t\tm[id].Translations[language] = translation\n\t\t\t}\n\t\t}\n\t}\n}", "func (j *jointRequest) merge(from *jointRequest) {\n\tfor _, tile := range from.tiles {\n\t\tj.tiles = append(j.tiles, tile)\n\t}\n}", "func (i *instance) merge(seq int, dep map[paxi.ID]int) {\n\tif seq > i.seq {\n\t\ti.seq = seq\n\t\ti.changed = true\n\t}\n\tfor id, d := range dep {\n\t\tif d > i.dep[id] {\n\t\t\ti.dep[id] = d\n\t\t\ti.changed = true\n\t\t}\n\t}\n}", "func Merge(resources ...v1.ResourceList) v1.ResourceList {\n\tresult := v1.ResourceList{}\n\tfor _, resourceList := range resources {\n\t\tfor resourceName, quantity := range resourceList {\n\t\t\tcurrent := result[resourceName]\n\t\t\tcurrent.Add(quantity)\n\t\t\tresult[resourceName] = current\n\t\t}\n\t}\n\treturn result\n}", "func storeDescMerge(srvcs []onet.Service, el *onet.Roster, nbr int) ([]*PopDesc,\n\t[]abstract.Point, []*Service, []abstract.Scalar) {\n\trosters := make([]*onet.Roster, len(el.List)/2)\n\tfor i := 0; i < len(el.List); i += 2 {\n\t\trosters[i/2] = onet.NewRoster(el.List[i : i+2])\n\t}\n\tdescs := make([]*PopDesc, len(rosters))\n\tcopy_descs := make([]*ShortDesc, len(rosters))\n\tfor i := range descs {\n\t\tdescs[i] = &PopDesc{\n\t\t\tName: \"name\",\n\t\t\tDateTime: \"2017-07-31 00:00\",\n\t\t\tLocation: fmt.Sprintf(\"city%d\", i),\n\t\t\tRoster: rosters[i],\n\t\t}\n\t\tcopy_descs[i] = &ShortDesc{\n\t\t\tLocation: fmt.Sprintf(\"city%d\", i),\n\t\t\tRoster: rosters[i],\n\t\t}\n\t}\n\tfor _, desc := range descs {\n\t\tdesc.Parties = copy_descs\n\t}\n\tatts := make([]abstract.Point, nbr)\n\n\tfor i := range atts {\n\t\tkp := config.NewKeyPair(network.Suite)\n\t\tatts[i] = kp.Public\n\t}\n\n\tpubs := make([]abstract.Point, len(srvcs))\n\tprivs := make([]abstract.Scalar, len(srvcs))\n\tfor i, _ := range srvcs {\n\t\tkp := config.NewKeyPair(network.Suite)\n\t\tpubs[i], privs[i] = kp.Public, kp.Secret\n\t}\n\tsret := []*Service{}\n\tfor i, s := range srvcs {\n\t\tsret = append(sret, s.(*Service))\n\t\ts.(*Service).data.Public = pubs[i]\n\t\tdesc := descs[i/2]\n\t\thash := desc.Hash()\n\t\tsig, err := crypto.SignSchnorr(network.Suite, privs[i], hash)\n\t\tlog.ErrFatal(err)\n\t\ts.(*Service).StoreConfig(&StoreConfig{desc, sig})\n\t}\n\treturn descs, atts, sret, privs\n}", "func (b *Bag) Merge(from *Bag) {\n\tb.Add(from.Items()...)\n}", "func Merge(datas interfaces.Sortable) interfaces.Sortable {\n\tmergeSort(datas, 0, datas.Len()-1)\n\treturn datas\n}", "func (a *API) Merge(other API) {\n\tif a.Short == \"\" {\n\t\ta.Short = other.Short\n\t}\n\n\tif a.Long == \"\" {\n\t\ta.Long = other.Long\n\t}\n\n\ta.Operations = append(a.Operations, other.Operations...)\n}", "func (sp *Properties) Merge(merge api.Properties) {\n\tfor _, id := range merge.Order() {\n\t\tprop, _ := merge.Get(id)\n\t\tsp.Add(prop)\n\t}\n}", "func (h HyperparameterV0) Merge(other interface{}) interface{} {\n\t// Never merge partial hyperparameters.\n\treturn h\n}", "func (b *Buffer) Merge(bs ...Buffer) {\n\tfor _, buf := range bs {\n\t\tfor p, v := range buf.CellMap {\n\t\t\tb.Set(p.X, p.Y, v)\n\t\t}\n\t\tb.SetArea(b.Area.Union(buf.Area))\n\t}\n}", "func (v *VersionVector) Merge(other *VersionVector) {\n\tother.REach(func(actor string, t LamportTime) {\n\t\tv.Witness(actor, t)\n\t})\n}", "func (v *ValidationErrors) Merge(errs *ValidationErrors) {\n\tv.Add(*errs...)\n}", "func (l *AttributeList) Merge(other AttributeList) AttributeList {\n\tif l.Len() == 0 {\n\t\treturn other\n\t}\n\tif other.Len() == 0 {\n\t\treturn *l\n\t}\n\tl.last.Next = other.first\n\tl.last = other.last\n\tl.length += other.Len()\n\treturn *l\n}", "func (d PacketData) Merge(oth PacketData) {\n\toth.pk.buf.TrimFront(int64(oth.pk.dataOffset()))\n\td.pk.buf.Merge(&oth.pk.buf)\n}", "func (b Binding) Merge(b2 Binding) Binding {\n\n\tresult := Binding{}\n\n\tfor k, v := range b {\n\t\tresult[k] = v\n\t}\n\n\tfor k, v := range b2 {\n\t\tresult[k] = v\n\t}\n\n\treturn result\n}", "func (s *Storage) Merge(ctx context.Context,\n\tconv types.UnboxConversationInfo, uid gregor1.UID, msgs []chat1.MessageUnboxed) (res MergeResult, err Error) {\n\tvar ierr error\n\tdefer s.Trace(ctx, &ierr, \"Merge\")()\n\tdefer func() { ierr = s.castInternalError(err) }()\n\treturn s.MergeHelper(ctx, conv, uid, msgs, nil)\n}", "func (b *BaseImpl) Merge() {\n\tb.Flatten()\n}", "func (rc *ResourceCollection) Merge(other *ResourceCollection) {\n\tfor resourceDomain, resourceKinds := range rc.collection { // e.g. for AWS\n\t\tif _, exists := other.collection[resourceDomain]; !exists { // only A has AWS\n\t\t\trc.collection[resourceDomain] = resourceKinds\n\t\t} else { // both have AWS\n\t\t\trc.ensureResourcePathExists(resourceDomain, \"\")\n\n\t\t\tfor resourceKind, resources := range rc.collection[resourceDomain] { // e.g. for EC2 instances\n\t\t\t\tif _, exists := other.collection[resourceDomain][resourceKind]; !exists { // only A has any EC2 instances\n\t\t\t\t\trc.collection[resourceDomain][resourceKind] = resources\n\t\t\t\t} else { // both have some EC2 instances\n\t\t\t\t\trc.ensureResourcePathExists(resourceDomain, resourceKind)\n\n\t\t\t\t\tfor id, resource := range rc.collection[resourceDomain][resourceKind] { // e.g. for EC2 instance with ID i-abc123def456\n\t\t\t\t\t\trc.collection[resourceDomain][resourceKind][id] = resource\n\t\t\t\t\t}\n\n\t\t\t\t\tfor id, resource := range other.collection[resourceDomain][resourceKind] {\n\t\t\t\t\t\trc.collection[resourceDomain][resourceKind][id] = resource\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor resourceKind, resources := range other.collection[resourceDomain] { // e.g. for security groups\n\t\t\t\tif _, exists := rc.collection[resourceDomain][resourceKind]; !exists { // only B has any security groups\n\t\t\t\t\trc.collection[resourceDomain][resourceKind] = resources\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor resourceDomain, resourceKinds := range other.collection { // e.g. for GCP\n\t\tif _, exists := rc.collection[resourceDomain]; !exists { // only B has GCP\n\t\t\trc.collection[resourceDomain] = resourceKinds\n\t\t}\n\t}\n}", "func (p *Port) Merge() bool {\n\tmerged := false\n\n\tif p.src != nil {\n\t\tfor dest := range p.dests {\n\t\t\tp.src.dests[dest] = true\n\t\t\tdest.src = p.src\n\t\t\tdest.strSrc = p.strSrc\n\t\t\tmerged = true\n\t\t}\n\t\tp.src.Disconnect(p)\n\t} else if len(p.dests) != 0 {\n\t\tfor dest := range p.dests {\n\t\t\tif dest.itemType != TYPE_TRIGGER {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tp.strSrc.dests[dest] = true\n\t\t\tdest.strSrc = p.strSrc\n\t\t\tmerged = true\n\t\t}\n\t}\n\n\tif p.sub != nil {\n\t\tmerged = p.sub.Merge() || merged\n\t}\n\n\tfor _, sub := range p.subs {\n\t\tmerged = sub.Merge() || merged\n\t}\n\n\treturn merged\n}", "func mergeUpdate(p, q *SlugResponse, t float64) SlugResponsePlusPlus {\n\t// Make of map of strings\n\t// to buses\n\tmb := map[string]Data{}\n\t// Loop through first\n\t// ping\n\tfor _, bus := range *p {\n\t\t// Map the bus ID to the\n\t\t// bus datastructure\n\t\tmb[bus.ID] = bus\n\t}\n\t// Prepare a result\n\tresult := SlugResponsePlusPlus{}\n\t// Loop through the second ping\n\tfor _, pingTwoBus := range *q {\n\t\t// Make a bus with angles and speed\n\t\td := DataPlusPlus{}\n\t\t// Add the buses' data to the bus++?\n\t\td.Data = pingTwoBus\n\t\t// Check if the current bus exists in ping one\n\t\tif pingOneBus, contains := mb[d.ID]; contains {\n\t\t\t// If it does, calculate its distance, speed , and angle\n\t\t\tdistance := geo.Dist(pingOneBus.Lat, pingOneBus.Lon, pingTwoBus.Lat, pingTwoBus.Lon)\n\t\t\td.Speed = geo.Speed(distance, t)\n\t\t\td.Angle = geo.Dir(pingOneBus.Lat, pingOneBus.Lon, pingTwoBus.Lat, pingTwoBus.Lon)\n\t\t}\n\t\t// push the bus to the result\n\t\tresult = append(result, d)\n\t}\n\treturn result\n}", "func (e *dataUsageEntry) merge(other dataUsageEntry) {\n\te.Objects += other.Objects\n\te.Versions += other.Versions\n\te.Size += other.Size\n\tors := other.ReplicationStats\n\tempty := replicationStats{}\n\tif ors != nil && *ors != empty {\n\t\tif e.ReplicationStats == nil {\n\t\t\te.ReplicationStats = &replicationStats{}\n\t\t}\n\t\te.ReplicationStats.PendingSize += other.ReplicationStats.PendingSize\n\t\te.ReplicationStats.FailedSize += other.ReplicationStats.FailedSize\n\t\te.ReplicationStats.ReplicatedSize += other.ReplicationStats.ReplicatedSize\n\t\te.ReplicationStats.ReplicaSize += other.ReplicationStats.ReplicaSize\n\t\te.ReplicationStats.PendingCount += other.ReplicationStats.PendingCount\n\t\te.ReplicationStats.FailedCount += other.ReplicationStats.FailedCount\n\n\t}\n\n\tfor i, v := range other.ObjSizes[:] {\n\t\te.ObjSizes[i] += v\n\t}\n}", "func (so *Operations) Merge(merge api.Operations) {\n\tfor _, id := range merge.Order() {\n\t\top, _ := merge.Get(id)\n\t\tso.Add(op)\n\t}\n}", "func (a *Ports) Merge(b *Ports) *Ports {\n\tresult := *a\n\n\tif b.HTTP != 0 {\n\t\tresult.HTTP = b.HTTP\n\t}\n\treturn &result\n}", "func (inj *Injector) Merge(i *Injector, override bool) error {\n\tfor name, v := range i.data {\n\t\tif _, ok := inj.data[name]; ok && !override {\n\t\t\treturn ErrInjectorSetTwicePointer(v)\n\t\t}\n\t\tinj.data[name] = v\n\t}\n\treturn nil\n}", "func (res *ruleMatchResults) merge(other ruleMatchResults) *ruleMatchResults {\n\tif res.cutoverNanos < other.cutoverNanos {\n\t\tres.cutoverNanos = other.cutoverNanos\n\t}\n\tres.pipelines = append(res.pipelines, other.pipelines...)\n\treturn res\n}", "func merge(a, b []model.Fingerprint) []model.Fingerprint {\n\tresult := make([]model.Fingerprint, 0, len(a)+len(b))\n\ti, j := 0, 0\n\tfor i < len(a) && j < len(b) {\n\t\tif a[i] < b[j] {\n\t\t\tresult = append(result, a[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tresult = append(result, b[j])\n\t\t\tj++\n\t\t}\n\t}\n\tfor ; i < len(a); i++ {\n\t\tresult = append(result, a[i])\n\t}\n\tfor ; j < len(b); j++ {\n\t\tresult = append(result, b[j])\n\t}\n\treturn result\n}", "func (tr *trooper) merge() {\n\ttr.trash()\n\ttr.neo = tr.part.AddPart().SetScale(0.5, 0.5, 0.5)\n\tm := tr.neo.MakeModel(\"flata\", \"msh:cube\", \"mat:tblue\")\n\tm.SetUniform(\"fd\", 1000)\n\ttr.addCenter()\n}", "func merge(rw http.ResponseWriter, req *http.Request) {\r\n\t// Decode the POST body\r\n\tdecoder := json.NewDecoder(req.Body)\r\n\tvar model distributed.MergeRequestModel\r\n\terr := decoder.Decode(&model)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tleft := model.Left\r\n\tright := model.Right\r\n\tsize, i, j := len(left)+len(right), 0, 0\r\n\tslice := make([]int, size, size)\r\n\r\n\tfor k := 0; k < size; k++ {\r\n\t\tif i > len(left)-1 && j <= len(right)-1 {\r\n\t\t\tslice[k] = right[j]\r\n\t\t\tj++\r\n\t\t} else if j > len(right)-1 && i <= len(left)-1 {\r\n\t\t\tslice[k] = left[i]\r\n\t\t\ti++\r\n\t\t} else if left[i] < right[j] {\r\n\t\t\tslice[k] = left[i]\r\n\t\t\ti++\r\n\t\t} else {\r\n\t\t\tslice[k] = right[j]\r\n\t\t\tj++\r\n\t\t}\r\n\t}\r\n\r\n\tresponseModel := distributed.MergeResponseModel{slice}\r\n\r\n\t// Parse the response model into a writable format\r\n\tresString, err := json.Marshal(responseModel)\r\n\r\n\trw.Write(resString)\r\n}", "func (bh* BinomialHeap) Merge(other *BinomialHeap) {\n bh.size += other.size\n\n for _, child := range nodeIterator(other.forest_head) {\n removeFromLinkedList(&other.forest_head, child)\n bh.insert(child)\n }\n}", "func (ops *SimpleOperations) Merge(merge Operations) {\n\tops.safe()\n\n\tfor _, operation := range merge.Order() {\n\t\tmergeOperation, _ := merge.Get(operation)\n\t\tops.Add(mergeOperation)\n\t}\n}", "func TestMergeSorted(t *testing.T) {\n\tunittest.SmallTest(t)\n\n\tfirst := []*TriageStatus{\n\t\t{\n\t\t\tName: FirstTest,\n\t\t\tDiameter: 4,\n\t\t\tPos: 2,\n\t\t\tNeg: 3,\n\t\t\tUntriaged: 1,\n\t\t\tUntHashes: types.DigestSlice{AlphaDigest},\n\t\t\tNum: 6,\n\t\t\tCorpus: \"gm\",\n\t\t\tBlame: []blame.WeightedBlame{\n\t\t\t\t{\n\t\t\t\t\tAuthor: \"[email protected]\",\n\t\t\t\t\tProb: 1.00,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: SecondTest,\n\t\t\tDiameter: 14,\n\t\t\tPos: 12,\n\t\t\tNeg: 13,\n\t\t\tUntriaged: 1,\n\t\t\tUntHashes: types.DigestSlice{BetaDigest},\n\t\t\tNum: 26,\n\t\t\tCorpus: \"gm\",\n\t\t\tBlame: []blame.WeightedBlame{\n\t\t\t\t{\n\t\t\t\t\tAuthor: \"[email protected]\",\n\t\t\t\t\tProb: 0.5,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAuthor: \"[email protected]\",\n\t\t\t\t\tProb: 0.5,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tsecond := []*TriageStatus{\n\t\t{\n\t\t\tName: FirstTest,\n\t\t\tDiameter: 24,\n\t\t\tPos: 22,\n\t\t\tNeg: 23,\n\t\t\tUntriaged: 0,\n\t\t\tUntHashes: types.DigestSlice{},\n\t\t\tNum: 45,\n\t\t\tCorpus: \"gm\",\n\t\t\tBlame: []blame.WeightedBlame{},\n\t\t},\n\t\t{\n\t\t\tName: SecondTest,\n\t\t\tDiameter: 14,\n\t\t\tPos: 12,\n\t\t\tNeg: 13,\n\t\t\tUntriaged: 1,\n\t\t\tUntHashes: types.DigestSlice{BetaDigest},\n\t\t\tNum: 26,\n\t\t\tCorpus: \"zzz\",\n\t\t\tBlame: []blame.WeightedBlame{\n\t\t\t\t{\n\t\t\t\t\tAuthor: \"[email protected]\",\n\t\t\t\t\tProb: 0.5,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAuthor: \"[email protected]\",\n\t\t\t\t\tProb: 0.5,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: ThirdTest,\n\t\t\tDiameter: 34,\n\t\t\tPos: 32,\n\t\t\tNeg: 33,\n\t\t\tUntriaged: 1,\n\t\t\tUntHashes: types.DigestSlice{GammaDigest},\n\t\t\tNum: 66,\n\t\t\tCorpus: \"gm\",\n\t\t\tBlame: []blame.WeightedBlame{\n\t\t\t\t{\n\t\t\t\t\tAuthor: \"[email protected]\",\n\t\t\t\t\tProb: 1.0,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tres := MergeSorted(first, second)\n\t// first and second should remain unchanged\n\trequire.Len(t, first, 2)\n\tassert.Equal(t, FirstTest, first[0].Name)\n\tassert.Equal(t, SecondTest, first[1].Name)\n\trequire.Len(t, second, 3)\n\tassert.Equal(t, FirstTest, second[0].Name)\n\tassert.Equal(t, SecondTest, second[1].Name)\n\tassert.Equal(t, ThirdTest, second[2].Name)\n\n\trequire.Equal(t, []*TriageStatus{second[0], first[1], second[1], second[2]}, res)\n}", "func (s *segment) merge(oth *segment) {\n\ts.pkt.Data().Merge(oth.pkt.Data())\n\ts.dataMemSize = s.pkt.MemSize()\n\toth.dataMemSize = oth.pkt.MemSize()\n}", "func (ss MultiRenderer) Append(elements ...Renderer) MultiRenderer {\n\t// Copy ss, to make sure no memory is overlapping between input and\n\t// output. See issue #97.\n\tresult := append(MultiRenderer{}, ss...)\n\n\tresult = append(result, elements...)\n\treturn result\n}", "func (m *merger) Merge(rawManifests []*apprclient.OperatorMetadata) (manifests *RawOperatorManifestData, err error) {\n\tallErrors := []error{}\n\tmerged := StructuredOperatorManifestData{}\n\n\tfor _, rawManifest := range rawManifests {\n\t\tmanifest, err := m.parser.Unmarshal(rawManifest.RawYAML)\n\t\tif err != nil {\n\t\t\tallErrors = append(allErrors, err)\n\t\t\tm.logger.Infof(\"skipping repository due to parsing error - %s\", rawManifest.RegistryMetadata)\n\n\t\t\tcontinue\n\t\t}\n\n\t\tmerged.Packages = append(merged.Packages, manifest.Packages...)\n\t\tmerged.CustomResourceDefinitions = append(merged.CustomResourceDefinitions, manifest.CustomResourceDefinitions...)\n\t\tmerged.ClusterServiceVersions = append(merged.ClusterServiceVersions, manifest.ClusterServiceVersions...)\n\t}\n\n\tmanifests, err = m.parser.Marshal(&merged)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\terr = utilerrors.NewAggregate(allErrors)\n\treturn\n}", "func (r *Record) mergeObjects(other *Record) {\n\tdebug.Assert(r.Name == other.Name, r.Name+\" vs \"+other.Name)\n\tif r.Key == nil && other.Key != nil {\n\t\tr.Key = other.Key\n\t}\n\tr.Objects = append(r.Objects, other.Objects...)\n}", "func (m *resourceInfo) merge(info IPMetadata, src source.Source) {\n\tswitch info := info.(type) {\n\tcase labels.Labels:\n\t\tl := labels.NewLabelsFromModel(nil)\n\t\tl.MergeLabels(info)\n\t\tm.labels = l\n\tdefault:\n\t\tlog.Errorf(\"BUG: Invalid IPMetadata passed to ipinfo.merge(): %+v\", info)\n\t\treturn\n\t}\n\tm.source = src\n}", "func (el *Elements) Append(d Elements) {\n\tswitch el.Type {\n\tcase part3.Int32:\n\t\tel.I32 = append(el.I32, d.I32...)\n\tcase part3.Float32:\n\t\tel.F32 = append(el.F32, d.F32...)\n\tcase part3.Float64:\n\t\tel.F64 = append(el.F64, d.F64...)\n\t}\n}", "func (m *Metadata) Merge(src proto.Message) {\n\tmetadata, ok := src.(*Metadata)\n\tif !ok {\n\t\treturn\n\t}\n\t*m = *metadata\n\t// Manually clone expiry timestamp as proto.Clone\n\t// cannot cope with values that contain unexported\n\t// attributes (as time.Time does)\n\tif metadata.Expires != nil {\n\t\texpires := *metadata.Expires\n\t\tm.Expires = &expires\n\t}\n\tif len(metadata.Labels) != 0 {\n\t\tm.Labels = make(map[string]string)\n\t\tfor k, v := range metadata.Labels {\n\t\t\tm.Labels[k] = v\n\t\t}\n\t}\n}", "func (nl *NodeList) Merge(other *NodeList) {\n\tif other == nil || other.Front() == nil || other.length == 0 {\n\t\treturn\n\t}\n\n\tif nl.front == nil {\n\t\tnl.front = other.Front()\n\t\tnl.back = other.Back()\n\t\tnl.length = other.length\n\t\treturn\n\t}\n\tif other.length == 1 {\n\t\tnl.Insert(other.Front())\n\t\treturn\n\t}\n\tnl.back.Next = other.Front()\n\tnl.back.Next.prev = nl.back\n\tnl.back = other.Back()\n\n\tnl.length += other.length\n}", "func (mdl *Model) Merge(model std.Model) error {\n\treturn nil\n}", "func Merge(l error, r error) error {\n\tif l == nil {\n\t\treturn r\n\t}\n\tif r == nil {\n\t\treturn l\n\t}\n\n\tif c, ok := l.(*collection); ok {\n\t\tc.append(r)\n\t\treturn c\n\t}\n\tif c, ok := r.(*collection); ok {\n\t\tc.insertFront(l)\n\t\treturn c\n\t}\n\tc := newCollection()\n\tc.append(l)\n\tc.append(r)\n\treturn c\n}", "func (c *Aggregator) Merge(oa aggregator.Aggregator, desc *sdkapi.Descriptor) error {\n\to, _ := oa.(*Aggregator)\n\tif o == nil {\n\t\treturn aggregator.NewInconsistentAggregatorError(c, oa)\n\t}\n\n\tc.samples = combine(c.samples, o.samples)\n\treturn nil\n}", "func (engine *Engine) Merge(e *Engine) error {\n\tengine.engines = append(engine.engines, e)\n\t//fmt.Printf(\"engine to merge\\n%+v\\n\", e)\n\t//for _, x := range e.Groups() {\n\t//\tfmt.Printf(\"group: \\n%+v\\n\", x)\n\t//}\n\treturn nil\n}", "func (h *HandshakeFragment) Merge(other *HandshakeFragment) error {\n\tpanic(\"TODO\")\n}", "func (o *Object) Merge(other *Object) *Object {\n\tres := o\n\tfor _, nat := range *other {\n\t\tres.Set(nat.Name, DupAtt(nat.Attribute))\n\t}\n\treturn res\n}", "func TestMergeTwoLists_Example4(t *testing.T) {\n\tl1 := &ListNode{\n\t\tVal: 1,\n\t\tNext: &ListNode{\n\t\t\tVal: 1,\n\t\t\tNext: &ListNode{\n\t\t\t\tVal: 2,\n\t\t\t\tNext: &ListNode{\n\t\t\t\t\tVal: 3,\n\t\t\t\t\tNext: &ListNode{\n\t\t\t\t\t\tVal: 3,\n\t\t\t\t\t\tNext: &ListNode{\n\t\t\t\t\t\t\tVal: 4,\n\t\t\t\t\t\t\tNext: &ListNode{\n\t\t\t\t\t\t\t\tVal: 5,\n\t\t\t\t\t\t\t\tNext: nil,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tl2 := &ListNode{\n\t\tVal: 0,\n\t\tNext: nil,\n\t}\n\n\t// [1,1,2,3,4,4]\n\texpectedOutput := &ListNode{\n\t\tVal: 0,\n\t\tNext: l1,\n\t}\n\n\toutput := mergeTwoLists_v2(l1, l2)\n\n\tif !reflect.DeepEqual(expectedOutput, output) {\n\t\tt.Error(\"Expected List does not match Actual\")\n\t}\n}", "func (dst *Workers) Merge(src Workers) {\n\tif dst == nil || len(src) == 0 {\n\t\treturn\n\t}\n\n\tcopied := *dst\n\tcopied = append(copied, src...)\n\n\tregistry := map[string]int{}\n\tfor i := len(copied); i > 0; i-- {\n\t\tregistry[copied[i-1].Name] = i - 1\n\t}\n\tunique := copied[:0]\n\tfor i, worker := range copied {\n\t\torigin := registry[worker.Name]\n\t\tif i == origin {\n\t\t\tunique = append(unique, worker)\n\t\t\tcontinue\n\t\t}\n\t\tunique[origin].Merge(worker)\n\t}\n\n\t*dst = unique\n}", "func (s *Cluster) merge(buf []byte) (mesh.GossipData, error) {\n\n\t// Decode the state we just received\n\tother, err := decodeSubscriptionState(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Merge and get the delta\n\tdelta := s.state.Merge(other)\n\tfor k, v := range other.All() {\n\n\t\t// Decode the event\n\t\tev, err := decodeSubscriptionEvent(k.(string))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Get the peer to use\n\t\tpeer := s.FindPeer(ev.Peer)\n\n\t\t// If the subscription is added, notify (TODO: use channels)\n\t\tif v.IsAdded() && peer.onSubscribe(k.(string), ev.Ssid) {\n\t\t\ts.OnSubscribe(ev.Ssid, peer)\n\t\t}\n\n\t\t// If the subscription is removed, notify (TODO: use channels)\n\t\tif v.IsRemoved() && peer.onUnsubscribe(k.(string), ev.Ssid) {\n\t\t\ts.OnUnsubscribe(ev.Ssid, peer)\n\t\t}\n\t}\n\n\treturn delta, nil\n}", "func (d PacketData) MergeBuffer(b *buffer.Buffer) {\n\td.pk.buf.Merge(b)\n}", "func (l *List) Merge(l2 *List) {\n\tif l.length == 0 {\n\t\tl.Lock()\n\t\tl2.Lock()\n\t\tl = l2\n\t\tl.Unlock()\n\t\tl2.Unlock()\n\t\treturn\n\t}\n\n\tif l2.length == 0 {\n\t\treturn\n\t}\n\tl.Lock()\n\tl2.Lock()\n\tl.tail.next = l2.head\n\tl2.head.prev = l.tail\n\tl.tail = l2.tail\n\tl.length += l2.length\n\tl.Unlock()\n\tl2.Unlock()\n}", "func mergeResource(res *Resource, resources map[Version][]*Resource, version *Version) *Resource {\n\tresourceAcrossVersions := make(map[Version]*Resource)\n\tfor v, resList := range resources {\n\t\tfor _, r := range resList {\n\t\t\t// Name is not unique, TerraformName must be\n\t\t\tif r.TerraformName() == res.TerraformName() {\n\t\t\t\tresourceAcrossVersions[v] = r\n\t\t\t}\n\t\t}\n\t}\n\tga, gaExists := resourceAcrossVersions[GA_VERSION]\n\tbeta, betaExists := resourceAcrossVersions[BETA_VERSION]\n\talpha, alphaExists := resourceAcrossVersions[ALPHA_VERSION]\n\tif alphaExists {\n\t\treturn alpha\n\t}\n\tif gaExists {\n\t\tif betaExists {\n\t\t\treturn mergeResources(ga, beta)\n\t\t}\n\t\treturn ga\n\t}\n\tbeta.Description = fmt.Sprintf(\"Beta only: %s\", beta.Description)\n\treturn beta\n}", "func (orchCol *OrchestratorCollection) Merge(otherOrchCol *OrchestratorCollection) *OrchestratorCollection {\n\n\tfor _, orch := range otherOrchCol.Orchestrators {\n\t\torchCol.Orchestrators = append(orchCol.Orchestrators, orch)\n\t}\n\n\treturn orchCol\n}", "func (dst *Worker) Merge(src Worker) {\n\tif dst == nil || dst.Name != src.Name {\n\t\treturn\n\t}\n\n\tif src.Enabled != nil {\n\t\tdst.Enabled = src.Enabled\n\t}\n\tif src.Command != \"\" {\n\t\tdst.Command = src.Command\n\t}\n\tif len(src.Commands) > 0 {\n\t\tdst.Commands = strings.Unique(append(dst.Commands, src.Commands...))\n\t}\n\tif src.Replicas != 0 {\n\t\tdst.Replicas = src.Replicas\n\t}\n\tif src.LivenessProbe != \"\" {\n\t\tdst.LivenessProbe = src.LivenessProbe\n\t}\n\tif src.Size != \"\" {\n\t\tdst.Size = src.Size\n\t}\n\n\tif src.Resources != nil && dst.Resources == nil {\n\t\tdst.Resources = new(Resources)\n\t}\n\tdst.Resources.Merge(src.Resources)\n}", "func (a *Addresses) Merge(b *Addresses) *Addresses {\n\tresult := *a\n\n\tif b.HTTP != \"\" {\n\t\tresult.HTTP = b.HTTP\n\t}\n\treturn &result\n}", "func TestMergeTwoLists_Example2(t *testing.T) {\n\toutput := mergeTwoLists_v2(nil, nil)\n\n\tif output != nil {\n\t\tt.Errorf(\"Expected: nil. Actual: %v\", output)\n\t}\n}", "func (m Metaitems) Merge(items Metaitems, strategy MetadataStrategy) Metaitems {\nOUTER:\n\tfor _, newItem := range items {\n\t\tfor _, oldItem := range m {\n\t\t\tif oldItem.Source == newItem.Source {\n\t\t\t\tif oldItem.Metadata != nil {\n\t\t\t\t\toldItem.Metadata = oldItem.Metadata.Merge(newItem.Metadata, strategy)\n\t\t\t\t}\n\t\t\t\tcontinue OUTER\n\t\t\t}\n\t\t}\n\n\t\tm = append(m, newItem)\n\t}\n\n\treturn m\n}", "func (dst *Hosts) Merge(src Hosts) {\n\tif dst == nil || len(src) == 0 {\n\t\treturn\n\t}\n\n\tcopied := *dst\n\tcopied = append(copied, src...)\n\n\tregistry := map[string]int{}\n\tfor i := len(copied); i > 0; i-- {\n\t\tregistry[copied[i-1].Name] = i - 1\n\t}\n\tunique := copied[:0]\n\tfor i, host := range copied {\n\t\torigin := registry[host.Name]\n\t\tif i == origin {\n\t\t\tunique = append(unique, host)\n\t\t\tcontinue\n\t\t}\n\t\tunique[origin].Merge(host)\n\t}\n\n\t*dst = unique\n}", "func (*ZapPlugin) Merge(segments []seg.Segment, drops []*roaring.Bitmap, path string,\n\tcloseCh chan struct{}, s seg.StatsReporter) (\n\t[][]uint64, uint64, error) {\n\tsegmentBases := make([]*SegmentBase, len(segments))\n\tfor segmenti, segment := range segments {\n\t\tswitch segmentx := segment.(type) {\n\t\tcase *Segment:\n\t\t\tsegmentBases[segmenti] = &segmentx.SegmentBase\n\t\tcase *SegmentBase:\n\t\t\tsegmentBases[segmenti] = segmentx\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"oops, unexpected segment type: %T\", segment))\n\t\t}\n\t}\n\treturn mergeSegmentBases(segmentBases, drops, path, DefaultChunkMode, closeCh, s)\n}", "func (bml BitmapLayers) Merge() (BitmapLayer, error) {\n\tout := BitmapLayer{}\n\tif len(bml) != 2 {\n\t\treturn out, fmt.Errorf(\"merge requires exactly two input segments\")\n\t}\n\n\tleft, right := bml[0], bml[1]\n\n\tadditions := left.Additions.Clone()\n\tadditions.Or(right.Additions)\n\tadditions.AndNot(right.Deletions)\n\n\tdeletions := left.Deletions.Clone()\n\tdeletions.AndNot(right.Additions)\n\tdeletions.Or(right.Deletions)\n\n\tout.Additions = Condense(additions)\n\tout.Deletions = Condense(deletions)\n\treturn out, nil\n}", "func TestMergeTwoLists_Example1(t *testing.T) {\n\tl1 := &ListNode{\n\t\tVal: 1,\n\t\tNext: &ListNode{\n\t\t\tVal: 2,\n\t\t\tNext: &ListNode{\n\t\t\t\tVal: 4,\n\t\t\t\tNext: nil,\n\t\t\t},\n\t\t},\n\t}\n\tl2 := &ListNode{\n\t\tVal: 1,\n\t\tNext: &ListNode{\n\t\t\tVal: 3,\n\t\t\tNext: &ListNode{\n\t\t\t\tVal: 4,\n\t\t\t\tNext: nil,\n\t\t\t},\n\t\t},\n\t}\n\n\t// [1,1,2,3,4,4]\n\texpectedOutput := &ListNode{\n\t\tVal: 1,\n\t\tNext: &ListNode{\n\t\t\tVal: 1,\n\t\t\tNext: &ListNode{\n\t\t\t\tVal: 2,\n\t\t\t\tNext: &ListNode{\n\t\t\t\t\tVal: 3,\n\t\t\t\t\tNext: &ListNode{\n\t\t\t\t\t\tVal: 4,\n\t\t\t\t\t\tNext: &ListNode{\n\t\t\t\t\t\t\tVal: 4,\n\t\t\t\t\t\t\tNext: nil,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\toutput := mergeTwoLists_v2(l1, l2)\n\n\tif !reflect.DeepEqual(expectedOutput, output) {\n\t\tt.Error(\"Expected List does not match Actual\")\n\t}\n}", "func (a *AttributeDefinition) Merge(other *AttributeDefinition) *AttributeDefinition {\n\tif other == nil {\n\t\treturn a\n\t}\n\tif a == nil {\n\t\treturn other\n\t}\n\tleft := a.Type.(Object)\n\tright := other.Type.(Object)\n\tif left == nil || right == nil {\n\t\tpanic(\"cannot merge non object attributes\") // bug\n\t}\n\tfor n, v := range right {\n\t\tleft[n] = v\n\t}\n\treturn a\n}", "func (m *MemoryLogger) Merge(other ...*MemoryLogger) []LogEntry {\n\tret := make([]LogEntry, 0)\n\telems := make([]*LogEntry, len(other)+1)\n\telems[0] = m.FirstEntry\n\tm.mutex.Lock()\n\tfor i, o := range other {\n\t\to.mutex.Lock()\n\t\telems[i+1] = o.FirstEntry\n\t}\n\n\tfor len(elems) > 0 {\n\t\t// Remove all elems that are nil\n\t\tnewElems := make([]*LogEntry, 0)\n\t\tfor _, v := range elems {\n\t\t\tif v != nil {\n\t\t\t\tnewElems = append(newElems, v)\n\t\t\t}\n\t\t}\n\t\telems = newElems\n\t\t// Find the next lowest element and move forward\n\t\tmin := time.Now()\n\t\tsmallest := -1\n\t\tfor i := range elems {\n\t\t\tif elems[i].Time.Before(min) {\n\t\t\t\tmin = elems[i].Time\n\t\t\t\tsmallest = i\n\t\t\t}\n\t\t}\n\t\tif smallest >= 0 {\n\t\t\tret = append(ret, *elems[smallest])\n\t\t\telems[smallest] = elems[smallest].Next\n\t\t}\n\t}\n\tm.mutex.Unlock()\n\tfor _, o := range other {\n\t\to.mutex.Unlock()\n\t}\n\treturn ret\n}", "func (p1 PortInfoMap) Merge(p2 PortInfoMap) error {\n\tvar err error\n\tfor svcPort, portInfo := range p2 {\n\t\tmergedInfo := PortInfo{}\n\t\tif existingPortInfo, ok := p1[svcPort]; ok {\n\t\t\tif existingPortInfo.TargetPort != portInfo.TargetPort {\n\t\t\t\treturn fmt.Errorf(\"for service port %d, target port in existing map is %q, but the merge map has %q\", svcPort, existingPortInfo.TargetPort, portInfo.TargetPort)\n\t\t\t}\n\t\t\tif existingPortInfo.NegName != portInfo.NegName {\n\t\t\t\treturn fmt.Errorf(\"for service port %d, NEG name in existing map is %q, but the merge map has %q\", svcPort, existingPortInfo.NegName, portInfo.NegName)\n\t\t\t}\n\t\t\tmergedInfo.ReadinessGate = existingPortInfo.ReadinessGate\n\t\t}\n\t\tmergedInfo.TargetPort = portInfo.TargetPort\n\t\tmergedInfo.NegName = portInfo.NegName\n\t\tmergedInfo.ReadinessGate = mergedInfo.ReadinessGate || portInfo.ReadinessGate\n\t\tp1[svcPort] = mergedInfo\n\t}\n\treturn err\n}", "func (r *MCResponse) Merge(subs []proto.Request) {\n\tif r.rTp != RequestTypeGet && r.rTp != RequestTypeGets && r.rTp != RequestTypeGat && r.rTp != RequestTypeGats {\n\t\t// TODO(felix): log or ???\n\t\treturn\n\t}\n\tconst endBytesLen = 5 // NOTE: endBytes length\n\tsubl := len(subs)\n\trebs := make([][]byte, subl)\n\treln := 0\n\tfor i := 0; i < subl; i++ {\n\t\tif err := subs[i].Resp.Err(); err != nil {\n\t\t\t// TODO(felix): log or ???\n\t\t\tcontinue\n\t\t}\n\t\tmcr, ok := subs[i].Resp.Proto().(*MCResponse)\n\t\tif !ok {\n\t\t\t// TODO(felix): log or ???\n\t\t\tcontinue\n\t\t}\n\t\tif bytes.Equal(mcr.data, endBytes) {\n\t\t\tcontinue\n\t\t}\n\t\trebs[i] = mcr.data[:len(mcr.data)-endBytesLen]\n\t\treln += len(rebs[i])\n\t}\n\tsa, ok := bufPool.Get().(*bufio.SliceAlloc)\n\tif !ok {\n\t\tr.data = make([]byte, reln+endBytesLen) // TODO(felix): optimize\n\t} else {\n\t\tr.data = sa.Make(reln + endBytesLen)\n\t\tbufPool.Put(sa)\n\t}\n\toff := 0\n\tfor i := 0; i < subl; i++ {\n\t\tbs := rebs[i]\n\t\tif len(bs) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcopy(r.data[off:], bs)\n\t\toff += len(bs)\n\t}\n\tcopy(r.data[off:], endBytes)\n}", "func (m *Empty) Merge(overrides *Empty) {\n\tif m == nil || overrides == nil {\n\t\treturn\n\t}\n\n}", "func mergeWaveBuffers(data []*audio.IntBuffer) (*audio.IntBuffer, error) {\n\tsize := len(data[0].Data)\n\tfor i := 1; i < len(data); i++ {\n\t\tsize += len(data[1].Data)\n\t\tif data[i].Format.NumChannels != data[0].Format.NumChannels {\n\t\t\treturn nil, errgo.New(\"different number of channels in files\")\n\t\t}\n\t\tif data[i].Format.SampleRate != data[0].Format.SampleRate {\n\t\t\treturn nil, errgo.New(\"different sample rates in different files\")\n\t\t}\n\t\tif data[i].SourceBitDepth != data[0].SourceBitDepth {\n\t\t\treturn nil, errgo.New(\"different bit-depths in different files\")\n\t\t}\n\t\tdata[0].Data = append(data[0].Data, data[i].Data...)\n\t}\n\treturn data[0], nil\n}", "func merge(original interface{}, update interface{}) (merged interface{}, err error) {\n\n\tlogger.Info(\"Merging\", \"original\", original, \"update\", update)\n\n\tswitch O := original.(type) {\n\n\tcase map[string]interface{}:\n\t\tU, ok := update.(map[string]interface{})\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"update is not mS like original\")\n\t\t}\n\t\tlogger.Info(\"mS entering\")\n\t\tfor key, val := range U {\n\t\t\tlogger.Debug(\"in merge mS-U\", \"key\", key, \"val\", val, \"curr\", O[key])\n\t\t\tif curr, exists := O[key]; exists {\n\t\t\t\ttmp, err := merge(curr, val)\n\t\t\t\tlogger.Debug(\"after merge mS\", \"tmp\", tmp, \"err\", err)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrap(err, \"in merge mS\")\n\t\t\t\t}\n\t\t\t\tO[key] = tmp\n\t\t\t} else {\n\t\t\t\tO[key] = val\n\t\t\t}\n\t\t}\n\t\tlogger.Info(\"mS returning\", \"O\", O)\n\t\treturn O, nil\n\n\tcase []interface{}:\n\t\tU, ok := update.([]interface{})\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"update is not aI like original\")\n\t\t}\n\t\t// logger.Warn(\"O\", \"data\", O)\n\t\t// logger.Warn(\"U\", \"data\", U)\n\n\t\tlogger.Info(\"aI entering\")\n\t\t// turn update into map\n\t\tUM := map[string]interface{}{}\n\t\tfor i, elem := range U {\n\t\t\tswitch E := elem.(type) {\n\n\t\t\tcase map[string]interface{}:\n\t\t\t\tname, ok := E[\"name\"]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, errors.New(\"original array objects must have names to be merged\")\n\t\t\t\t}\n\t\t\t\tUM[name.(string)] = E\n\n\t\t\tcase string:\n\t\t\t\tUM[E] = E\n\n\t\t\tdefault:\n\t\t\t\tlogger.Error(\"original unknown elem type in aI\", \"i\", i, \"elem\", elem)\n\t\t\t\treturn nil, errors.New(\"original unknown elem type in aI\")\n\t\t\t}\n\t\t}\n\n\t\tfor i, elem := range O {\n\t\t\t// logger.Crit(\"O-loop\", \"i\", i, \"elem\", elem)\n\t\t\tswitch E := elem.(type) {\n\n\t\t\tcase map[string]interface{}:\n\t\t\t\tiname, ok := E[\"name\"]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, errors.New(\"original array objects must have names to be merged\")\n\t\t\t\t}\n\n\t\t\t\tname := iname.(string)\n\t\t\t\t// logger.Error(\"Name\", \"name\", name)\n\n\t\t\t\tcurr, exists := UM[name]\n\t\t\t\tif exists {\n\t\t\t\t\ttmp, err := merge(elem, curr)\n\t\t\t\t\t// this is correct, the var names curr and elem are backwards...\n\t\t\t\t\t// busy fixing a bug\n\t\t\t\t\t// logger.Crit(\"merging with existing element\", \"key\", name, \"val\", curr, \"curr\", elem)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, errors.Wrap(err, \"in merge MS\")\n\t\t\t\t\t}\n\t\t\t\t\tO[i] = tmp\n\t\t\t\t\tdelete(UM, name)\n\t\t\t\t}\n\t\t\tcase string:\n\t\t\t\t_, exists := UM[E]\n\t\t\t\tif exists {\n\t\t\t\t\tdelete(UM, E)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tlogger.Error(\"original unknown elem type in aI\", \"i\", i, \"elem\", elem)\n\t\t\t\treturn nil, errors.New(\"original unknown elem type in aI\")\n\t\t\t}\n\t\t}\n\t\t// merge\n\t\tlogger.Info(\"aI\")\n\n\t\t// turn back into array\n\t\tOA := []interface{}{}\n\t\tfor _, val := range O {\n\t\t\tOA = append(OA, val)\n\t\t}\n\t\tfor _, elem := range U {\n\t\t\tswitch E := elem.(type) {\n\n\t\t\tcase map[string]interface{}:\n\t\t\t\tname, ok := E[\"name\"]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, errors.New(\"original array objects must have names to be merged\")\n\t\t\t\t}\n\t\t\t\t_, exists := UM[name.(string)]\n\t\t\t\tif exists {\n\t\t\t\t\tOA = append(OA, elem)\n\t\t\t\t}\n\n\t\t\tcase string:\n\t\t\t\t_, exists := UM[E]\n\t\t\t\tif exists {\n\t\t\t\t\tOA = append(OA, elem)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\t// logger.Error(\"OA\", \"data\", OA)\n\n\t\tlogger.Info(\"aI returning\", \"OA\", OA)\n\t\treturn OA, nil\n\n\tcase string:\n\t\treturn update, nil\n\n\tdefault:\n\t\treturn nil, errors.New(\"unmergable original\" + fmt.Sprintf(\"%t, %+v\", original, original))\n\n\t}\n\n\tlogger.Crit(\"Shouldn't get here (end of merge function)\")\n\treturn nil, errors.New(\"PANIC, should not get here\")\n}", "func TestMergeTwoLists_Example3(t *testing.T) {\n\toutput := mergeTwoLists_v2(nil, &ListNode{\n\t\tVal: 0,\n\t\tNext: nil,\n\t})\n\n\texpectedOutput := &ListNode{\n\t\tVal: 0,\n\t\tNext: nil,\n\t}\n\n\tif !reflect.DeepEqual(expectedOutput, output) {\n\t\tt.Errorf(\"Expected: &{0 <nil>}. Actual: %v\", output)\n\t}\n}", "func (d *Release) merge() map[string]interface{} {\n\tif len(d.dep) > 0 {\n\t\treturn d.dep\n\t}\n\tif d.src = d.ref.ToDeploy(d.env1, d.env2); len(d.src) == 0 {\n\t\t// No variable in this project for these environments\n\t\treturn nil\n\t}\n\td.dst = d.fetch()\n\td.dep = make(map[string]interface{})\n\tfor k, sv := range d.src {\n\t\tdv, ok := d.dst[k]\n\t\tswitch {\n\t\tcase !ok:\n\t\t\td.dep[k] = sv\n\t\t\td.task.Add++\n\t\tcase sv == nil:\n\t\t\td.dep[k] = sv\n\t\t\td.task.Del++\n\t\tcase sv != dv:\n\t\t\td.dep[k] = sv\n\t\t\td.task.Upd++\n\t\tdefault:\n\t\t\td.task.NoOp++\n\t\t}\n\t}\n\treturn d.dep\n}", "func (s *Stream) Merge(samples Samples) {\n\tsort.Sort(samples)\n\ts.stream.merge(samples)\n}", "func (r Result) Merge(r1 Result) Result {\n\treturn Result{append(r.List, r1.List...), r.Sum + r1.Sum, r.Bonus + r1.Bonus, r.Size}\n}", "func mergeMemberShipList(recievedMemberShipList map[string]Membership) {\r\n\tfor key, _ := range recievedMemberShipList {\r\n\t\tif key == MyOldID {\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n\tfor key, receivedMembership := range recievedMemberShipList {\r\n\t\tMT.Lock()\r\n\t\tif existedMembership, ok := MembershipList[key]; ok {\r\n\t\t\tif receivedMembership.HeartBeat == -2 {\r\n\t\t\t\tif _, ok := LeaveNodes[key]; !ok {\r\n\t\t\t\t\thelper.LogLeaver(Logger, MyVM, key)\r\n\t\t\t\t\tMembershipList[key] = receivedMembership\r\n\t\t\t\t\tLeaveNodes[key] = 1\r\n\t\t\t\t\t//build one row message\r\n\t\t\t\t\ttempMembershipList := map[string]Membership{key: MembershipList[key]}\r\n\t\t\t\t\tjsonString, err := json.Marshal(tempMembershipList)\r\n\t\t\t\t\tif err != nil {\r\n\t\t\t\t\t\tpanic(err)\r\n\t\t\t\t\t}\r\n\t\t\t\t\tmsg := string(jsonString)\r\n\t\t\t\t\tfor id := range MembershipList {\r\n\t\t\t\t\t\t_, okLeave := LeaveNodes[id]\r\n\t\t\t\t\t\t_, okFail := FailedNodes[id]\r\n\t\t\t\t\t\t// dont send to myself, leave nodes and fail nodes\r\n\t\t\t\t\t\tif id != MyID && !okLeave && !okFail {\r\n\t\t\t\t\t\t\tsendMsgToID(id, msg)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tgo deleteIDAfterTcleanup(key)\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// we know it left, do nothing\r\n\t\t\t\t}\r\n\t\t\t} else if existedMembership.HeartBeat < receivedMembership.HeartBeat {\r\n\t\t\t\t_, okLeave := LeaveNodes[key]\r\n\t\t\t\t_, okFail := FailedNodes[key]\r\n\t\t\t\tif !okLeave && !okFail {\r\n\t\t\t\t\tMembershipList[key] = receivedMembership\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tif _, ok := FailedNodes[key]; ok {\r\n\t\t\t\t//refuse accept failed node\r\n\t\t\t} else if _, ok := LeaveNodes[key]; ok {\r\n\t\t\t\t// refuse accept leaved node\r\n\t\t\t} else {\r\n\t\t\t\thelper.LogJoiner(Logger, MyVM, key)\r\n\t\t\t\tMembershipList[key] = receivedMembership\r\n\t\t\t}\r\n\t\t}\r\n\t\tMT.Unlock()\r\n\t}\r\n}", "func (t *Telemetry) Merge(b *Telemetry) *Telemetry {\n\tconfig := *t\n\n\tif b.StatsdAddress != \"\" {\n\t\tconfig.StatsdAddress = b.StatsdAddress\n\t}\n\n\treturn &config\n}", "func (status Resources) Merge(with Resources) {\n\tfor key, withTable := range with {\n\t\ttable, exist := status[key]\n\t\tif !exist {\n\t\t\tstatus[key] = withTable\n\t\t} else {\n\t\t\ttable.Items = append(table.Items, withTable.Items...)\n\t\t}\n\t}\n}", "func (a *UnsignedArray) Merge(b *UnsignedArray) {\n\tif a.Len() == 0 {\n\t\t*a = *b\n\t\treturn\n\t}\n\n\tif b.Len() == 0 {\n\t\treturn\n\t}\n\n\t// Normally, both a and b should not contain duplicates. Due to a bug in older versions, it's\n\t// possible stored blocks might contain duplicate values. Remove them if they exists before\n\t// merging.\n\t// a = a.Deduplicate()\n\t// b = b.Deduplicate()\n\n\tif a.MaxTime() < b.MinTime() {\n\t\ta.Timestamps = append(a.Timestamps, b.Timestamps...)\n\t\ta.Values = append(a.Values, b.Values...)\n\t\treturn\n\t}\n\n\tif b.MaxTime() < a.MinTime() {\n\t\tvar tmp UnsignedArray\n\t\ttmp.Timestamps = append(b.Timestamps, a.Timestamps...)\n\t\ttmp.Values = append(b.Values, a.Values...)\n\t\t*a = tmp\n\t\treturn\n\t}\n\n\tout := NewUnsignedArrayLen(a.Len() + b.Len())\n\ti, j, k := 0, 0, 0\n\tfor i < len(a.Timestamps) && j < len(b.Timestamps) {\n\t\tif a.Timestamps[i] < b.Timestamps[j] {\n\t\t\tout.Timestamps[k] = a.Timestamps[i]\n\t\t\tout.Values[k] = a.Values[i]\n\t\t\ti++\n\t\t} else if a.Timestamps[i] == b.Timestamps[j] {\n\t\t\tout.Timestamps[k] = b.Timestamps[j]\n\t\t\tout.Values[k] = b.Values[j]\n\t\t\ti++\n\t\t\tj++\n\t\t} else {\n\t\t\tout.Timestamps[k] = b.Timestamps[j]\n\t\t\tout.Values[k] = b.Values[j]\n\t\t\tj++\n\t\t}\n\t\tk++\n\t}\n\n\tif i < len(a.Timestamps) {\n\t\tn := copy(out.Timestamps[k:], a.Timestamps[i:])\n\t\tcopy(out.Values[k:], a.Values[i:])\n\t\tk += n\n\t} else if j < len(b.Timestamps) {\n\t\tn := copy(out.Timestamps[k:], b.Timestamps[j:])\n\t\tcopy(out.Values[k:], b.Values[j:])\n\t\tk += n\n\t}\n\n\ta.Timestamps = out.Timestamps[:k]\n\ta.Values = out.Values[:k]\n}", "func main() {\n\tnums1 := []int{1,4,7,0,0,0}\n\tnums2 := []int{2,3,6}\n\tmerge(nums1, len(nums1)-len(nums2), nums2, len(nums2))\n\tfmt.Println(nums1)\n}", "func (ct *ClusterTopology) Merge(topology *ClusterTopology) {\n\tlog.Println(\"Merging topologies ...\")\n\tfor _, node := range topology.Nodes {\n\t\tlog.Printf(\"Evaluating node %s ...\\r\\n\", node.Node.Name)\n\t\tct.addNode(node)\n\t}\n\tct.AddNode(currentNode) // restore current node if needed\n\tct.buildHashcode()\n}", "func (m *resourceInfo) unmerge(info IPMetadata) {\n\tswitch info.(type) {\n\tcase labels.Labels:\n\t\tm.labels = nil\n\tdefault:\n\t\tlog.Errorf(\"BUG: Invalid IPMetadata passed to ipinfo.unmerge(): %+v\", info)\n\t\treturn\n\t}\n}", "func (validation *Validation) Merge(_validation *Validation) *Validation {\n\treturn validation.merge(\"\", _validation)\n}", "func (st *notificationState) Merge(other mesh.GossipData) mesh.GossipData {\n\to := other.(*notificationState)\n\to.mtx.RLock()\n\tdefer o.mtx.RUnlock()\n\tst.mtx.Lock()\n\tdefer st.mtx.Unlock()\n\n\tfor k, v := range o.set {\n\t\tif prev, ok := st.set[k]; !ok || prev.Timestamp.Before(v.Timestamp) {\n\t\t\tst.set[k] = v\n\t\t}\n\t}\n\treturn st\n}", "func (v *Venom) Merge(l ConfigLevel, data ConfigMap) {\n\tv.Store.Merge(l, data)\n}", "func Merge(changing [][]byte, static ...[]byte) (merged []byte) {\n\tmerged = make([]byte, 0)\n\tif len(changing) <= 0 && len(static) <= 0 {\n\t\treturn\n\t}\n\tfor _, bs := range static {\n\t\tmerged = append(merged, bs...)\n\t}\n\tfor _, bs := range changing {\n\t\tmerged = append(merged, Int64ToBytes(int64(len(bs)))...)\n\t\tmerged = append(merged, bs...)\n\t}\n\treturn\n}", "func (l *UDPServersLoadBalancer) Mergeable(loadBalancer *UDPServersLoadBalancer) bool {\n\tsavedServers := l.Servers\n\tdefer func() {\n\t\tl.Servers = savedServers\n\t}()\n\tl.Servers = nil\n\n\tsavedServersLB := loadBalancer.Servers\n\tdefer func() {\n\t\tloadBalancer.Servers = savedServersLB\n\t}()\n\tloadBalancer.Servers = nil\n\n\treturn reflect.DeepEqual(l, loadBalancer)\n}", "func (m *Merge) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (batch *Batch) Append(dataId common.DataID) {\n\tindices := batch.set[dataId.BundleID]\n\tif indices == nil {\n\t\tindices = []int{}\n\t}\n\tindices = append(indices, dataId.Index)\n\n\tbatch.set[dataId.BundleID] = indices\n\tbatch.Count += 1\n}", "func (a Vector) Merge(b Vector) Vector {\n\tvar ai, bi int\n\tfor bi < len(b) {\n\t\tif ai == len(a) {\n\t\t\t// We've reach the end of a, all that remains are appends\n\t\t\treturn append(a, b[bi:]...)\n\t\t}\n\n\t\tif a[ai].id > b[bi].id {\n\t\t\t// The index from b should be inserted here\n\t\t\tn := make(Vector, len(a)+1)\n\t\t\tcopy(n, a[:ai])\n\t\t\tn[ai] = b[bi]\n\t\t\tcopy(n[ai+1:], a[ai:])\n\t\t\ta = n\n\t\t}\n\n\t\tif a[ai].id == b[bi].id {\n\t\t\tif v := b[bi].value; v > a[ai].value {\n\t\t\t\ta[ai].value = v\n\t\t\t}\n\t\t}\n\n\t\tif bi < len(b) && a[ai].id == b[bi].id {\n\t\t\tbi++\n\t\t}\n\t\tai++\n\t}\n\n\treturn a\n}", "func TestMerge(t *testing.T) {\n\ta := NewEvent(\"1970-01-01T00:00:00Z\", map[int64]interface{}{-1: int64(30), -2: \"foo\"})\n\tb := NewEvent(\"1970-01-01T00:00:00Z\", map[int64]interface{}{-1: 20, 3: \"baz\"})\n\ta.Merge(b)\n\tif a.Data[-1] != 20 || a.Data[-2] != \"foo\" || a.Data[3] != \"baz\" {\n\t\tt.Fatalf(\"Invalid merge: %v\", a.Data)\n\t}\n}", "func (j *JobScaling) Merge(b *JobScaling) *JobScaling {\n\tconfig := *j\n\n\tif b.Enabled {\n\t\tconfig.Enabled = b.Enabled\n\t}\n\n\tif b.ConsulToken != \"\" {\n\t\tconfig.ConsulToken = b.ConsulToken\n\t}\n\n\tif b.ConsulKeyLocation != \"\" {\n\t\tconfig.ConsulKeyLocation = b.ConsulKeyLocation\n\t}\n\n\treturn &config\n}", "func (a *StringArray) Merge(b *StringArray) {\n\tif a.Len() == 0 {\n\t\t*a = *b\n\t\treturn\n\t}\n\n\tif b.Len() == 0 {\n\t\treturn\n\t}\n\n\t// Normally, both a and b should not contain duplicates. Due to a bug in older versions, it's\n\t// possible stored blocks might contain duplicate values. Remove them if they exists before\n\t// merging.\n\t// a = a.Deduplicate()\n\t// b = b.Deduplicate()\n\n\tif a.MaxTime() < b.MinTime() {\n\t\ta.Timestamps = append(a.Timestamps, b.Timestamps...)\n\t\ta.Values = append(a.Values, b.Values...)\n\t\treturn\n\t}\n\n\tif b.MaxTime() < a.MinTime() {\n\t\tvar tmp StringArray\n\t\ttmp.Timestamps = append(b.Timestamps, a.Timestamps...)\n\t\ttmp.Values = append(b.Values, a.Values...)\n\t\t*a = tmp\n\t\treturn\n\t}\n\n\tout := NewStringArrayLen(a.Len() + b.Len())\n\ti, j, k := 0, 0, 0\n\tfor i < len(a.Timestamps) && j < len(b.Timestamps) {\n\t\tif a.Timestamps[i] < b.Timestamps[j] {\n\t\t\tout.Timestamps[k] = a.Timestamps[i]\n\t\t\tout.Values[k] = a.Values[i]\n\t\t\ti++\n\t\t} else if a.Timestamps[i] == b.Timestamps[j] {\n\t\t\tout.Timestamps[k] = b.Timestamps[j]\n\t\t\tout.Values[k] = b.Values[j]\n\t\t\ti++\n\t\t\tj++\n\t\t} else {\n\t\t\tout.Timestamps[k] = b.Timestamps[j]\n\t\t\tout.Values[k] = b.Values[j]\n\t\t\tj++\n\t\t}\n\t\tk++\n\t}\n\n\tif i < len(a.Timestamps) {\n\t\tn := copy(out.Timestamps[k:], a.Timestamps[i:])\n\t\tcopy(out.Values[k:], a.Values[i:])\n\t\tk += n\n\t} else if j < len(b.Timestamps) {\n\t\tn := copy(out.Timestamps[k:], b.Timestamps[j:])\n\t\tcopy(out.Values[k:], b.Values[j:])\n\t\tk += n\n\t}\n\n\ta.Timestamps = out.Timestamps[:k]\n\ta.Values = out.Values[:k]\n}", "func (f *First) Merge(ctx *sql.Context, buffer, partial sql.Row) error {\n\treturn nil\n}", "func (mb *MutableBag) Merge(bags ...*MutableBag) error {\n\t// first step is to make sure there are no redundant definitions of the same attribute\n\tkeys := make(map[string]bool)\n\tfor _, bag := range bags {\n\t\tif bag == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor k := range bag.values {\n\t\t\tif keys[k] {\n\t\t\t\treturn fmt.Errorf(\"conflicting value for attribute %s\", k)\n\t\t\t}\n\t\t\tkeys[k] = true\n\t\t}\n\t}\n\n\t// now that we know there are no conflicting definitions, do the actual merging...\n\tfor _, bag := range bags {\n\t\tif bag == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor k, v := range bag.values {\n\t\t\tmb.values[k] = copyValue(v)\n\t\t}\n\t}\n\n\treturn nil\n}", "func Merge(dest interface{}, source interface{}) error {\n\topts := make([]func(*mergo.Config), 0)\n\n\t// lists are always overridden - we don't append merged lists since it generally makes things more complicated\n\topts = append(opts, mergo.WithOverride)\n\n\terr := mergo.Merge(dest, source, opts...)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func (s *FKCascadeRuntimeStats) Merge(other execdetails.RuntimeStats) {\n\ttmp, ok := other.(*FKCascadeRuntimeStats)\n\tif !ok {\n\t\treturn\n\t}\n\ts.Total += tmp.Total\n\ts.Keys += tmp.Keys\n}", "func (dst *Engine) Merge(src *Engine) {\n\tif dst == nil || src == nil {\n\t\treturn\n\t}\n\n\tif src.Name != \"\" {\n\t\tdst.Name = src.Name\n\t}\n\tif src.Version != \"\" {\n\t\tdst.Version = src.Version\n\t}\n\tif src.Size != \"\" {\n\t\tdst.Size = src.Size\n\t}\n\n\tif src.Resources != nil && dst.Resources == nil {\n\t\tdst.Resources = new(Resources)\n\t}\n\tdst.Resources.Merge(src.Resources)\n}", "func parMerge(a[] int, fst int, snd int, lng int, c chan bool, done chan bool) {\n <- c; <- c\n merge(a, fst, snd, lng)\n done <- true\n}", "func mergeMessages(src, dst []*translation.Message) []*translation.Message {\n\tmerged := make(map[string]*translation.Message)\n\tfor idx := range dst {\n\t\tmerged[dst[idx].ID] = dst[idx]\n\t}\n\tfor idx := range src {\n\t\tmerged[src[idx].ID] = src[idx]\n\t}\n\tvar out []*translation.Message\n\tfor _, message := range merged {\n\t\tout = append(out, message)\n\t}\n\treturn out\n}", "func MergeBU(datas interfaces.Sortable) interfaces.Sortable {\n\tN := datas.Len()\n\tfor sz := 1; sz < N; sz = 2 * sz {\n\t\tfor lo := 0; lo < N-sz; lo += 2 * sz {\n\t\t\tmid := lo + sz - 1\n\t\t\thi := mid + sz\n\t\t\tif hi > N-1 {\n\t\t\t\thi = N - 1\n\t\t\t}\n\t\t\tmerge(datas, lo, mid, hi)\n\t\t}\n\t}\n\n\treturn datas\n}", "func (e Entities) Merge(entities Entities) Entities {\n\tfor i := range entities {\n\t\t// Check for duplicates\n\t\tif !e.Contains(entities[i]) {\n\t\t\t// Add to new list\n\t\t\te = append(e, entities[i])\n\t\t}\n\t}\n\treturn e\n}", "func (dst *Proxies) Merge(src Proxies) {\n\tif dst == nil || len(src) == 0 {\n\t\treturn\n\t}\n\n\tcopied := *dst\n\tcopied = append(copied, src...)\n\n\tregistry := map[string]int{}\n\tfor i := len(copied); i > 0; i-- {\n\t\tregistry[copied[i-1].Name] = i - 1\n\t}\n\tunique := copied[:0]\n\tfor i, proxy := range copied {\n\t\torigin := registry[proxy.Name]\n\t\tif i == origin {\n\t\t\tunique = append(unique, proxy)\n\t\t\tcontinue\n\t\t}\n\t\tunique[origin].Merge(proxy)\n\t}\n\n\t*dst = unique\n}" ]
[ "0.5636764", "0.5608513", "0.55030245", "0.5457892", "0.5433847", "0.5427023", "0.5413673", "0.5328313", "0.52650255", "0.52569515", "0.524656", "0.5213097", "0.5209504", "0.5205742", "0.5193463", "0.5180105", "0.51653993", "0.5135421", "0.51296806", "0.5109867", "0.51043874", "0.5092349", "0.50806683", "0.5052632", "0.50442845", "0.5035266", "0.50291884", "0.50093764", "0.50038636", "0.49942723", "0.49692103", "0.49655086", "0.49587047", "0.49517155", "0.49451482", "0.4944445", "0.4943638", "0.49414247", "0.49367133", "0.4936314", "0.49342906", "0.49316856", "0.49302313", "0.4912852", "0.49124584", "0.4891188", "0.48890126", "0.48773426", "0.4858622", "0.4855537", "0.48509115", "0.48491123", "0.48444387", "0.4831474", "0.48310667", "0.4815867", "0.4810602", "0.48093906", "0.48089704", "0.48080474", "0.48064616", "0.48013407", "0.48012358", "0.4788977", "0.47799724", "0.47780395", "0.47773167", "0.47715756", "0.47679007", "0.47627965", "0.47423357", "0.47414708", "0.47367865", "0.47360814", "0.47336608", "0.47258353", "0.47249892", "0.47234985", "0.47234002", "0.47190362", "0.47162187", "0.4706924", "0.47048265", "0.4703168", "0.46960205", "0.4696002", "0.46900707", "0.4686029", "0.4685823", "0.46842083", "0.46807984", "0.46798918", "0.4678331", "0.4678299", "0.46768922", "0.46759948", "0.46744812", "0.46632397", "0.4661853", "0.46614859" ]
0.61825055
0
Generate a new block based on the old block and new payload
func generateNewBlock(oldBlock Block, dataPayload string) (Block, error) { var newBlock Block timeNow := time.Now() newBlock.Index = oldBlock.Index + 1 newBlock.Timestamp = timeNow.String() newEvent, err := dataPayloadtoServiceEvent(dataPayload) if err != nil { log.Println("ERROR: Unable to convert data payload into ServiceEvent for new block generation.") } newBlock.Event = newEvent newBlock.PrevHash = oldBlock.Hash newBlock.Hash = calculateHash(newBlock) return newBlock, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *BlockchainService) generateBlock(oldBlock *Block, payload int) Block {\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Payload = payload\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(&newBlock)\n\n\treturn newBlock\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Validator = address\n\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Data = makeSignature(newBlock.Hash)\n\n\treturn newBlock, nil\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func generateBlock(oldBlock Block, Key int) Block {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Key = Key\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\tf, err := os.OpenFile(\"blocks.txt\",\n\t\tos.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tb, err := json.Marshal(newBlock)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\tif _, err := f.WriteString(string(b)); err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn newBlock\n}", "func GenerateBlock(oldBlock model.Block, data string, address string) (model.Block, error) {\n\n\tvar newBlock model.Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = crypto.CalculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func ProduceBlock(prevBlockHash string, prevBlock *Block) *Block {\n // This function creates a new block.\n //\n // The implementation is fairly straightforward matter of creating a Block instance and filling in the fields.\n //\n // This function's API is slightly weird, it requires the caller to compute `prevBlockHash = HashBlock(prevBlock)`.\n // Why we don't simplify the API by computing `prevBlockHash` ourselves, reducing the number of arguments\n // from two to one? Two reasons:\n //\n // - Immediately, it makes the placement of the `HashBlock()` debugging output less confusing.\n // - Eventually, we will have more data with the same data flow as `prevBlockHash`, so writing code to route this data\n // now will be useful later.\n\n newBlock := new(Block)\n\n if prevBlock == nil {\n newBlock.PrevHash = prevBlockHash\n newBlock.Height = 1\n } else {\n newBlock.PrevHash = prevBlockHash\n newBlock.Height = prevBlock.Height + 1\n }\n\n return newBlock\n}", "func generateBlock(previousBlock Block, BPM int, address string) (Block, error) {\n\n\tnewBlock := Block{\n\t\tIndex: previousBlock.Index + 1,\n\t\tTimestamp: time.Now().String(),\n\t\tBPM: BPM,\n\t\tPrevHash: previousBlock.Hash,\n\t}\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func NewBlock(oldBlock Block, data string) Block {\n\t// fmt.Println(\"******TODO: IMPLEMENT NewBlock!******\")\n\tblock := Block{Data: data, Timestamp: time.Now().Unix(), PrevHash: oldBlock.Hash, Hash: []byte{}}\n\tblock.Hash = block.calculateHash()\n\t// fmt.Println(\"data: \" + block.Data)\n\t// fmt.Printf(\"timestamp: %d\", block.Timestamp)\n\t// fmt.Println()\n\t// fmt.Printf(\"preHash: %x\", block.PrevHash)\n\t// fmt.Println()\n\t// fmt.Printf(\"currentHash: %x\", block.Hash)\n\t// fmt.Println()\n\t// fmt.Println(\"******TODO: END NewBlock!******\")\n\t// fmt.Println()\n\t// fmt.Println()\n\t// fmt.Println()\n\treturn block\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func newBlock(prevHash [32]byte, prevHashWithoutTx [32]byte, commitmentProof [crypto.COMM_PROOF_LENGTH]byte, height uint32) *protocol.Block {\n\tblock := new(protocol.Block)\n\tblock.PrevHash = prevHash\n\tblock.PrevHashWithoutTx = prevHashWithoutTx\n\tblock.CommitmentProof = commitmentProof\n\tblock.Height = height\n\tblock.StateCopy = make(map[[32]byte]*protocol.Account)\n\tblock.Aggregated = false\n\n\treturn block\n}", "func (honest *Honest) createBlock(iterationCount int, stakeMap map[int]int) (*Block,error) {\n\n\t// Has block already been appended from advertisements by other client?\n\tif(honest.bc.getBlock(iterationCount) != nil){\n\t\treturn nil, blockExistsError\n\t}\n\n\tpulledGradient := make([]float64, honest.ncol)\n\tpulledGradient = honest.bc.getLatestGradient()\n\tupdatedGradient := make([]float64, honest.ncol)\n\tdeltaM := mat.NewDense(1, honest.ncol, make([]float64, honest.ncol))\n\tpulledGradientM := mat.NewDense(1, honest.ncol, pulledGradient)\n\t// avgFactor := 1.0/float64(len(honest.blockUpdates))\n\n\t// Update Aggregation\n\tfor _, update := range honest.blockUpdates {\n\t\ttheirStake := stakeMap[update.SourceID] \n\t\tif update.Accepted {\n\t\t\tdeltaM = mat.NewDense(1, honest.ncol, update.Delta)\n\t\t\tpulledGradientM.Add(pulledGradientM, deltaM)\t\n\t\t\tstakeMap[update.SourceID] = theirStake + STAKE_UNIT\n\t\t} else {\n\t\t\toutLog.Printf(\"Skipping an update\")\n\t\t\tstakeMap[update.SourceID] = theirStake - STAKE_UNIT\n\t\t}\n\t}\n\n\t// pulledGradientM.Scale(avgFactor, pulledGradientM)\n\n\tmat.Row(updatedGradient, 0, pulledGradientM)\n\n\tupdatesGathered := make([]Update, len(honest.blockUpdates))\n\tcopy(updatesGathered, honest.blockUpdates)\n\n\tbData := BlockData{iterationCount, updatedGradient, updatesGathered}\n\thonest.bc.AddBlock(bData, stakeMap) \n\n\tnewBlock := honest.bc.Blocks[len(honest.bc.Blocks)-1]\n\n\treturn newBlock,nil\n\n\n}", "func PrepareBlock(nodes []RealtimeNode, prevBlock Block, txs Transactions, appHash Digest) Block {\n var lastBlockHash = TmMerkleHash(packMulti(prevBlock.Header))\n var lastCommit = make([]Seal, 0, len(nodes))\n for i, node := range nodes {\n lastCommit[i] = node.SignBlockHash(lastBlockHash)\n }\n\n return Block{\n Header: Header{\n LastBlockHash: lastBlockHash,\n LastCommitHash: TmMerkleHash(packMulti(lastCommit)),\n TxsHash: TmMerkleHash(packMulti(txs)),\n AppHash: appHash,\n },\n LastCommit: lastCommit,\n Txs: txs,\n }\n}", "func makeBlock(txns []map[string]int, chain []map[string]interface{}) map[string]interface{} {\n\tparentBlock := chain[len(chain)-1]\n\tparentHash := parentBlock[\"hash\"]\n\tcontents := parentBlock[\"contents\"].(map[string]interface{})\n\tblockNumber := contents[\"blockNumber\"].(int)\n\ttxnCount := len(txns)\n\tblockContents := map[string]interface{}{\"blockNumber\": blockNumber + 1, \"parentHash\": parentHash, \"txnCount\": txnCount, \"txns\": txns}\n\tblockhash := hashme(blockContents)\n\tblock := map[string]interface{}{\"hash\": blockhash, \"contents\": blockContents}\n\treturn block\n}", "func (c *Crawler) newBlock(block *wire.MsgBlock, hash *chainhash.Hash) {\t\n\tc.height += 1\n\tc.blockQueue.PushBack(*hash)\n\n\tif c.blockQueue.Len() > BlockQueueSize {\n\t\tc.blockQueue.PopFront()\n\t}\n}", "func NewBlock(data *SPOTuple, prevBlockHash string) (*Block, error) {\n\n\tblock := &Block{\n\t\tBlockId: nuid.Next(),\n\t\tData: data,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: \"\",\n\t\tSig: \"\",\n\t\tAuthor: cs.PublicID(),\n\t\tSender: cs.PublicID(),\n\t}\n\n\t// assign new hash\n\tblock.setHash()\n\n\t// now sign the completed block\n\terr := block.sign()\n\tif err != nil {\n\t\tlog.Println(\"unable to sign block: \", err)\n\t\treturn nil, err\n\t}\n\n\treturn block, nil\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block {\n\t// Reward of mining a block\n\tcoinBaseTransaction := NewRewardTransacion()\n\ttxs := []*Transaction{coinBaseTransaction}\n\ttxs = append(txs, originalTxs...)\n\t// Verify transactions\n\tfor _, tx := range txs {\n\t\tif !tx.IsCoinBaseTransaction() {\n\t\t\tif blockchain.VerifityTransaction(tx, txs) == false {\n\t\t\t\tlog.Panic(\"Verify transaction failed...\")\n\t\t\t}\n\t\t}\n\t}\n\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\t// Get the latest block\n\tvar block Block\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\thash := b.Get([]byte(\"l\"))\n\t\t\tblockBytes := b.Get(hash)\n\t\t\tgobDecode(blockBytes, &block)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Mine a new block\n\tnewBlock := NewBlock(txs, block.Height+1, block.BlockHash)\n\n\treturn newBlock\n}", "func MineBlock(w http.ResponseWriter, r *http.Request) {\n\t// Checks for the block in data field\n\tvar data BlockData\n\terr := json.NewDecoder(r.Body).Decode(&data)\n\tif err != nil {\n\t\tlog.Println(\"MineBlock: Received block failed to prase(JSON)\")\n\t}\n\n\tsuccess := b.GenerateNextBlock(data.Data)\n\tif success {\n\t\thub.broadcastMsg(RespLatestMsg())\n\t}\n}", "func generateRandomBlock() types.Block {\n\tblock := types.Block{\n\t\tTimestamp: types.Timestamp(rand.Uint64()),\n\t}\n\treturn block\n}", "func (g *testGenerator) createPremineBlock(blockName string, additionalAmount dcrutil.Amount) *wire.MsgBlock {\n\tcoinbaseTx := wire.NewMsgTx()\n\tcoinbaseTx.AddTxIn(&wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: 0, // Updated below.\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\t// Add each required output and tally the total payouts for the coinbase\n\t// in order to set the input value appropriately.\n\tvar totalSubsidy dcrutil.Amount\n\tfor _, payout := range g.params.BlockOneLedger {\n\t\tpayoutAddr, err := dcrutil.DecodeAddress(payout.Address, g.params)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tpkScript, err := txscript.PayToAddrScript(payoutAddr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcoinbaseTx.AddTxOut(&wire.TxOut{\n\t\t\tValue: payout.Amount + int64(additionalAmount),\n\t\t\tVersion: 0,\n\t\t\tPkScript: pkScript,\n\t\t})\n\n\t\ttotalSubsidy += dcrutil.Amount(payout.Amount)\n\t}\n\tcoinbaseTx.TxIn[0].ValueIn = int64(totalSubsidy)\n\n\t// Generate the block with the specially created regular transactions.\n\treturn g.nextBlock(blockName, nil, nil, func(b *wire.MsgBlock) {\n\t\tb.Transactions = []*wire.MsgTx{coinbaseTx}\n\t})\n}", "func replaceChain(newBlock Block) bool {\n\n\t// make this thread safe\n\tblockchainwritelock.Lock()\n\tdefer blockchainwritelock.Unlock()\n\n\t// Is the block valid and if so then append it to the chain\n\tif isBlockValid(newBlock, Blockchain[len(Blockchain)-1]) {\n\t\tBlockchain = append(Blockchain, newBlock)\n\t\tBlockchainLength = len(Blockchain)\n\t\tvar registration string\n\n\t\t// Update vehicle lookups\n\t\tlog.Printf(\"INFO: replaceChain(): Adding vehicle to vehicle and blocklookup map.\")\n\t\tlastregindex := len(newBlock.Event.PerformedOnVehicle.VehicleRegistration)\n\t\tregistration = newBlock.Event.PerformedOnVehicle.VehicleRegistration[lastregindex-1]\n\t\tregistration = strings.ToUpper(registration)\n\t\tregistration = strings.Replace(registration, \" \", \"\", -1)\n\n\t\tblocklist := vehicleMap[registration]\n\n\t\tlog.Printf(\"INFO: replaceChain(): REG %s, BLOCKLIST SIZE %s\", registration, strconv.Itoa(len(blocklist)))\n\n\t\tlog.Printf(\"INFO: replaceChain(): Captured registration: %s with %s previous entries\", registration, strconv.Itoa(len(blocklist)))\n\n\t\tif (len(blocklist)) > 0 {\n\t\t\tlog.Printf(\"INFO: replaceChain(): Vehicle been added before. Appending new block id with value %s\", strconv.Itoa(newBlock.Index))\n\t\t\tvehicleMap[registration] = append(blocklist, newBlock.Index)\n\t\t} else {\n\t\t\tnewBlockSlice := []int{newBlock.Index}\n\t\t\tlog.Printf(\"INFO: replaceChain(): created new list of blocks for registration %s, size is %s\", registration, strconv.Itoa(len(newBlockSlice)))\n\n\t\t\t// vehicleMap not initialised so set it up\n\t\t\tif len(vehicleMap) < 1 {\n\t\t\t\tlog.Printf(\"INFO: replaceChain(): vehicleMap is not initialised, size is %s\", strconv.Itoa(len(vehicleMap)))\n\t\t\t\tvehicleMap = make(map[string][]int)\n\t\t\t}\n\t\t\t// Add the new vehicle to the map\n\t\t\tlog.Printf(\"INFO: replaceChain(): Adding vehicle %s to new vehicleMap\", registration)\n\t\t\tvehicleMap[registration] = newBlockSlice\n\t\t}\n\n\t\tlog.Printf(\"INFO: replaceChain(): Added vehicle reg %s to block lookup table, blockid %s\", registration, strconv.Itoa(newBlock.Index))\n\n\t\tlog.Printf(\"INFO: replaceChain(): Appended new block, writing to disk with ID %s\", strconv.Itoa(BlockchainLength))\n\t\terr := interfaceToFile(\"./saved_chains/md5589_blockchain_\"+strconv.Itoa(BlockchainLength), Blockchain)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ERROR: Unable to write blockchain to disk: %s\", strconv.Itoa(BlockchainLength))\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func newBlock(t nbt.Tag) BlockState {\r\n\tblock := BlockState{}\r\n\tblock.Name = t.Compound()[\"Name\"].String()\r\n\tblock.parseProperties(t)\r\n\treturn block\r\n}", "func generateBlock(block *Block) (bool, string) {\n\tb := *block\n\tdata := []byte(fmt.Sprintf(\"%v\", b.HashBlock))\n\tsum := sha256.Sum256(data)\n\thash := sum[:] // Converts from [32]byte to []byte\n\t// TODO: make sure to turn in with call to isLeadingNumZeroCharacters,\n\t// not with call to isLeadingNumZeroes (which is used for finer control of block generation)\n\tif isLeadingNumZeroes(hash) {\n\t// if isLeadingNumZeroCharacters(hash) {\n\t\thashString := string(hash)\n\t\tb.Hash = hashString\n\t\taddToBlockChain(b)\n\t\tbroadcastBlock(b)\n\t\tfmt.Println(\"Done generating new block\")\n\t\treturn true, hashString\n\t} else {\n\t\tb.HashBlock.Nonce = b.HashBlock.Nonce + 1\n\t\t*block = b\n\t\treturn false, \"\"\n\t}\n}", "func genOneBlock(blockCnt int32, addr int, localBlkCnt int32, sleepTime int) (Block, bool) {\n\tlastBlock := Blockchain[blockCnt-1]\n\tprevHash := lastBlock.thisHash\n\tblockTemplate := Block{nil, prevHash, addr, 0, initNbitInt, 0, initNbitInt, 1}\n\tnonce, thisHash, premature, realNbit, alpha := solvePoW(blockTemplate, localBlkCnt, sleepTime)\n\tif premature {\n\t\t// solving PoW is interrupted by hearing of new blocks, return immediately\n\t\treturn blockTemplate, true\n\t}\n\t// populate the block template with the right nonce and this hash\n\tblockTemplate.thisHash = thisHash\n\tblockTemplate.nonce = nonce\n\tblockTemplate.HPAM_nbit = realNbit\n\tblockTemplate.alpha = alpha\n\treturn blockTemplate, false\n}", "func (oc *Operachain) MakeBlock(name string) {\n\tvar newHeight int\n\tvar tip []byte\n\terr := oc.Db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\t\ttip = b.Get([]byte(\"l\"))\n\t\ttipData := b.Get(tip)\n\t\ttipBlock := DeserializeBlock(tipData)\n\t\tnewHeight = tipBlock.Height + 1\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tnewBlock := NewBlock(oc.MyName, tip, oc.KnownTips[name], newHeight)\n\n\toc.AddBlock(newBlock)\n\n\toc.MyGraph.Tip = oc.BuildGraph(newBlock.Hash, oc.MyGraph.ChkVertex, oc.MyGraph)\n\tfmt.Println(\"create new block\")\n\t//oc.UpdateChk = true\n}", "func mineNewBlock (block *Block) {\n proofPrefix := strings.Repeat(\"0\", difficulty)\n for calculateHash(*block)[:difficulty] != proofPrefix {\n block.Nonce ++\n }\n\n block.Hash = calculateHash(*block)\n}", "func (w *Writer) newBlockWriter(typ byte) *blockWriter {\n\tblock := w.block\n\n\tvar blockStart uint32\n\tif w.next == 0 {\n\t\thb := w.headerBytes()\n\t\tblockStart = uint32(copy(block, hb))\n\t}\n\n\tbw := newBlockWriter(typ, block, blockStart)\n\tbw.restartInterval = w.opts.RestartInterval\n\treturn bw\n}", "func NewBlock(data Data, previousBlock Block, noonce string) Block {\n\tnewBlock := Block{\n\t\ttimestamp: time.Now(),\n\t\tdata: data,\n\t\tpreviousHash: previousBlock.GetHash(),\n\t\tnoonce: noonce,\n\t}\n\tnewBlock.hash()\n\n\treturn newBlock\n}", "func NewBlock(_data string, _prevHash []byte) *Block {\n\t_block := &Block{\n\t\tTimestamp: time.Now().Unix(),\n\t\tData: []byte(_data),\n\t\tPrevHash: _prevHash,\n\t\tHash: []byte{},\n\t}\n\n\tpow := NewProofOfWork(_block)\n\tnonce, hash := pow.Run()\n\n\t_block.Nonce = nonce\n\t_block.Hash = hash[:]\n\n\treturn _block\n}", "func (honest *Honest) createBlockSecAgg(iteration int, nodeList []int, stakeMap map[int]int) (*Block,error) {\n\n\t// Has block already been appended from advertisements by other client?\n\tif(honest.bc.getBlock(iterationCount) != nil){\n\t\treturn nil, blockExistsError\n\t}\n\n\tpulledGradient := make([]float64, honest.ncol)\n\tpulledGradient = honest.bc.getLatestGradient()\n\tupdatedGradient := make([]float64, honest.ncol)\n\tdeltaM := mat.NewDense(1, honest.ncol, make([]float64, honest.ncol))\n\tpulledGradientM := mat.NewDense(1, honest.ncol, pulledGradient)\n\n\t// Recover Secret Secure Aggregation\n\tif (len(nodeList) > 0){\n\n\t\taggregateUpdate := honest.recoverAggregateUpdates()\t\n\t\tdeltaM = mat.NewDense(1, honest.ncol, aggregateUpdate)\n\t\tpulledGradientM.Add(pulledGradientM, deltaM)\n\n\t}\n\t\n\n\t// Update Aggregation\n\tfor _, nodeIndex := range nodeList {\n\t\t\n\t\tbyteCommitment, _ := honest.secretList[nodeIndex].CommitmentUpdate.MarshalBinary()\n\t\ttheirStake := stakeMap[nodeIndex]\n\t\tstakeMap[nodeIndex] = theirStake + STAKE_UNIT\n\t\tthisNodeUpdate := Update{Iteration:iteration, Commitment: byteCommitment, Accepted:true}\n\t\thonest.blockUpdates = append(honest.blockUpdates, thisNodeUpdate)\n\n\t\toutLog.Printf(\"Update:%s\", thisNodeUpdate)\n\t\toutLog.Printf(\"List of Updates:%s\", honest.blockUpdates)\n\t\n\t}\n\n\tmat.Row(updatedGradient, 0, pulledGradientM)\n\n\tupdatesGathered := make([]Update, len(honest.blockUpdates))\n\tcopy(updatesGathered, honest.blockUpdates)\n\n\tbData := BlockData{iteration, updatedGradient, updatesGathered}\n\thonest.bc.AddBlock(bData, stakeMap) \n\n\tnewBlock := honest.bc.Blocks[len(honest.bc.Blocks)-1]\n\n\treturn newBlock,nil\n\n}", "func (bc *Blockchain) AddBlock() {\n newBlock := new(Block)\n newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork()\n //newBlock.Timestamp = time.Now().Unix()\n newBlock.Index = len(bc.Chain)\n newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1])\n newBlock.Difficulty = bc.AdjustDifficulty()\n\n bc.BlockMutex.Lock()\n bc.Chain = append(bc.Chain, *newBlock)\n bc.BlockMutex.Unlock()\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}\n\tpow := NewProofOfWork(block)\n\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func TestBlock(t *testing.T) {\n\tl := &Leading{\n\t\tMagic: 0x7425,\n\t\tLenBlock: 0,\n\t}\n\n\tfmt.Println(l)\n\n\th := &chunk.Header{}\n\tfmt.Println(hex.Dump(h.Marshal()))\n\n\tcaller := &chunk.Quater{\n\t\tMain: \"1LVfRcj31E9mGujxUD3nTJjsUPtcczqJnX\",\n\t\tSub: \"send\",\n\t}\n\tcallee := &chunk.Quater{\n\t\tMain: \"1LVfRcj31E9mGujxUD3nTJjsUPtcczqJnX\",\n\t\tSub: \"recv\",\n\t}\n\n\tr := chunk.NewRouting(caller, callee)\n\tfmt.Println(hex.Dump(r.Marshal()))\n\n\tc := &chunk.Content{\n\t\tSha: chunk.GetHash('0'),\n\t\tMime: 0xff,\n\t\tCipher: []byte{},\n\t\tBody: []byte(\"Hello bitmsg\"),\n\t}\n\t//fmt.Println(c)\n\tc.Marshal()\n\tb := NewBlock(*h, *r)\n\tb.AddContent(*c)\n\tfmt.Println(hex.Dump(b.Header.ShaMerkle[:]))\n\tfmt.Println(hex.Dump(b.Marshal()))\n}", "func cloneBlock(b *wire.MsgBlock) wire.MsgBlock {\n\tvar blockCopy wire.MsgBlock\n\tblockCopy.Header = b.Header\n\tfor _, tx := range b.Transactions {\n\t\tblockCopy.AddTransaction(tx.Copy())\n\t}\n\tfor _, stx := range b.Transactions {\n\t\tblockCopy.AddSTransaction(stx.Copy())\n\t}\n\treturn blockCopy\n}", "func (b *Block) NewBlock(height int32, parentHash string, value p1.MerklePatriciaTrie) {\n\n var header Header\n mptAsBytes := getBytes(value)\n\n header.Height = height\n header.Timestamp = int64(time.Now().Unix())\n header.ParentHash = parentHash\n header.Size = int32(len(mptAsBytes))\n header.Nonce = \"\"\n hashString := string(header.Height) + string(header.Timestamp) + header.ParentHash + value.Root + string(header.Size)\n sum := sha3.Sum256([]byte(hashString))\n header.Hash = hex.EncodeToString(sum[:])\n\n b.Header = header\n b.Mpt = value\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func (bc BlockChain) deserializeBlock(o []byte) *Block {\r\n\tif !json.Valid(o) {\r\n\t\tpanic(\"Input is not a valid json object for block\")\r\n\t}\r\n\r\n\tvar jsonBlock Block\r\n\tvar b Block\r\n\t/**\r\n\tdec := json.NewDecoder(strings.NewReader(string(\to)))\r\n\tif err := dec.Decode(&jsonBlock); err == io.EOF {\r\n\t} else if err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\t**/\r\n\terr := json.Unmarshal(o, &jsonBlock)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//fmt.Println(\"new block is \" + jsonBlock.Serialize())\r\n\r\n\tbalances := make(map[string]int)\r\n\tchainLength := jsonBlock.ChainLength\r\n\ttimestamp := jsonBlock.Timestamp\r\n\r\n\tif jsonBlock.IsGenesisBlock() {\r\n\t\t//fmt.Println(\"setting balances\")\r\n\t\t//fmt.Println(jsonBlock.Balances)\r\n\t\tfor client, amount := range jsonBlock.Balances {\r\n\t\t\tbalances[client] = amount\r\n\t\t}\r\n\t\tb.Balances = balances\r\n\t} else {\r\n\t\tprevBlockHash := jsonBlock.PrevBlockHash\r\n\t\tproof := jsonBlock.Proof\r\n\t\trewardAddr := jsonBlock.RewardAddr\r\n\t\ttransactions := make(map[string]*Transaction)\r\n\t\tif jsonBlock.Transactions != nil {\r\n\t\t\tfor id, tx := range jsonBlock.Transactions {\r\n\t\t\t\ttransactions[id] = tx\r\n\t\t\t}\r\n\t\t}\r\n\t\t//GOTTA FIX THIS WHEN YOU IMPLEMENT CONSTANTS\r\n\t\tb = *bc.MakeBlock(rewardAddr, nil, nil, nil)\r\n\t\tb.ChainLength = chainLength\r\n\t\tb.Timestamp = timestamp\r\n\t\tb.PrevBlockHash = prevBlockHash\r\n\t\tb.Proof = proof\r\n\t\tb.Transactions = transactions\r\n\t}\r\n\treturn &b\r\n}", "func generateGenesisBlock() Block {\n\n\tvar genesisBlock Block\n\tvar genesisRecord ServiceEvent\n\tvar genesisRecordEventDescription EventDescription\n\tvar genesisRecordEventDescriptionType EventType\n\tvar genesisRecordVehicle Vehicle\n\tvar genesisRecordGarage Garage\n\n\t// Seed values for Garage, Vehicle, EventType and EventDescription\n\tgenesisRecordGarage.GarageId = 0\n\tgenesisRecordGarage.Location = \"genesis location\"\n\tgenesisRecordGarage.Name = \"genesis inc.\"\n\tgenesisRecordGarage.Owner = \"genesis and co.\"\n\tgenesisRecordGarage.Type = \"main dealer\"\n\n\tgenesisRecordVehicle.V5c = \"63ne515\"\n\tgenesisRecordVehicle.VehicleColour = append(genesisRecordVehicle.VehicleColour, \"starting colour\")\n\tgenesisRecordVehicle.VehicleMake = \"genesis make\"\n\tgenesisRecordVehicle.VehicleModel = \"genesis model\"\n\tgenesisRecordVehicle.VehicleRegistration = append(genesisRecordVehicle.VehicleRegistration, \"GEN 351 S\")\n\n\tgenesisRecordEventDescriptionType.EventId = 0\n\tgenesisRecordEventDescriptionType.EventDescription = \"genesis event\"\n\n\tgenesisRecordEventDescription.EventItem = append(genesisRecordEventDescription.EventItem, genesisRecordEventDescriptionType)\n\tgenesisRecordEventDescription.VehicleMilage = 10000000\n\n\t// Pull all the objects into ServiceEvent\n\tgenesisRecord.EventAuthorisor = \"Created by serviceChain as the Genesis Block\"\n\tgenesisRecord.EventDetails = genesisRecordEventDescription\n\tgenesisRecord.Identifier = 1\n\tgenesisRecord.PerformedBy = genesisRecordGarage\n\tgenesisRecord.PerformedOnVehicle = genesisRecordVehicle\n\n\t// Set the values for the Block\n\tgenesisBlock.Index = 1\n\tgenesisBlock.Hash = \"0\"\n\tgenesisBlock.PrevHash = \"0\"\n\tgenesisBlock.Timestamp = time.Now().String()\n\tgenesisBlock.Event = genesisRecord\n\n\tblockString, err := json.MarshalIndent(genesisBlock, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Println(\"INFO: serviceChain.createGenesisBlock(): Problem creating the JSON output of the genesis block. Continuing...\")\n\t}\n\n\tlog.Println(\"INFO: serviceChain.generateGenesisBlock(): Created block with contents: \" + string(blockString))\n\n\treturn genesisBlock\n}", "func ProcessBlock(code WasmCode, block Block, prevVMState VMState, prevManifestReceipt SwarmReceipt,\n) (VMState, Manifest, SwarmReceipt, Digest) {\n var vmState = NextVMState(code, prevVMState, block.Txs)\n var txsReceipt = SwarmUpload(pack(block.Txs))\n\n var manifest = Manifest{\n Header: block.Header,\n VMStateHash: MerkleHash(vmState),\n LastCommit: block.LastCommit,\n TxsReceipt: txsReceipt,\n LastManifestReceipt: prevManifestReceipt,\n }\n var receipt = SwarmUpload(pack(manifest))\n var nextAppHash = Hash(pack(manifest))\n\n return vmState, manifest, receipt, nextAppHash\n}", "func main() {\n\tvar chainHead *Block\n\tgenesis := BlockData{Transactions: []string{\"S2E\", \"S2Z\"}}\n\t//fmt.Printf(\"helllooo\")\n\t//fmt.Println(genesis)\n\tchainHead = InsertBlock(genesis, chainHead)\n\t//var x string=CalculateHash(chainHead)\n\t//fmt.Printf(\"%x\\n\", x)\n\n\tsecondBlock := BlockData{Transactions: []string{\"E2Alice\", \"E2Bob\", \"S2John\"}}\n\tchainHead = InsertBlock(secondBlock, chainHead)\n\n\tListBlocks(chainHead)\n\n\t//ChangeBlock(\"S2E\", \"S2Trudy\", chainHead)\n\n\tListBlocks(chainHead)\n\n\tVerifyChain(chainHead)\n\n}", "func GenerateNextBlock(data string, nonce int32) block {\n\tpreviousBlock := getLatestBlock()\n\n\tnextIndex := previousBlock.Index + 1\n\tnextTimestamp := time.Now().UnixNano()\n\tnextHash := calculateHash(nextIndex, previousBlock.Hash, nextTimestamp, data, 0, nonce)\n\n\treturn block{\n\t\tIndex: nextIndex,\n\t\tHash: nextHash,\n\t\tPreviousHash: previousBlock.Hash,\n\t\tTimestamp: nextTimestamp,\n\t\tData: data,\n\t}\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tTimestamp: time.Now().UTC().Unix(),\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: []byte{},\n\t\tData: []byte(data),\n\t}\n\n\tpow := NewProofOfWork(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func (cm *chainManager) MintNewBlock(timestamp time.Time) (*block.Block, error) {\n\treturn cm.bc.MintNewBlock(timestamp)\n}", "func NewBlock(block Block, data string) Block {\r\n\tt := time.Now().Unix()\r\n\tBlockID := block.BlockID\r\n\tBlockID++\r\n\thashed := sha256.Sum256([]byte(data))\r\n\tsignature, err := rsa.SignPKCS1v15(rand.Reader, nodeinfo.PrivateKey, crypto.SHA256, hashed[:])\r\n\tif err != nil {\r\n\t\tlog.Fatalln(err)\r\n\t}\r\n\tnonce, hash := computeHashWithProofOfWork(IntToStr(BlockID)+IntToStr(t)+data+string(signature)+nodeinfo.NodeID+block.Hash, nodeinfo.Difficulty)\r\n\treturn Block{BlockID, t, data, signature, nodeinfo.NodeID, block.Hash, hash, nonce}\r\n}", "func newChunkBlock(chunks []*chunk, reporter errorLocationReporter) *chunk {\n\tr := newChunk(CHUNK_BLOCK, reporter)\n\tr.m[\"chunks\"] = chunks\n\treturn r\n}", "func getBlock(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\n\thash, err := chainhash.NewHashFromStr(ps.ByName(\"hash\"))\n\tif err != nil {\n\t\tlog.Printf(\"could not convert string to hash: %s\\n\", err)\n\t}\n\n\tblock, err := dao.GetBlock(hash)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Not found\")\n\t\treturn\n\t}\n\t//block.Confirmations = getBlockConfirmations(block)\n\t//block.Confirmations = getBlockConfirmations(*block) // needs dynamic calculation\n\n\t//apiblock, err := insight.ConvertToInsightBlock(block)\n\n\tjson.NewEncoder(w).Encode(&block)\n}", "func CreateBlock(transactions []*Transaction, prevHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevHash, []byte{}, 0}\n\tpow := CreatePoW(block)\n\tnonce, hash := pow.Mine()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewBlock(index idx.Block, time Timestamp, events hash.Events, prevHash hash.Event) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tTime: time,\n\t\tEvents: events,\n\t\tPrevHash: prevHash,\n\t\tSkippedTxs: make([]uint, 0),\n\t}\n}", "func handleWriteBlock(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar m model.Message\n\n\t// Decode http request into message struct\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&m); err != nil {\n\t\trespondWithJSON(w, r, http.StatusBadRequest, r.Body)\n\t\treturn\n\t}\n\n\t// checks if the password is correct\n\t// if !authenticate(m.Password) {\n\t// \trespondWithJSON(w, r, http.StatusUnauthorized, r.Body)\n\t// }\n\n\tdefer r.Body.Close()\n\n\t//ensure atomicity when creating new block\n\tvar mutex = &sync.Mutex{}\n\tmutex.Lock()\n\tnewBlock := blockchainhelpers.GenerateBlock(model.Blockchain[len(model.Blockchain)-1], m.BPM)\n\tmutex.Unlock()\n\n\tif blockchainhelpers.IsBlockValid(newBlock, model.Blockchain[len(model.Blockchain)-1]) {\n\t\tmodel.Blockchain = append(model.Blockchain, newBlock)\n\t\tspew.Dump(model.Blockchain)\n\t}\n\n\trespondWithJSON(w, r, http.StatusCreated, newBlock)\n\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tTimestamp: time.Now().Unix(),\n\t\tData: []byte(data),\n\t\tPrevBlockHash: prevBlockHash,\n\t\tHash: []byte{},\n\t}\n\tpow := NewProofOfWork(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewBlock(b *block.Block, chain blockchainer.Blockchainer) Block {\n\tres := Block{\n\t\tBlock: *b,\n\t\tBlockMetadata: BlockMetadata{\n\t\t\tSize: io.GetVarSize(b),\n\t\t\tConfirmations: chain.BlockHeight() - b.Index + 1,\n\t\t},\n\t}\n\n\thash := chain.GetHeaderHash(int(b.Index) + 1)\n\tif !hash.Equals(util.Uint256{}) {\n\t\tres.NextBlockHash = &hash\n\t}\n\n\treturn res\n}", "func (a *insight) NewBlock(id interface{}) *block {\n\tb := new(block)\n\tb.insight = a\n\tswitch v := id.(type) {\n\tcase int:\n\t\tb.Height = int(v)\n\t\tb.hash()\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase string:\n\t\tb.Hash = string(v)\n\t\tb.pages()\n\t\tb.info()\n\t\treturn b\n\tcase nil:\n\t\treturn b.latestBlock()\n\t}\n\treturn nil\n}", "func mockBlock(height uint32, txs ...*types.Transaction) *types.Block {\n\treturn &types.Block{\n\t\tHeader: types.Header{\n\t\t\tHeight: height,\n\t\t},\n\t\tTransactions: txs,\n\t}\n}", "func (prev_block Block) Next(data string) Block {\n\t// TODO\n\tprevHash := prev_block.Hash\n\tgen := prev_block.Generation + 1\n\tdif := prev_block.Difficulty\n\tvar p uint64\n\tvar h []byte\n\n\tb := Block{prevHash, gen, dif, data, p, h}\n\treturn b\n}", "func AddBlock(block *types.Block, db *types.DB) {\n\ttxCheck := func(txs []*types.Tx) bool {\n\t\t// start = copy.deepcopy(txs)\n\t\tvar start = txs\n\t\tvar txsSource []*types.Tx\n\t\tvar startCopy []*types.Tx\n\n\t\tfor !reflect.DeepEqual(start, startCopy) {\n\t\t\t// Block passes this test\n\t\t\tif start == nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// startCopy = copy.deepcopy(start)\n\t\t\tstartCopy = start\n\t\t\tlast := start[len(start)-1]\n\n\t\t\t// transactions.tx_check[start[-1]['type']](start[-1], out, DB)\n\t\t\tfn := transactionVerify[last.Type]\n\t\t\tif fn(last, txsSource, db) {\n\t\t\t\t// start.pop()\n\t\t\t\tstart = start[:len(start)-1]\n\t\t\t\ttxsSource = append(txsSource, last)\n\t\t\t} else {\n\t\t\t\t// Block is invalid\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// Block is invalid\n\t\treturn true\n\t}\n\n\t// if \"error\" in block: return False\n\tif block.Error != nil {\n\t\treturn\n\t}\n\n\t// if \"length\" not in block: return False\n\t// NOTE: block.Length not being set means it takes its \"zero value\".\n\t// This shouldn't be a problem, check out next if stmt.\n\tif block.Length == 0 {\n\t\treturn\n\t}\n\n\tlength := db.Length\n\tif block.Length != length+1 {\n\t\treturn\n\t}\n\n\tif block.DiffLength != HexSum(db.DiffLength, HexInv(block.Target)) {\n\t\treturn\n\t}\n\n\tif length >= 0 && tools.DetHash(db.GetBlock(length)) != block.PrevHash {\n\t\treturn\n\t}\n\n\t// a = copy.deepcopy(block)\n\t// a.pop(\"nonce\")\n\tblockCopy := block\n\tblockCopy.Nonce = nil\n\n\t//if \"target\" not in block.keys(): return False\n\tif block.Target == \"\" {\n\t\treturn\n\t}\n\n\thalfWay := &types.HalfWay{\n\t\tNonce: block.Nonce,\n\t\tHalfHash: tools.DetHash(blockCopy),\n\t}\n\n\tif tools.DetHash(halfWay) > block.Target {\n\t\treturn\n\t}\n\n\tif block.Target != Target(db, block.Length) {\n\t\treturn\n\t}\n\n\t// TODO: Figure out why 8 (length)?\n\tearliestMedian := median(RecentBlockTimes(db, config.Get().Mmm, 8))\n\t// `float64` (unix epoch) back to `time.Time`\n\tsec, nsec := math.Modf(earliestMedian)\n\tearliest := time.Unix(int64(sec), int64(nsec*1e9))\n\n\t// if block.Time > time.time(): return false\n\t// if block.Time < earliest: return false\n\tif block.Time.After(time.Now()) || block.Time.Before(earliest) {\n\t\treturn\n\t}\n\n\tif txCheck(block.Txs) {\n\t\treturn\n\t}\n\n\t// block_check was unnecessary because it was only called once\n\t// and it only returned true at its end\n\n\t// if block_check(block, db):\n\tlog.Println(\"add_block:\", block)\n\tdb.Put(strconv.Itoa(block.Length), block)\n\n\tdb.Length = block.Length\n\tdb.DiffLength = block.DiffLength\n\n\torphans := db.Txs\n\tdb.Txs = nil\n\n\tfor _, tx := range block.Txs {\n\t\tdb.AddBlock = true\n\t\tfn := transactionUpdate[tx.Type]\n\t\tfn(tx, db)\n\t}\n\n\tfor _, tx := range orphans {\n\t\tAddTx(tx, db)\n\t}\n}", "func (ob *Observer) updateBlock(curHeight, nextHeight int64, curBlockHash string) error {\n\tblock, err := ob.deps.Recorder.Block(nextHeight)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[Observer.updateBlock]: failed to get block info, height=%d\", nextHeight)\n\t}\n\n\tif curHeight != 0 && block.ParentBlockHash != curBlockHash {\n\t\tif err := ob.DeleteBlock(curHeight); err != nil {\n\t\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to delete a forked block\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := ob.RecordBlockAndTxs(block); err != nil {\n\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to save and process block\")\n\t}\n\n\treturn nil\n}", "func (app *App) BeginBlock(req abci.RequestBeginBlock) abci.ResponseBeginBlock {\n\tres := app.BandApp.BeginBlock(req)\n\tapp.accsInBlock = make(map[string]bool)\n\tapp.accsInTx = make(map[string]bool)\n\tapp.msgs = []Message{}\n\tif app.emitStartState {\n\t\tapp.emitStartState = false\n\t\tapp.emitNonHistoricalState()\n\t} else {\n\t\t{\n\t\t\tfor _, val := range req.GetLastCommitInfo().Votes {\n\t\t\t\tvalidator := app.StakingKeeper.ValidatorByConsAddr(app.DeliverContext, val.GetValidator().Address)\n\t\t\t\tapp.Write(\"NEW_VALIDATOR_VOTE\", JsDict{\n\t\t\t\t\t\"consensus_address\": validator.GetConsAddr().String(),\n\t\t\t\t\t\"block_height\": req.Header.GetHeight() - 1,\n\t\t\t\t\t\"voted\": val.GetSignedLastBlock(),\n\t\t\t\t})\n\t\t\t\tapp.emitUpdateValidatorRewardAndAccumulatedCommission(validator.GetOperator())\n\t\t\t}\n\t\t}\n\t}\n\tapp.Write(\"NEW_BLOCK\", JsDict{\n\t\t\"height\": req.Header.GetHeight(),\n\t\t\"timestamp\": app.DeliverContext.BlockTime().UnixNano(),\n\t\t\"proposer\": sdk.ConsAddress(req.Header.GetProposerAddress()).String(),\n\t\t\"hash\": req.GetHash(),\n\t\t\"inflation\": app.MintKeeper.GetMinter(app.DeliverContext).Inflation.String(),\n\t\t\"supply\": app.SupplyKeeper.GetSupply(app.DeliverContext).GetTotal().String(),\n\t})\n\tfor _, event := range res.Events {\n\t\tapp.handleBeginBlockEndBlockEvent(event)\n\t}\n\n\treturn res\n}", "func (bc *Blockchain) createBlock() {\n\tnonce := bc.proofOfWork()\n\tpreviousHash := bc.lastBlock().Hash()\n\tbc.chainNewBlock(nonce, previousHash)\n}", "func NewBlock(index uint64, ordered Events) *Block {\n\tevents := make(hash.EventsSlice, len(ordered))\n\tfor i, e := range ordered {\n\t\tevents[i] = e.Hash()\n\t}\n\n\treturn &Block{\n\t\tIndex: index,\n\t\tEvents: events,\n\t}\n}", "func CreateBlock(data string, prevHash []byte) *Block {\n\tblock := &Block{[]byte{}, []byte(data), prevHash, 0}\n\tpow := NewProof(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func (self *BlockChain) NewBlock(proof int, previous_hash string) {\n\n\t// check if previous hash matches self.hash(self.chain[-1])\n\tt := time.Now()\n\n\tblock := Block{\n\t\tIndex: len(self.Chain) + 1,\n\t\tTimestamp: t.UnixNano(),\n\t\tTransactions: self.CurrentTransactions,\n\t\tProof: proof,\n\t\tPreviousHash: previous_hash}\n\n\t// Reset the current list of transactions\n\tself.CurrentTransactions = nil\n\tself.Chain = append(self.Chain, block)\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func (c *Chain) PushBlock(newBlock *core.Block) {\n\tmaybeWarnMultipleProduction(c.fdb, b.Num)\n\n\t// forkdb.PushBlock will set the head pointing to longest chain in forkdb.\n\terr := c.fdb.AppendBlock(newBlock)\n\tif err != nil {\n\t\tfmt.Errorf(\"invalid block, ignoring...\")\n\t\treturn\n\t}\n\n\tif newBlock.PrevBlockId == c.Head().ID {\n\t\tc.startUndoSession()\n\t\tok := c.ApplyBlock(newBlock)\n\t\tif ok {\n\t\t\t// if everything goes right, then gpo's head block will be updated to new head\n\t\t\t// and all cached values will be reloaded\n\t\t\t// Chain's push undo session should leave the operation logs for future popblock,\n\t\t\t// only block becomes irriverible, then commit the block/session/revision\n\t\t\t// each block has exactly one session/revision\n\t\t\t// c.setHead(newBlock) - NOT NECESSARY, since head is reloaded from gpo in pushundosession\n\t\t\tc.pushUndoSession()\n\t\t} else {\n\t\t\t// undo all operations on statusdb during ApplyBlock()\n\t\t\t// also reload all cached values during undo\n\t\t\tc.undo()\n\t\t\t// usally undo operation hase nothing to do with forkdb\n\t\t\t// BUT here, the block is invalid, so we need to remove it\n\t\t\t// before remove block, the system will unpack the tx and store them in pending_tx_list\n\t\t\tc.fdb.RemoveBlock(newBlock)\n\t\t\t// c.setHead(previous head) -- NOT NECCESSARY\n\t\t}\n\t} else {\n\t\tif newBlock.Num > c.Head().Num {\n\t\t\t// if the new block is not build off from current chain's head block\n\t\t\t// and also has bigger number, means it just created a new longest branch\n\t\t\t// so we need to switch to the new longest branch\n\t\t\tc.switchBranch(newBlock)\n\t\t}\n\t}\n}", "func isValidBlock(newBlock, oldBlock Block) bool {\n\tif oldBlock.Index+1 != newBlock.Index {\n\t\treturn false\n\t}\n\n\tif oldBlock.Hash != newBlock.PrevHash {\n\t\treturn false\n\t}\n\n\tif calculateBlockHash(newBlock) != newBlock.Hash {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c *Chain) GenerateBlock(when int, who string, privkey *ecdsa.PrivateKey) (*core.Block, error) {\n\tif when <= c.Gpo().Time || when != c.Gpo().Time+config.BlockInterval {\n\t\treturn nil, fmt.Errorf(\"incorrect time\")\n\t}\n\n\twitness, err := c.sdb.GetAccountByName(who)\n\tif err != nil || witness.PublicKey != utils.EncodePubKeyInPem(&privkey.PublicKey) {\n\t\treturn nil, fmt.Errorf(\"incorret witness or key\")\n\t}\n\n\tb := core.Block{\n\t\t// ID will be set later\n\t\tNum: c.Gpo().BlockNum,\n\t\tPrevBlockId: c.Gpo().BlockId,\n\t\tCreatedOn: when,\n\t\tWitness: who,\n\t}\n\n\t// move pending txs to block\n\tc.movePendingTransactionsToBlock(&b)\n\t//c.MoveTxToBlock(&b)\n\n\t// set b.ID\n\t// set b.MerkleRoot\n\treturn &b, nil\n}", "func NewBlock(data string, transactions []*Tx, prevBlockHash []byte) *Block {\n\tblock := &Block{\n\t\tIdentifier: internal.GenerateID(),\n\t\tData: []byte(data),\n\t\tTransactions: transactions,\n\t\tPrevBlockHash: prevBlockHash,\n\t\tTimestamp: time.Now().Unix(),\n\t}\n\n\tpow := NewPow(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\treturn block\n}", "func (s *service) MineNewBlock(lastBlock *Block, data []Transaction) (*Block, error) {\n\t// validations\n\tif lastBlock == nil {\n\t\treturn nil, ErrMissingLastBlock\n\t}\n\n\tdifficulty := lastBlock.Difficulty\n\tvar nonce uint32\n\tvar timestamp int64\n\tvar hash string\n\tfor {\n\t\tnonce++\n\t\ttimestamp = time.Now().UnixNano()\n\t\tdifficulty = adjustBlockDifficulty(*lastBlock, timestamp, s.MineRate)\n\t\thash = hashing.SHA256Hash(timestamp, *lastBlock.Hash, data, nonce, difficulty)\n\t\tif hexStringToBinary(hash)[:difficulty] == strings.Repeat(\"0\", int(difficulty)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn yieldBlock(timestamp, lastBlock.Hash, &hash, data, nonce, difficulty), nil\n}", "func CreateNewBlock(txs []*model.Transaction, prevHash string, reward float64, height int64, pk []byte, l *model.Ledger, difficulty int, ctl chan commands.Command) (*model.Block, commands.Command, []*model.Transaction, error) {\n\torigL := GetLedgerDeepCopy(l)\n\n\terrTxs, err := HandleTransactions(txs, l)\n\tif err != nil {\n\t\treturn nil, commands.NewDefaultCommand(), errTxs, err\n\t}\n\n\t// All transactions are valid if reached here, calculate transaction fee on the original ledger.\n\tfee, err := CalcTxFee(txs, origL)\n\tif err != nil {\n\t\tlog.Fatalln(\"there should never be a case where handle transaction success but fail calcFee\")\n\t}\n\n\tblock := model.Block{\n\t\tPrevHash: prevHash,\n\t\tTxs: txs,\n\t\tCoinbase: CreateCoinbaseTx(reward+fee, pk, height),\n\t}\n\n\tc, err := Mine(&block, difficulty, ctl)\n\treturn &block, c, []*model.Transaction{}, err\n}", "func newBlocksURL(query map[string]string) url.URL {\n\tu, _ := url.Parse(\"/blocks\")\n\tif query == nil {\n\t\tquery = map[string]string{}\n\t}\n\tquery[\"expand\"] = \"payload\"\n\n\treturn addQuery(u, query)\n}", "func (I *Blockchain) NewBlock(proof uint64, previousHash string) {\n\t// In order to be able to create the first block\n\tif previousHash == \"\" {\n\t\tpreviousHash = \"1\"\n\t}\n\t// Create the block\n\tb := block{\n\t\tindex: I.currentIndex,\n\t\ttimestamp: time.Now().UnixNano(),\n\t\tproof: proof,\n\t\tpreviousHash: previousHash,\n\t\ttransactions: I.currentTransactions,\n\t}\n\t// Append the new block\n\tI.blocks = append(I.blocks, b)\n\t// Reset the transactions\n\tI.currentTransactions = make([]transaction, 0)\n\t// Update the index\n\tI.currentIndex += 1\n\t// Modify the last block variable\n\tI.lastBlock = b\n}", "func (app *BurrowMint) BeginBlock(hash []byte, header *abci.Header) {\n\n}", "func (s *BlockchainService) Add(payload int) (Block, error) {\n\ts.mutex.Lock()\n\n\tnewBlock := s.generateBlock(s.chain[len(s.chain)-1], payload)\n\n\tif isBlockValid(&newBlock, s.chain[len(s.chain)-1]) {\n\t\tnewBlockchain := append(s.chain, &newBlock)\n\t\ts.replaceChain(newBlockchain)\n\t\tspew.Dump(s.chain)\n\n\t\ts.mutex.Unlock()\n\n\t\treturn newBlock, nil\n\t}\n\n\ts.mutex.Unlock()\n\n\treturn Block{}, errors.New(\"Failed to add new block for payload\")\n}", "func GenerateOpBlock() (hash string, b shared.Block, success bool) {\n\tfmt.Println(\"Generate Op Block\")\n\n\tb = shared.Block{PreviousBlockHash: prevHash, MinerKey: minerPrivateKey.PublicKey}\n\toperationsToAdd, intersection := getOperationsToArrayToAddBlock()\n\tif intersection {\n\t\treturn \"\", shared.Block{}, false\n\t}\n\tb.Operations = operationsToAdd\n\tblockString := ConvertBlockToString(b)\n\tnonce, hash := FindSecret(blockString, minerNetSettings.PoWDifficultyOpBlock)\n\tb.Nonce = nonce\n\tb.Hash = hash\n\n\tsuccess = FloodBlock(b)\n\n\t// valid := true\n\tif verification.VerifyBlock(b, blockChain, minerNetSettings, existingBlockHashes, allShapes) {\n\t\tinkBank += minerNetSettings.InkPerOpBlock\n\t}\n\n\t// Adding the new block to the block chain\n\tif success {\n\t\tUpdateBlockChain(b)\n\t}\n\n\tfmt.Println(\"Done GenerateOpBlock\")\n\n\t// verify block here\n\treturn hash, b, success\n}", "func NewBlock(sigKey ed25519.PrivateKey, previousBlock BlockID, txs []*Transaction) (*Block, error) {\n\trand_bytes := make([]byte, 8)\n\t_, err := rand.Read(rand_bytes)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get Random data\")\n\t}\n\ttemp := binary.LittleEndian.Uint64(rand_bytes)\n\tb := &Block{\n\t\tHeader: &BlockHeader{\n\t\t\tVersion: 0,\n\t\t\tPreviousBlock: previousBlock,\n\t\t\tTimestamp: 0, // XXX: Populate this correctly.\n\t\t\tRandom: temp,\n\t\t},\n\t\tTransactions: &Transactions{Transactions: txs},\n\t}\n\n\tb.Header.MerkleRoot, err = b.MerkleRoot()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to compute merkle root\")\n\t}\n\n\tbid := b.BlockID()\n\tb.Header.Signature = ed25519.Sign(sigKey, bid[:])\n\n\treturn b, nil\n}", "func NewBlock(index int, data interface{}, date time.Time) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tDate: date,\n\t\tData: data,\n\t}\n}", "func processBlock(payload []byte) {\n\tvar block *protocol.Block\n\tblock = block.Decode(payload)\n\n\t//Block already confirmed and validated\n\tif storage.ReadClosedBlock(block.Hash) != nil {\n\t\tlogger.Printf(\"Received block (%x) has already been validated.\\n\", block.Hash[0:8])\n\t\treturn\n\t}\n\n\t//Append received Block to stash\n\tstorage.WriteToReceivedStash(block)\n\n\t//Start validation process\n\terr := validate(block, false)\n\tif err == nil {\n\t\tlogger.Printf(\"Validated block (received): %vState:\\n%v\", block, getState())\n\t\tbroadcastBlock(block)\n\t\tCalculateBlockchainSize(block.GetSize())\n\t} else {\n\t\tlogger.Printf(\"Received block (%x) could not be validated: %v\\n\", block.Hash[0:8], err)\n\t}\n}", "func (g *testGenerator) updateBlockState(oldBlockName string, oldBlockHash chainhash.Hash, newBlockName string, newBlock *wire.MsgBlock) {\n\t// Remove existing entries.\n\tdelete(g.blocks, oldBlockHash)\n\tdelete(g.blocksByName, oldBlockName)\n\n\t// Add new entries.\n\tnewBlockHash := newBlock.BlockHash()\n\tg.blocks[newBlockHash] = newBlock\n\tg.blocksByName[newBlockName] = newBlock\n}", "func (b *BlockChain) MineBlock(txns []*Transaction) {\n\t// construct new block and prev hash will be current tip of db\n\tblock := NewBlock(txns, b.tip)\n\n\terr := b.db.Update(func(tx *bolt.Tx) error {\n\t\tbckt := tx.Bucket([]byte(blocksBucket))\n\t\tif err := bckt.Put(block.Hash, block.Serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := bckt.Put([]byte(\"l\"), block.Hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.tip = block.Hash\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"AddBlock :\", err)\n\t}\n}", "func CopyBlocks(ctx context.Context, blocksQuery *ent.BlockQuery, addToFlow func(b *ent.BlockCreate)) error {\n\tclient := ent.FromContext(ctx)\n\tblocks, err := blocksQuery.\n\t\tWithSubFlow().\n\t\tWithGotoBlock().\n\t\tWithEntryPoint().\n\t\tWithExitPoints().\n\t\tAll(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch flow blocks: %w\", err)\n\t}\n\toldToNewBlock := make(map[int]*ent.Block, len(blocks))\n\toldToNewEntryPoint := make(map[int]*ent.EntryPoint)\n\toldToNewExitPoint := make(map[int]*ent.ExitPoint)\n\tfor _, blk := range blocks {\n\t\tblockCreate := client.Block.Create().\n\t\t\tSetCid(blk.Cid).\n\t\t\tSetType(blk.Type).\n\t\t\tSetStartParamDefinitions(blk.StartParamDefinitions).\n\t\t\tSetNillableTriggerType(blk.TriggerType).\n\t\t\tSetNillableActionType(blk.ActionType).\n\t\t\tSetUIRepresentation(blk.UIRepresentation)\n\t\taddToFlow(blockCreate)\n\t\tif blk.Edges.SubFlow != nil {\n\t\t\tblockCreate.SetSubFlow(blk.Edges.SubFlow)\n\t\t}\n\t\tnewBlock, err := blockCreate.Save(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create new block: %w\", err)\n\t\t}\n\t\toldToNewBlock[blk.ID] = newBlock\n\t\tif blk.Edges.EntryPoint != nil {\n\t\t\tentryPoint := blk.Edges.EntryPoint\n\t\t\tnewEntryPoint, err := getDefaultEntryPoint(ctx, newBlock)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toldToNewEntryPoint[entryPoint.ID] = newEntryPoint\n\t\t}\n\t\tfor _, exitPoint := range blk.Edges.ExitPoints {\n\t\t\tnewExitPoint, err := getOrCreateExitPoint(ctx, exitPoint, newBlock)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\toldToNewExitPoint[exitPoint.ID] = newExitPoint\n\t\t}\n\t}\n\tif err := copyConnectors(ctx, oldToNewEntryPoint, oldToNewExitPoint); err != nil {\n\t\treturn err\n\t}\n\tfor _, blk := range blocks {\n\t\tnewBlock := oldToNewBlock[blk.ID]\n\t\tswitch newBlock.Type {\n\t\tcase block.TypeEnd, block.TypeDecision, block.TypeSubFlow, block.TypeTrigger, block.TypeAction, block.TypeTrueFalse:\n\t\t\tif err := copyInputParams(ctx, blk, oldToNewBlock); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase block.TypeGoTo:\n\t\t\tnewGotoBlock, ok := oldToNewBlock[blk.Edges.GotoBlock.ID]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"failed to find goto block: %v\", blk.Edges.GotoBlock.ID)\n\t\t\t}\n\t\t\tif err := newBlock.Update().\n\t\t\t\tSetGotoBlock(newGotoBlock).\n\t\t\t\tExec(ctx); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update goto block: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func TestGraphQLBlockSerialization(t *testing.T) {\n\tstack := createNode(t, true, false)\n\tdefer stack.Close()\n\t// start node\n\tif err := stack.Start(); err != nil {\n\t\tt.Fatalf(\"could not start node: %v\", err)\n\t}\n\n\tfor i, tt := range []struct {\n\t\tbody string\n\t\twant string\n\t\tcode int\n\t}{\n\t\t{ // Should return latest block\n\t\t\tbody: `{\"query\": \"{block{number}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":{\"number\":10}}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{ // Should return info about latest block\n\t\t\tbody: `{\"query\": \"{block{number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":{\"number\":10,\"gasUsed\":0,\"gasLimit\":11500000}}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:0){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":{\"number\":0,\"gasUsed\":0,\"gasLimit\":11500000}}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:-1){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":null}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:-500){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":null}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:\\\"0\\\"){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":{\"number\":0,\"gasUsed\":0,\"gasLimit\":11500000}}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:\\\"-33\\\"){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":null}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:\\\"1337\\\"){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"data\":{\"block\":null}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:\\\"0xbad\\\"){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"errors\":[{\"message\":\"strconv.ParseInt: parsing \\\"0xbad\\\": invalid syntax\"}],\"data\":{}}`,\n\t\t\tcode: 400,\n\t\t},\n\t\t{ // hex strings are currently not supported. If that's added to the spec, this test will need to change\n\t\t\tbody: `{\"query\": \"{block(number:\\\"0x0\\\"){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"errors\":[{\"message\":\"strconv.ParseInt: parsing \\\"0x0\\\": invalid syntax\"}],\"data\":{}}`,\n\t\t\tcode: 400,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{block(number:\\\"a\\\"){number,gasUsed,gasLimit}}\",\"variables\": null}`,\n\t\t\twant: `{\"errors\":[{\"message\":\"strconv.ParseInt: parsing \\\"a\\\": invalid syntax\"}],\"data\":{}}`,\n\t\t\tcode: 400,\n\t\t},\n\t\t{\n\t\t\tbody: `{\"query\": \"{bleh{number}}\",\"variables\": null}\"`,\n\t\t\twant: `{\"errors\":[{\"message\":\"Cannot query field \\\"bleh\\\" on type \\\"Query\\\".\",\"locations\":[{\"line\":1,\"column\":2}]}]}`,\n\t\t\tcode: 400,\n\t\t},\n\t\t// should return `estimateGas` as decimal\n\t\t{\n\t\t\tbody: `{\"query\": \"{block{ estimateGas(data:{}) }}\"}`,\n\t\t\twant: `{\"data\":{\"block\":{\"estimateGas\":53000}}}`,\n\t\t\tcode: 200,\n\t\t},\n\t\t// should return `status` as decimal\n\t\t{\n\t\t\tbody: `{\"query\": \"{block {number call (data : {from : \\\"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\\\", to: \\\"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\\\", data :\\\"0x12a7b914\\\"}){data status}}}\"}`,\n\t\t\twant: `{\"data\":{\"block\":{\"number\":10,\"call\":{\"data\":\"0x\",\"status\":1}}}}`,\n\t\t\tcode: 200,\n\t\t},\n\t} {\n\t\tresp, err := http.Post(fmt.Sprintf(\"%s/graphql\", stack.HTTPEndpoint()), \"application/json\", strings.NewReader(tt.body))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not post: %v\", err)\n\t\t}\n\t\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not read from response body: %v\", err)\n\t\t}\n\t\tif have := string(bodyBytes); have != tt.want {\n\t\t\tt.Errorf(\"testcase %d %s,\\nhave:\\n%v\\nwant:\\n%v\", i, tt.body, have, tt.want)\n\t\t}\n\t\tif tt.code != resp.StatusCode {\n\t\t\tt.Errorf(\"testcase %d %s,\\nwrong statuscode, have: %v, want: %v\", i, tt.body, resp.StatusCode, tt.code)\n\t\t}\n\t}\n}", "func DeepCopyBlock(b *SignedBlock) (*SignedBlock, error) {\n\tres := &SignedBlock{\n\t\tSignedBlockHeader: eos.SignedBlockHeader{\n\t\t\tBlockHeader: eos.BlockHeader{\n\t\t\t\tTimestamp: BlockTimestamp{Time: b.Timestamp.UTC()},\n\t\t\t\tProducer: b.Producer,\n\t\t\t\tConfirmed: b.Confirmed,\n\t\t\t\tPrevious: CopyChecksum256(b.Previous),\n\t\t\t\tTransactionMRoot: CopyChecksum256(b.TransactionMRoot),\n\t\t\t\tActionMRoot: CopyChecksum256(b.ActionMRoot),\n\t\t\t\tScheduleVersion: b.ScheduleVersion,\n\t\t\t\tHeaderExtensions: make([]*eos.Extension, 0, len(b.HeaderExtensions)),\n\t\t\t},\n\t\t\tProducerSignature: CopySignature(b.ProducerSignature),\n\t\t},\n\t\tTransactions: make([]eos.TransactionReceipt, 0, len(b.Transactions)),\n\t\tBlockExtensions: make([]*eos.Extension, 0, len(b.BlockExtensions)),\n\t}\n\n\tif b.NewProducersV1 != nil {\n\t\tres.NewProducersV1 = &eos.ProducerSchedule{\n\t\t\tVersion: b.NewProducersV1.Version,\n\t\t\tProducers: make([]eos.ProducerKey, 0, len(b.NewProducersV1.Producers)),\n\t\t}\n\n\t\tfor _, prod := range b.NewProducersV1.Producers {\n\t\t\tres.NewProducersV1.Producers = append(res.NewProducersV1.Producers, eos.ProducerKey{\n\t\t\t\tAccountName: prod.AccountName,\n\t\t\t\tBlockSigningKey: prod.BlockSigningKey,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, ext := range b.HeaderExtensions {\n\t\tres.HeaderExtensions = append(res.HeaderExtensions, CopyExt(ext))\n\t}\n\n\tfor _, ext := range b.BlockExtensions {\n\t\tres.BlockExtensions = append(res.BlockExtensions, CopyExt(ext))\n\t}\n\n\tfor _, trx := range b.Transactions {\n\t\ttrxCopy := eos.TransactionReceipt{\n\t\t\tTransactionReceiptHeader: trx.TransactionReceiptHeader,\n\t\t\tTransaction: eos.TransactionWithID{\n\t\t\t\tID: CopyChecksum256(trx.Transaction.ID),\n\t\t\t\tPacked: &eos.PackedTransaction{\n\t\t\t\t\tSignatures: make([]ecc.Signature, 0, len(trx.Transaction.Packed.Signatures)),\n\t\t\t\t\tCompression: trx.Transaction.Packed.Compression,\n\t\t\t\t\tPackedContextFreeData: CopyBytes(trx.Transaction.Packed.PackedContextFreeData),\n\t\t\t\t\tPackedTransaction: CopyBytes(trx.Transaction.Packed.PackedTransaction),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tfor _, s := range trx.Transaction.Packed.Signatures {\n\t\t\ttrxCopy.Transaction.Packed.Signatures = append(trxCopy.Transaction.Packed.Signatures, CopySignature(s))\n\t\t}\n\t\tres.Transactions = append(res.Transactions, trxCopy)\n\t}\n\n\treturn res, nil\n}", "func (build *blockBuilder) Now() (chained.Block, error) {\n\n\tif build.blk == nil {\n\t\treturn nil, errors.New(\"the validated block is mandatory in order to build a Block instance\")\n\t}\n\n\tif build.met == nil {\n\n\t\tif build.id == nil {\n\t\t\treturn nil, errors.New(\"the ID is mandatory in order to build a Block instance\")\n\t\t}\n\n\t\tif build.prevID == nil {\n\t\t\treturn nil, errors.New(\"the previous ID is mandatory in order to build a Block instance\")\n\t\t}\n\n\t\tif build.crOn == nil {\n\t\t\treturn nil, errors.New(\"the previous ID is mandatory in order to build a Block instance\")\n\t\t}\n\n\t\tblocks := [][]byte{\n\t\t\tbuild.id.Bytes(),\n\t\t\t[]byte(strconv.Itoa(int(build.crOn.UnixNano()))),\n\t\t\tbuild.prevID.Bytes(),\n\t\t\tbuild.blk.GetMetaData().GetHashTree().GetHash().Get(),\n\t\t}\n\n\t\tht, htErr := build.htBuilderFactory.Create().Create().WithBlocks(blocks).Now()\n\t\tif htErr != nil {\n\t\t\treturn nil, htErr\n\t\t}\n\n\t\tmet, metErr := build.metaDataBuilderFactory.Create().Create().WithID(build.id).WithPreviousID(build.prevID).WithHashTree(ht).CreatedOn(*build.crOn).Now()\n\t\tif metErr != nil {\n\t\t\treturn nil, metErr\n\t\t}\n\n\t\tbuild.met = met\n\n\t}\n\n\tif build.met == nil {\n\t\treturn nil, errors.New(\"the MetaData is mandatory in order to build a Block instance\")\n\t}\n\n\tout := createBlock(build.met.(*MetaData), build.blk.(*concrete_validated.Block))\n\treturn out, nil\n}", "func FormatBlock(\n\theader tmtypes.Header, size int, gasLimit int64,\n\tgasUsed *big.Int, transactions interface{}, bloom ethtypes.Bloom,\n) map[string]interface{} {\n\tif len(header.DataHash) == 0 {\n\t\theader.DataHash = tmbytes.HexBytes(common.Hash{}.Bytes())\n\t}\n\n\treturn map[string]interface{}{\n\t\t\"number\": hexutil.Uint64(header.Height),\n\t\t\"hash\": hexutil.Bytes(header.Hash()),\n\t\t\"parentHash\": hexutil.Bytes(header.LastBlockID.Hash),\n\t\t\"nonce\": hexutil.Uint64(0), // PoW specific\n\t\t\"sha3Uncles\": common.Hash{}, // No uncles in Tendermint\n\t\t\"logsBloom\": bloom,\n\t\t\"transactionsRoot\": hexutil.Bytes(header.DataHash),\n\t\t\"stateRoot\": hexutil.Bytes(header.AppHash),\n\t\t\"miner\": common.Address{},\n\t\t\"mixHash\": common.Hash{},\n\t\t\"difficulty\": 0,\n\t\t\"totalDifficulty\": 0,\n\t\t\"extraData\": hexutil.Uint64(0),\n\t\t\"size\": hexutil.Uint64(size),\n\t\t\"gasLimit\": hexutil.Uint64(gasLimit), // Static gas limit\n\t\t\"gasUsed\": (*hexutil.Big)(gasUsed),\n\t\t\"timestamp\": hexutil.Uint64(header.Time.Unix()),\n\t\t\"transactions\": transactions.([]common.Hash),\n\t\t\"uncles\": []string{},\n\t\t\"receiptsRoot\": common.Hash{},\n\t}\n}", "func (d *Data) mutateBlock(ctx *datastore.VersionedCtx, mutID uint64, chunkPt dvid.ChunkPoint3d, prev, data []byte, batcher storage.KeyValueBatcher) {\n\t// Get the synaptic elements for this block\n\ttk := NewBlockTKey(chunkPt)\n\telems, err := getElements(ctx, tk)\n\tif err != nil {\n\t\tdvid.Errorf(\"err getting elements for block %s: %v\\n\", chunkPt, err)\n\t\treturn\n\t}\n\tif len(elems) == 0 {\n\t\treturn\n\t}\n\tblockSize := d.blockSize()\n\tbatch := batcher.NewBatch(ctx)\n\n\t// Compute the strides (in bytes)\n\tbX := blockSize[0] * 8\n\tbY := blockSize[1] * bX\n\n\t// Iterate through all element positions, finding corresponding label and storing elements.\n\tvar delta DeltaModifyElements\n\tlabels := make(map[uint64]struct{})\n\ttoAdd := LabelElements{}\n\ttoDel := LabelPoints{}\n\tfor n := range elems {\n\t\tpt := elems[n].Pos.Point3dInChunk(blockSize)\n\t\ti := pt[2]*bY + pt[1]*bX + pt[0]*8\n\t\tlabel := binary.LittleEndian.Uint64(data[i : i+8])\n\t\tvar old uint64\n\t\tif len(prev) != 0 {\n\t\t\told = binary.LittleEndian.Uint64(prev[i : i+8])\n\t\t}\n\t\tif label != 0 {\n\t\t\ttoAdd.add(label, elems[n].ElementNR)\n\t\t\tlabels[label] = struct{}{}\n\t\t\tdelta.Add = append(delta.Add, ElementPos{Label: label, Kind: elems[n].Kind, Pos: elems[n].Pos})\n\t\t}\n\t\tif old != 0 {\n\t\t\ttoDel.add(old, elems[n].Pos)\n\t\t\tlabels[old] = struct{}{}\n\t\t\tdelta.Del = append(delta.Del, ElementPos{Label: old, Kind: elems[n].Kind, Pos: elems[n].Pos})\n\t\t}\n\t}\n\n\t// Modify any modified label k/v.\n\tfor label := range labels {\n\t\ttk := NewLabelTKey(label)\n\t\tlabelElems, err := getElementsNR(ctx, tk)\n\t\tif err != nil {\n\t\t\tdvid.Errorf(\"err getting elements for label %d: %v\\n\", label, err)\n\t\t\treturn\n\t\t}\n\t\tdeletions, found := toDel[label]\n\t\tif found {\n\t\t\tfor _, pt := range deletions {\n\t\t\t\tlabelElems.delete(pt)\n\t\t\t}\n\t\t}\n\t\tadditions, found := toAdd[label]\n\t\tif found {\n\t\t\tlabelElems.add(additions)\n\t\t}\n\t\tval, err := json.Marshal(labelElems)\n\t\tif err != nil {\n\t\t\tdvid.Errorf(\"couldn't serialize annotation elements in instance %q: %v\\n\", d.DataName(), err)\n\t\t\treturn\n\t\t}\n\t\tbatch.Put(tk, val)\n\t}\n\tif err := batch.Commit(); err != nil {\n\t\tdvid.Criticalf(\"bad commit in annotations %q after delete block: %v\\n\", d.DataName(), err)\n\t\treturn\n\t}\n\n\t// Notify any subscribers of label annotation changes.\n\tevt := datastore.SyncEvent{Data: d.DataUUID(), Event: ModifyElementsEvent}\n\tmsg := datastore.SyncMessage{Event: ModifyElementsEvent, Version: ctx.VersionID(), Delta: delta}\n\tif err := datastore.NotifySubscribers(evt, msg); err != nil {\n\t\tdvid.Criticalf(\"unable to notify subscribers of event %s: %v\\n\", evt, err)\n\t}\n\n\t// send kafka merge event to instance-uuid topic\n\tversionuuid, _ := datastore.UUIDFromVersion(ctx.VersionID())\n\tmsginfo := map[string]interface{}{\n\t\t\"Action\": \"mutate-block\",\n\t\t\"MutationID\": mutID,\n\t\t\"UUID\": string(versionuuid),\n\t\t\"Timestamp\": time.Now().String(),\n\t\t\"Delta\": delta,\n\t}\n\tjsonmsg, _ := json.Marshal(msginfo)\n\tif err := d.PublishKafkaMsg(jsonmsg); err != nil {\n\t\tdvid.Errorf(\"unable to write mutate-block to kafka for data %q: %v\\n\", d.DataName(), err)\n\t}\n}", "func newblock(prog *obj.Prog) *BasicBlock {\n\tif prog == nil {\n\t\tFatal(\"newblock: prog cannot be nil\")\n\t}\n\tresult := new(BasicBlock)\n\tresult.rpo = -1\n\tresult.mark = UNVISITED\n\tresult.first = prog\n\tresult.last = prog\n\tresult.pred = make([]*BasicBlock, 0, 2)\n\tresult.succ = make([]*BasicBlock, 0, 2)\n\treturn result\n}", "func CreateBlock(txs []*Transaction, prevHash []byte) *Block {\n\tblock := &Block{[]byte{}, txs, prevHash, 0}\n\tpow := NewProof(block)\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\treturn block\n}", "func replaceChain(newChain []Block) {\n\tif len(newChain) > len(BlockChain) {\n\t\tBlockChain = newChain\n\t}\n}", "func NewBlock(data *models.Block, opts ...options.Option[Block]) (newBlock *Block) {\n\treturn options.Apply(&Block{\n\t\tstrongChildren: make([]*Block, 0),\n\t\tweakChildren: make([]*Block, 0),\n\t\tlikedInsteadChildren: make([]*Block, 0),\n\t\tModelsBlock: data,\n\t}, opts)\n}", "func (e *emitter) emitBlock(name string, node ast.Expr) *mir.Block {\n\tlastInsn := e.emitInsn(node)\n\t// emitInsn() emits instructions in descending order.\n\t// Reverse the order to iterate instractions ascending order.\n\tfirstInsn := mir.Reverse(lastInsn)\n\treturn mir.NewBlock(name, firstInsn, lastInsn)\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func (b *BlockRaw) ToBlock() (*Block, StdError) {\n\tvar (\n\t\tNumber uint64\n\t\tAvgTime int64\n\t\tTxcounts uint64\n\t\tTransactions []TransactionInfo\n\t\terr error\n\t)\n\tif Number, err = strconv.ParseUint(b.Number, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(b.AvgTime, \"0x\") == 0 || strings.Index(b.AvgTime, \"-0x\") == 0 {\n\t\tb.AvgTime = strings.Replace(b.AvgTime, \"0x\", \"\", 1)\n\t}\n\tif AvgTime, err = strconv.ParseInt(b.AvgTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif Txcounts, err = strconv.ParseUint(b.TxCounts, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tfor _, t := range b.Transactions {\n\t\ttransactionInfo, err := t.ToTransaction()\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn nil, NewSystemError(err)\n\t\t}\n\t\tTransactions = append(Transactions, *transactionInfo)\n\t}\n\treturn &Block{\n\t\tVersion: b.Version,\n\t\tNumber: Number,\n\t\tHash: b.Hash,\n\t\tParentHash: b.ParentHash,\n\t\tWriteTime: b.WriteTime,\n\t\tAvgTime: AvgTime,\n\t\tTxCounts: Txcounts,\n\t\tMerkleRoot: b.MerkleRoot,\n\t\tTransactions: Transactions,\n\t}, nil\n}", "func (dao *blockDAO) putBlock(blk *block.Block) error {\n\tbatch := db.NewBatch()\n\n\theight := byteutil.Uint64ToBytes(blk.Height())\n\thash := blk.HashBlock()\n\tserHeader, err := blk.Header.Serialize()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize block header\")\n\t}\n\tserBody, err := blk.Body.Serialize()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize block body\")\n\t}\n\tserFooter, err := blk.Footer.Serialize()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize block footer\")\n\t}\n\tif dao.compressBlock {\n\t\ttimer := dao.timerFactory.NewTimer(\"compress_header\")\n\t\tserHeader, err = compress.Compress(serHeader)\n\t\ttimer.End()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error when compressing a block header\")\n\t\t}\n\t\ttimer = dao.timerFactory.NewTimer(\"compress_body\")\n\t\tserBody, err = compress.Compress(serBody)\n\t\ttimer.End()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error when compressing a block body\")\n\t\t}\n\t\ttimer = dao.timerFactory.NewTimer(\"compress_footer\")\n\t\tserFooter, err = compress.Compress(serFooter)\n\t\ttimer.End()\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"error when compressing a block footer\")\n\t\t}\n\t}\n\tbatch.Put(blockHeaderNS, hash[:], serHeader, \"failed to put block header\")\n\tbatch.Put(blockBodyNS, hash[:], serBody, \"failed to put block body\")\n\tbatch.Put(blockFooterNS, hash[:], serFooter, \"failed to put block footer\")\n\n\thashKey := append(hashPrefix, hash[:]...)\n\tbatch.Put(blockHashHeightMappingNS, hashKey, height, \"failed to put hash -> height mapping\")\n\n\theightKey := append(heightPrefix, height...)\n\tbatch.Put(blockHashHeightMappingNS, heightKey, hash[:], \"failed to put height -> hash mapping\")\n\n\tvalue, err := dao.kvstore.Get(blockNS, topHeightKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get top height\")\n\t}\n\ttopHeight := enc.MachineEndian.Uint64(value)\n\tif blk.Height() > topHeight {\n\t\tbatch.Put(blockNS, topHeightKey, height, \"failed to put top height\")\n\t}\n\n\tvalue, err = dao.kvstore.Get(blockNS, totalActionsKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get total actions\")\n\t}\n\ttotalActions := enc.MachineEndian.Uint64(value)\n\ttotalActions += uint64(len(blk.Actions))\n\ttotalActionsBytes := byteutil.Uint64ToBytes(totalActions)\n\tbatch.Put(blockNS, totalActionsKey, totalActionsBytes, \"failed to put total actions\")\n\n\tif !dao.writeIndex {\n\t\treturn dao.kvstore.Commit(batch)\n\t}\n\tif err := indexBlock(dao.kvstore, blk, batch); err != nil {\n\t\treturn err\n\t}\n\treturn dao.kvstore.Commit(batch)\n}", "func newBlockInventory(instance *BlockInstance, inv IInventory, ejectOnUnsubscribe bool, invTypeId InvTypeId) *blockInventory {\n blkInv := &blockInventory{\n inv: inv,\n subscribers: make(map[EntityId]IPlayerClient),\n ejectOnUnsubscribe: ejectOnUnsubscribe,\n invTypeId: invTypeId,\n }\n\n if instance != nil {\n blkInv.chunk = instance.Chunk\n blkInv.blockLoc = instance.BlockLoc\n }\n\n blkInv.inv.SetSubscriber(blkInv)\n\n return blkInv\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func AddBlock(b Block) error {\n\t// fmt.Println(\"******TODO: IMPLEMENT AddBlock!******\")\n\tspew.Dump(Blockchain)\n\t// Fill me in, brave wizard.\n\tprevBlock := Blockchain[len(Blockchain)-1]\n\t// fmt.Println(prevBlock)\n\t// fmt.Println(b)\n\tif bytes.Compare(b.PrevHash, prevBlock.Hash) != 0 {\n\t\t// return errors.New(\"Error block\")\n\t\treturn fmt.Errorf(\"New Block should have Hash: %x, but has Hash: %x\",\n\t\t\tprevBlock.Hash, b.PrevHash)\n\t}\n\tBlockchain = append(Blockchain, b)\n\treturn nil\n}", "func (d *Data) transcodeBlock(b blockData) (out []byte, err error) {\n\tformatIn, checksum := dvid.DecodeSerializationFormat(dvid.SerializationFormat(b.data[0]))\n\n\tvar start int\n\tif checksum == dvid.CRC32 {\n\t\tstart = 5\n\t} else {\n\t\tstart = 1\n\t}\n\n\tvar outsize uint32\n\n\tswitch formatIn {\n\tcase dvid.LZ4:\n\t\toutsize = binary.LittleEndian.Uint32(b.data[start : start+4])\n\t\tout = b.data[start+4:]\n\t\tif len(out) != int(outsize) {\n\t\t\terr = fmt.Errorf(\"block %s was corrupted lz4: supposed size %d but had %d bytes\", b.bcoord, outsize, len(out))\n\t\t\treturn\n\t\t}\n\tcase dvid.Uncompressed, dvid.Gzip:\n\t\toutsize = uint32(len(b.data[start:]))\n\t\tout = b.data[start:]\n\tdefault:\n\t\terr = fmt.Errorf(\"labelmap data was stored in unknown compressed format: %s\", formatIn)\n\t\treturn\n\t}\n\n\tvar formatOut dvid.CompressionFormat\n\tswitch b.compression {\n\tcase \"\", \"lz4\":\n\t\tformatOut = dvid.LZ4\n\tcase \"blocks\":\n\t\tformatOut = formatIn\n\tcase \"gzip\":\n\t\tformatOut = dvid.Gzip\n\tcase \"uncompressed\":\n\t\tformatOut = dvid.Uncompressed\n\tdefault:\n\t\terr = fmt.Errorf(\"unknown compression %q requested for blocks\", b.compression)\n\t\treturn\n\t}\n\n\tvar doMapping bool\n\tvar mapping *VCache\n\tif !b.supervoxels {\n\t\tif mapping, err = getMapping(d, b.v); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif mapping != nil && mapping.mapUsed {\n\t\t\tdoMapping = true\n\t\t}\n\t}\n\n\t// Need to do uncompression/recompression if we are changing compression or mapping\n\tvar uncompressed, recompressed []byte\n\tif formatIn != formatOut || b.compression == \"gzip\" || doMapping {\n\t\tswitch formatIn {\n\t\tcase dvid.LZ4:\n\t\t\tuncompressed = make([]byte, outsize)\n\t\t\tif err = lz4.Uncompress(out, uncompressed); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase dvid.Uncompressed:\n\t\t\tuncompressed = out\n\t\tcase dvid.Gzip:\n\t\t\tgzipIn := bytes.NewBuffer(out)\n\t\t\tvar zr *gzip.Reader\n\t\t\tzr, err = gzip.NewReader(gzipIn)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tuncompressed, err = ioutil.ReadAll(zr)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tzr.Close()\n\t\t}\n\n\t\tvar block labels.Block\n\t\tif err = block.UnmarshalBinary(uncompressed); err != nil {\n\t\t\terr = fmt.Errorf(\"unable to deserialize label block %s: %v\", b.bcoord, err)\n\t\t\treturn\n\t\t}\n\n\t\tif !b.supervoxels {\n\t\t\tmodifyBlockMapping(b.v, &block, mapping)\n\t\t}\n\n\t\tif b.compression == \"blocks\" { // send native DVID block compression with gzip\n\t\t\tout, err = block.CompressGZIP()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else { // we are sending raw block data\n\t\t\tuint64array, size := block.MakeLabelVolume()\n\t\t\texpectedSize := d.BlockSize().(dvid.Point3d)\n\t\t\tif !size.Equals(expectedSize) {\n\t\t\t\terr = fmt.Errorf(\"deserialized label block size %s does not equal data %q block size %s\", size, d.DataName(), expectedSize)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch formatOut {\n\t\t\tcase dvid.LZ4:\n\t\t\t\trecompressed = make([]byte, lz4.CompressBound(uint64array))\n\t\t\t\tvar size int\n\t\t\t\tif size, err = lz4.Compress(uint64array, recompressed); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\toutsize = uint32(size)\n\t\t\t\tout = recompressed[:outsize]\n\t\t\tcase dvid.Uncompressed:\n\t\t\t\tout = uint64array\n\t\t\tcase dvid.Gzip:\n\t\t\t\tvar gzipOut bytes.Buffer\n\t\t\t\tzw := gzip.NewWriter(&gzipOut)\n\t\t\t\tif _, err = zw.Write(uint64array); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tzw.Flush()\n\t\t\t\tzw.Close()\n\t\t\t\tout = gzipOut.Bytes()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func NewBlock(transactionPool *mempool, previousBlock *Block) *Block {\n\n\tcurrentBlock := Block{}\n\tcurrentBlock.PreviousBlock = previousBlock\n\n\t// First, select which transactions the block will contain\n\tselectedTransactions := selectTransactions(transactionPool)\n\tcurrentBlock.Transactions = selectedTransactions\n\n\t// Second, calculate the hash of the selected transactions\n\thashedTransaction := string(processTransactions(selectedTransactions))\n\thashedBlockData := hashedTransaction + currentBlock.Hash\n\tcurrentBlock.Hash = hashedBlockData\n\treturn &currentBlock\n}", "func (bc *Blockchain) chainNewBlock(nonce int, previousHash [32]byte) *Block {\n\tb := NewBlock(nonce, previousHash, bc.transactionPool)\n\tbc.chain = append(bc.chain, b)\n\tbc.transactionPool = []*Transaction{}\n\treturn b\n}" ]
[ "0.7882912", "0.75677776", "0.7454618", "0.740441", "0.7075559", "0.6992254", "0.695611", "0.6840896", "0.646973", "0.645678", "0.6430594", "0.6280684", "0.6150822", "0.6101972", "0.604691", "0.60240793", "0.60015756", "0.59656155", "0.5949742", "0.5923937", "0.5896824", "0.5883046", "0.5879155", "0.58695817", "0.5836307", "0.57753754", "0.5773185", "0.5755589", "0.5743179", "0.56896675", "0.5687846", "0.56852186", "0.5679116", "0.56700623", "0.56598777", "0.5656478", "0.56508183", "0.5650121", "0.56443495", "0.56439245", "0.56324446", "0.563231", "0.56303746", "0.5625296", "0.56216544", "0.5621033", "0.56171703", "0.56099355", "0.56077397", "0.5606031", "0.5601366", "0.56009644", "0.5593378", "0.55855024", "0.557482", "0.5572314", "0.55666035", "0.5559032", "0.5558595", "0.5557114", "0.55354345", "0.55353427", "0.5526195", "0.5511564", "0.5511205", "0.5500484", "0.5495502", "0.5492567", "0.54909754", "0.5489348", "0.5473568", "0.54582876", "0.54569066", "0.54502916", "0.5441924", "0.54316074", "0.54187566", "0.54146653", "0.5414013", "0.540953", "0.54020166", "0.5395534", "0.5379082", "0.5366937", "0.5365746", "0.53632665", "0.53613496", "0.53537166", "0.5348044", "0.53401124", "0.53395385", "0.53355575", "0.53328544", "0.53284216", "0.53179514", "0.53157246", "0.5314326", "0.531266", "0.5311301", "0.5307993" ]
0.79917556
0
Load Garages, Vehicles and Events in order to provide baseline data sets
func loadBaseData() error { err := fileToInterface(validGarageDataFile, &ValidGarages) if err != nil { log.Println("ERROR: Unable to load valid garage data") return err } err = fileToInterface(validVehicleDataFile, &ValidVehicles) if err != nil { log.Println("ERROR: Unable to load valid vehicles data") return err } err = fileToInterface(validEventDataFile, &ValidEvents) if err != nil { log.Println("ERROR: Unable to load valid events data") return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func loadData() {\r\n\tloadImages()\r\n\tsortPredictDetails()\t \r\n}", "func (al *AggregateLoader) Load() (retErr error) {\n\tlog.Println(\"loader started\")\n\tconfig := al.config\n\tignoreNew = config.IgnoreNew\n\tdg, err := dgraph.NewDgraphConnection(&dgraph.Config{\n\t\tHosts: config.Alpha,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//api.NewDgraphClient(server1),\n\n\t// Drop schema and all the data present in database\n\tif config.DropSchema {\n\t\tif err := dropSchema(dg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// creates schema whatever is present in database\n\tif config.CreateSchema {\n\t\tif err := createSchema(dg, config.SchemaFiles); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !(config.LoadMetadata || config.LoadEquipments || config.LoadStaticData) {\n\t\treturn\n\t}\n\n\tbatchSize = config.BatchSize\n\tfmt.Println(batchSize)\n\twg := new(sync.WaitGroup)\n\tch := make(chan *api.Mutation)\n\tdoneChan := make(chan struct{})\n\t// Load metadata from equipments files\n\tif config.LoadMetadata {\n\t\tfor _, filename := range config.MetadataFiles.EquipFiles {\n\t\t\twg.Add(1)\n\t\t\tgo func(fn string) {\n\t\t\t\tloadEquipmentMetadata(ch, doneChan, fn)\n\t\t\t\twg.Done()\n\t\t\t}(config.ScopeSkeleten + \"/\" + filename)\n\t\t}\n\t}\n\n\tml := &MasterLoader{}\n\n\tif config.LoadStaticData || config.LoadEquipments {\n\t\topts := badger.DefaultOptions(config.BadgerDir)\n\t\topts.Truncate = true\n\t\tdb, err := badger.Open(opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer db.Close()\n\n\t\tzero, err := grpc.Dial(config.Zero, grpc.WithInsecure())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer zero.Close()\n\n\t\txidMap = xidmap.New(db, zero, xidmap.Options{\n\t\t\tNumShards: 32,\n\t\t\tLRUSize: 4096,\n\t\t})\n\n\t\tdefer xidMap.EvictAll()\n\n\t\tfile := config.StateConfig\n\n\t\tm, err := newMasterLoaderFromFile(file)\n\t\tif err != nil {\n\t\t\tlogger.Log.Error(\"state file not found all data will be processod\", zap.String(\"state_file\", file), zap.Error(err))\n\t\t\tml = &MasterLoader{\n\t\t\t\tLoaders: make(map[string]*ScopeLoader),\n\t\t\t}\n\t\t} else {\n\t\t\tml = m\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif err := saveMaterLoaderTofile(file, ml); err != nil {\n\t\t\t\tlogger.Log.Error(\"cannot save state\", zap.Error(err))\n\t\t\t}\n\t\t}()\n\t}\n\n\t// load equipments using equiments types\n\t// Preconditions: equipment types must have been created\n\tif config.LoadEquipments {\n\t\teqTypes, err := config.Repository.EquipmentTypes(context.Background(), []string{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tlog.Println(config.EquipmentFiles)\n\t\t\tloadEquipments(ml, ch, config.MasterDir, config.Scopes, config.EquipmentFiles, eqTypes, doneChan)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\t// Load static data like products equipments that\n\t// Like Products,application,acquired rights,instances\n\tif config.LoadStaticData {\n\t\tfor _, ldr := range al.loaders {\n\t\t\twg.Add(1)\n\t\t\tgo func(l loader) {\n\t\t\t\tl.load(ml, dg, config.MasterDir, l.scopes, l.files, ch, doneChan)\n\t\t\t\twg.Done()\n\t\t\t}(ldr)\n\t\t}\n\t}\n\n\tmuRetryChan := make(chan *api.Mutation)\n\tac := new(AbortCounter)\n\n\tfilesProcessedChan := make(chan struct{})\n\n\tgo func() {\n\t\twg.Wait()\n\t\t// wg wait above will make sure that all the gouroutines possibly writing on this\n\t\t// channel are returened so that there are no panic if someone write on this channel.\n\t\tclose(filesProcessedChan)\n\t\tfmt.Println(\"file processing done\")\n\t}()\n\n\twg1 := new(sync.WaitGroup)\n\twg1.Add(1)\n\tgo func() {\n\t\thandleAborted(muRetryChan, ch, doneChan, ac)\n\t\twg1.Done()\n\t}()\n\twg1.Add(1)\n\tgo func() {\n\t\tsigChan := make(chan os.Signal)\n\t\tsignal.Notify(sigChan)\n\t\tselect {\n\t\tcase sig := <-sigChan:\n\t\t\tlog.Println(sig.String())\n\t\tcase <-filesProcessedChan:\n\t\t}\n\t\t// Close done chan\n\t\tclose(doneChan)\n\t\twg1.Done()\n\t\t// Close done chan\n\t}()\n\tmutations := 0\n\tnquads := 0\n\tt := time.Now()\n\n\tfor i := 0; i < 1; i++ {\n\t\twg1.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg1.Done()\n\t\t\tfor {\n\t\t\t\tvar mu *api.Mutation\n\t\t\t\tselect {\n\t\t\t\tcase mu = <-ch:\n\t\t\t\tcase <-filesProcessedChan:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif _, err := dg.NewTxn().Mutate(context.Background(), mu); err != nil {\n\t\t\t\t\t// TODO : do not return here directly make an error and return\n\t\t\t\t\tmuRetryChan <- mu\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t\tmutations++\n\t\t\t\tnquads += len(mu.Set)\n\t\t\t\tfmt.Printf(\"time elapsed[%v], completed mutations: %v, edges_total:%v,edges this mutation: %v \\n\", time.Now().Sub(t), mutations, nquads, len(mu.Set))\n\t\t\t\t// log.Println(ass.GetUids())\n\t\t\t}\n\t\t}()\n\t}\n\twg1.Wait()\n\tif ac.Count() != 0 {\n\t\treturn fmt.Errorf(\"cannot compete :%d number of aborted mutations\\n %v\", ac.Count(), ml.Error())\n\t}\n\treturn ml.Error()\n}", "func loadData() {\n\tlogger.Info(\"Initating Vendor Refresh\")\n\tpurgeCSVS()\n\tdownloadFiles()\n\tloadCSV()\n\tpurgeCSVS()\n\tlogger.Info(\"Vendor Refresh Complete\")\n}", "func (e *LoadDataWorker) Load(\n\tctx context.Context,\n\treaderInfos []LoadDataReaderInfo,\n) error {\n\tvar (\n\t\tjobID int64\n\t\tparser mydump.Parser\n\t\terr error\n\t)\n\tctx = kv.WithInternalSourceType(ctx, kv.InternalLoadData)\n\n\ts, err := e.getSysSessionFn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer e.putSysSessionFn(ctx, s)\n\n\tsqlExec := s.(sqlexec.SQLExecutor)\n\t// TODO: move it to bootstrap\n\t_, err = sqlExec.ExecuteInternal(ctx, asyncloaddata.CreateLoadDataJobs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjobID, err = asyncloaddata.CreateLoadDataJob(\n\t\tctx, sqlExec, e.Path, e.schemaName, e.table.Meta().Name.O,\n\t\t\"logical\", e.Ctx.GetSessionVars().User.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\tif err == nil {\n\t\t\terr2 := asyncloaddata.FinishJob(\n\t\t\t\tctx,\n\t\t\t\tsqlExec,\n\t\t\t\tjobID,\n\t\t\t\te.Ctx.GetSessionVars().StmtCtx.GetMessage())\n\t\t\tterror.Log(err2)\n\t\t\treturn\n\t\t}\n\t\terrMsg := err.Error()\n\t\tif errImpl, ok := err.(*errors.Error); ok {\n\t\t\terrMsg = terror.ToSQLError(errImpl).Error()\n\t\t}\n\n\t\terr2 := asyncloaddata.FailJob(ctx, sqlExec, jobID, errMsg)\n\t\tterror.Log(err2)\n\t}()\n\n\tfailpoint.Inject(\"AfterCreateLoadDataJob\", nil)\n\n\tprogress := asyncloaddata.Progress{\n\t\tSourceFileSize: -1,\n\t\tLoadedFileSize: 0,\n\t\tLoadedRowCnt: 0,\n\t}\n\n\ttotalFilesize := int64(0)\n\thasErr := false\n\tfor _, readerInfo := range readerInfos {\n\t\tif readerInfo.Remote == nil {\n\t\t\tlogutil.Logger(ctx).Warn(\"can not get total file size when LOAD DATA from local file\")\n\t\t\thasErr = true\n\t\t\tbreak\n\t\t}\n\t\ttotalFilesize += readerInfo.Remote.size\n\t}\n\tif !hasErr {\n\t\tprogress.SourceFileSize = totalFilesize\n\t}\n\te.progress.Store(&progress)\n\n\terr = asyncloaddata.StartJob(ctx, sqlExec, jobID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfailpoint.Inject(\"AfterStartJob\", nil)\n\n\tgroup, groupCtx := errgroup.WithContext(ctx)\n\t// done is used to let commitWork goroutine notify UpdateJobProgress\n\t// goroutine that the job is finished.\n\tdone := make(chan struct{})\n\n\t// processStream goroutine.\n\tgroup.Go(func() error {\n\t\tfor _, info := range readerInfos {\n\t\t\treader, err2 := info.Opener(ctx)\n\t\t\tif err2 != nil {\n\t\t\t\treturn err2\n\t\t\t}\n\n\t\t\tparser, err2 = e.buildParser(ctx, reader, info.Remote)\n\t\t\tif err2 != nil {\n\t\t\t\tterror.Log(reader.Close())\n\t\t\t\treturn err2\n\t\t\t}\n\t\t\terr2 = e.processStream(groupCtx, parser, reader)\n\t\t\tterror.Log(reader.Close())\n\t\t\tif err2 != nil {\n\t\t\t\treturn err2\n\t\t\t}\n\t\t}\n\n\t\tclose(e.commitTaskQueue)\n\t\treturn nil\n\t})\n\t// commitWork goroutine.\n\tgroup.Go(func() error {\n\t\terr2 := e.commitWork(groupCtx)\n\t\tif err2 == nil {\n\t\t\tclose(done)\n\t\t}\n\t\treturn err2\n\t})\n\t// UpdateJobProgress goroutine.\n\tgroup.Go(func() error {\n\t\tticker := time.NewTicker(time.Duration(asyncloaddata.HeartBeatInSec) * time.Second)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\t// try to update progress to set 100% progress\n\t\t\t\tp := e.progress.Load()\n\t\t\t\tok, err2 := asyncloaddata.UpdateJobProgress(ctx, sqlExec, jobID, p.String())\n\t\t\t\tif !ok || err2 != nil {\n\t\t\t\t\tlogutil.Logger(ctx).Warn(\"failed to update job progress when finished\",\n\t\t\t\t\t\tzap.Bool(\"ok\", ok), zap.Error(err2))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\tcase <-groupCtx.Done():\n\t\t\t\treturn nil\n\t\t\tcase <-ticker.C:\n\t\t\t\tp := e.progress.Load()\n\t\t\t\tok, err2 := asyncloaddata.UpdateJobProgress(ctx, sqlExec, jobID, p.String())\n\t\t\t\tif err2 != nil {\n\t\t\t\t\treturn err2\n\t\t\t\t}\n\t\t\t\tif !ok {\n\t\t\t\t\treturn errors.Errorf(\"failed to keepalive for LOAD DATA job %d\", jobID)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\terr = group.Wait()\n\te.SetMessage()\n\treturn err\n}", "func LoadAll(args ...interface{}) error {\n\treturn doAll(Load, args...)\n}", "func loadAll(bi *Bi) (*Bi, error) {\n\n\tvar err error\n\n\tbi.allstops, err = bi.gtfs.AllStops()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbi.allroutes, err = bi.gtfs.Routes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bi, nil\n}", "func (s *EventStore) Load(aggregateID string) ([]flux.Record, error) {\n\t// ensure valid db connection\n\tif s.db == nil {\n\t\treturn nil, errors.New(\"no db connection\")\n\t}\n\n\t// query for events and aggregate type by aggregate id\n\trows, err := s.db.Query(\"select type, data, version from \"+s.tableName+\" where aggregate_id=$1 order by num asc\", aggregateID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// prepare return value\n\trecords := make([]flux.Record, 0)\n\n\t// iterate through results\n\tfor rows.Next() {\n\t\t// scan row into fields\n\t\t// type, data, version\n\t\trecord := flux.Record{}\n\t\terr := rows.Scan(&record.Type, &record.Data, &record.Version)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trecords = append(records, record)\n\t}\n\treturn records, nil\n}", "func TestLoad(t *testing.T){\n\t\n\tLoadData()\n\n\t// Simple test if the lists contain anything\n\tif len(sightings) == 0{\n\t\tt.Errorf(\"Loading sightings failed\")\n\t}\n\tif len(species) == 0{\n\t\tt.Errorf(\"Loading species failed\")\n\t}\n}", "func Load(db *gorm.DB) {\n\terr := db.DropTableIfExists(&models.Tariff{}, &models.Customer{}, &models.Subscription{}, &models.License{}).Error\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot drop table: %v\", err)\n\t}\n\terr = db.AutoMigrate(&models.Tariff{}, &models.Customer{}, &models.Subscription{}, &models.License{}).Error\n\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot migrate table: %v\", err)\n\t}\n\n\tfor i := range tariffs {\n\t\terr = db.Model(&models.Tariff{}).Create(&tariffs[i]).Error\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot seed tariff table: %v\", err)\n\t\t}\n\t}\n\n\tfor i := range customers {\n\t\terr = db.Model(&models.Customer{}).Create(&customers[i]).Error\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot seed customer table: %v\", err)\n\t\t}\n\t}\n\n\tfor i := range subscription {\n\t\terr = db.Model(&models.Subscription{}).Create(&subscription[i]).Error\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot seed subscription table: %v\", err)\n\t\t}\n\t}\n}", "func loadData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t// Fetch necessary data\n\ttimes := getEventTimes()\n\timages, err := loadImages()\n\tcheckError(err)\n\n\t// Encode to json\n\tdata := struct {\n\t\tEvents []event `json:\"events\"`\n\t\tImages []imageData `json:\"images\"`\n\t}{times, images}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\terr = json.NewEncoder(w).Encode(&data)\n\tcheckError(err)\n}", "func (c *Client) Load(aggregateID string) ([]eventhus.Event, error) {\n\tvar events []eventhus.Event\n\n\tsess := c.session.Copy()\n\tdefer sess.Close()\n\n\tvar aggregate AggregateDB\n\terr := sess.DB(c.db).C(\"events\").FindId(aggregateID).One(&aggregate)\n\tif err == mgo.ErrNotFound {\n\t\treturn events, nil\n\t} else if err != nil {\n\t\treturn events, err\n\t}\n\n\tevents = make([]eventhus.Event, len(aggregate.Events))\n\tregister := eventhus.NewEventRegister()\n\n\tfor i, dbEvent := range aggregate.Events {\n\t\t// Create an event of the correct type.\n\t\tdataType, err := register.Get(dbEvent.Type)\n\t\tif err != nil {\n\t\t\treturn events, err\n\t\t}\n\n\t\t// Manually decode the raw BSON event.\n\t\tif err := dbEvent.RawData.Unmarshal(dataType); err != nil {\n\t\t\treturn events, err\n\t\t}\n\n\t\t// Set concrete event and zero out the decoded event.\n\t\tdbEvent.data = dataType\n\t\tdbEvent.RawData = bson.Raw{}\n\n\t\t// Translate dbEvent to eventhus.Event\n\t\tevents[i] = eventhus.Event{\n\t\t\tAggregateID: aggregateID,\n\t\t\tAggregateType: dbEvent.AggregateType,\n\t\t\tVersion: dbEvent.Version,\n\t\t\tType: dbEvent.Type,\n\t\t\tData: dbEvent.data,\n\t\t}\n\t}\n\n\treturn events, nil\n}", "func loadAlerts(conn *grpc.ClientConn, db *gorm.DB) {\n\tvar alerts []dexter.Alert\n\tclient := dataPb.NewDataClient(conn)\n\n\t// for every alert create a chart if needed\n\tdb.Find(&alerts)\n\tfor _, alert := range alerts {\n\t\tlog.Println(alert.ID)\n\t\tdexter.SetupChart(alert, client)\n\t}\n}", "func LoadDatasets(dbPath, key string) []*Dataset {\n\tvar datasets []*Dataset\n\n\tdirs, err := ioutil.ReadDir(dbPath)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn datasets\n\t}\n\n\tfor _, dir := range dirs {\n\t\tif !strings.HasPrefix(dir.Name(), \".\") && dir.IsDir() {\n\t\t\tds := &Dataset{\n\t\t\t\tpath: filepath.Join(dbPath, dir.Name()),\n\t\t\t\tlastModified: dir.ModTime(),\n\t\t\t\tkey: key,\n\t\t\t}\n\n\t\t\tdatasets = append(datasets, ds)\n\t\t}\n\t}\n\treturn datasets\n}", "func (s *Store) Load(ctx context.Context, aggregateID string, version int) (eventsource.History, error) {\n\tpartition := selectPartition(version, s.eventsPerItem)\n\tinput, err := makeQueryInput(s.tableName, s.hashKey, s.rangeKey, aggregateID, partition)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thistory := make(eventsource.History, 0, version)\n\n\tvar startKey map[string]*dynamodb.AttributeValue\n\tfor {\n\t\tout, err := s.api.Query(input)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(out.Items) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// events are stored within av as _t{version} = {event-type}, _d{version} = {serialized event}\n\t\tfor _, item := range out.Items {\n\t\t\tfor key, av := range item {\n\t\t\t\tif !isKey(key) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trecordVersion, err := versionFromKey(key)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tif version > 0 && recordVersion > version {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\thistory = append(history, eventsource.Record{\n\t\t\t\t\tVersion: recordVersion,\n\t\t\t\t\tData: av.B,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tstartKey = out.LastEvaluatedKey\n\t\tif len(startKey) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tsort.Slice(history, func(i, j int) bool {\n\t\treturn history[i].Version < history[j].Version\n\t})\n\n\treturn history, nil\n}", "func (b *Bolt) LoadAll(data interface{}) error {\n\n\tbuf := &bytes.Buffer{}\n\terr := b.client.View(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(b.bucket))\n\t\tbuf.WriteByte('[')\n\t\tif bkt != nil {\n\t\t\tfirst := true\n\t\t\tif err := bkt.ForEach(func(_, v []byte) error {\n\t\t\t\tif len(v) > 0 {\n\t\t\t\t\tif first {\n\t\t\t\t\t\tfirst = false\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbuf.WriteByte(',')\n\t\t\t\t\t}\n\n\t\t\t\t\tbuf.Write(v)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t\tbuf.WriteByte(']')\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Buffer: %s\\n\", buf.Bytes())\n\tif err = json.Unmarshal(buf.Bytes(), data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(db *gorm.DB) {\n\n\tinput1 := \"1996-02-08\"\n\tlayout1 := \"2006-01-02\"\n\tt, _ := time.Parse(layout1, input1)\n\n\tinput := \"2018-10-01\"\n\tlayout := \"2006-01-02\"\n\tstart, _ := time.Parse(layout, input)\n\n\tinput2 := \"2020-10-01\"\n\tlayout2 := \"2006-01-02\"\n\tend, _ := time.Parse(layout2, input2)\n\n\tvar users = []models.User{\n\t\tmodels.User{\n\t\t\tFirstname: \"Steven\",\n\t\t\tLastname: \"Victor\",\n\t\t\tEmail: \"[email protected]\",\n\t\t\tAccesslevel: 1,\n\t\t\tPassword: \"password\",\n\t\t\tDateofbirth: t,\n\t\t},\n\t\tmodels.User{\n\t\t\tFirstname: \"Kevin\",\n\t\t\tLastname: \"Feige\",\n\t\t\tEmail: \"[email protected]\",\n\t\t\tAccesslevel: 1,\n\t\t\tPassword: \"password\",\n\t\t\tDateofbirth: t,\n\t\t},\n\t\tmodels.User{\n\t\t\tFirstname: \"Karim\",\n\t\t\tLastname: \"Benzema\",\n\t\t\tEmail: \"[email protected]\",\n\t\t\tAccesslevel: 1,\n\t\t\tPassword:\"Mostafa87\",\n\t\t\tDateofbirth: t,\n\t\t},\n\t}\n\n\tvar votes = []models.Vote{\n\t\tmodels.Vote{\n\t\t\tTitle: \"Title 1\",\n\t\t\tDesc: \"Hello world 1\",\n\t\t\tAuthorID : 1,\n\t\t\tStartDate: start,\n\t\t\tEndDate: end,\n\t\t},\n\t\tmodels.Vote{\n\t\t\tTitle: \"Propreté des trottoirs\",\n\t\t\tDesc: \"Dans le budget qui sera soumis au vote des conseillers de Paris lundi, 32 M€ seront consacrés à l’achat de nouvelles machines, plus silencieuses, plus propres et plus performantes. Il n’y aura pas d’embauche d’agents supplémentaires.\",\n\t\t\tAuthorID : 1,\n\t\t\tStartDate: start,\n\t\t\tEndDate: end,\n\t\t},\n\t\tmodels.Vote{\n\t\t\tTitle: \"Title 2\",\n\t\t\tDesc: \"Hello world 2\",\n\t\t\tAuthorID : 1,\n\t\t\tStartDate: start,\n\t\t\tEndDate: end,\n\t\t},\n\t}\n\n\terr := db.Debug().DropTableIfExists(&models.Vote{}, &models.User{}).Error\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot drop table: %v\", err)\n\t}\n\terr = db.Debug().AutoMigrate(&models.User{}, &models.Vote{}).Error\n\tif err != nil {\n\t\tlog.Fatalf(\"cannot migrate table: %v\", err)\n\t}\n\n\terr = db.Debug().Model(&models.Vote{}).AddForeignKey(\"author_id\", \"users(id)\", \"cascade\", \"cascade\").Error\n\tif err != nil {\n\t\tlog.Fatalf(\"attaching foreign key error: %v\", err)\n\t}\n\n\t\n\n\tfor i := range users {\n\t\terr = db.Debug().Model(&models.User{}).Create(&users[i]).Error\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot seed users table: %v\", err)\n\t\t}\n\n\t\tvotes[i].AuthorID = users[i].ID\n\t\terr = db.Debug().Model(&models.Vote{}).Create(&votes[i]).Error\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"cannot seed votes table: %v\", err)\n\t\t}\n\t}\n\tdb.Model(&votes[0]).Association(\"Users\")\n\terr = db.Debug().Model(&votes[0]).Association(\"Users\").Append(&users).Error\n\tif err != nil {\n\t\tlog.Fatalf(\"Association error: %v\", err)\n\t}\n\t\t\n\n}", "func dumpLoad(refGene string, db *sql.DB) {\n\t/*\n\t\treaderName := \"r\" + strconv.Itoa(rand.Int())\n\t\tmysql.RegisterReaderHandler(readerName,\n\t\t\tfunc() io.Reader {\n\t\t\t\treturn bytes.NewBufferString(refGene)\n\t\t\t})\n\t\tdefer mysql.DeregisterReaderHandler(readerName)\n\t\tcmd := \"LOAD DATA LOCAL INFILE 'Reader::\" + readerName + \"' \" +\n\t\t\t\"IGNORE INTO TABLE chr \"\n\t\t_, err := db.Exec(cmd)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}*/\n}", "func (db *ldb) loadAll() {\n\tf, err := os.Open(game_data_file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trd := bufio.NewReader(f)\n\n\tvar l = 0\n\tvar matrix = make([]string, 0)\n\tfor {\n\t\tline, err := rd.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tdb.data = append(db.data, matrix)\n\t\t\t\tdb.maxLevel = len(db.data)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\t\tline = strings.TrimRight(line, \"\\t\\n\\f\\r\")\n\t\tif len(line) == 0 {\n\t\t\tdb.data = append(db.data, matrix)\n\t\t\tl = l + 1\n\t\t\tmatrix = make([]string, 0)\n\t\t} else {\n\t\t\tmatrix = append(matrix, line)\n\t\t}\n\t}\n}", "func BatchLoad(baseFolder string) error {\n\treturn batchLoad(baseFolder, false)\n}", "func (l ImportDataLoader) InitialDataLoad(\n\tctx context.Context, db *gosql.DB, gen workload.Generator,\n) (int64, error) {\n\tif l.FilesPerNode == 0 {\n\t\tl.FilesPerNode = 1\n\t}\n\n\tlog.Infof(ctx, \"starting import of %d tables\", len(gen.Tables()))\n\tstart := timeutil.Now()\n\tconst useConnectionDB = ``\n\tbytes, err := ImportFixture(\n\t\tctx, db, gen, useConnectionDB, l.FilesPerNode, l.InjectStats, l.CSVServer)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, `importing fixture`)\n\t}\n\telapsed := timeutil.Since(start)\n\tlog.Infof(ctx, \"imported %s bytes in %d tables (took %s, %s)\",\n\t\thumanizeutil.IBytes(bytes), len(gen.Tables()), elapsed, humanizeutil.DataRate(bytes, elapsed))\n\n\treturn bytes, nil\n}", "func LoadData(userCsv, itemCsv string) {\n\tfmt.Printf(\"Load users from user file..\")\n\tLoadUsers(userCsv)\n\tfmt.Printf(\"OK\\n\")\n\tfmt.Printf(\"Load items from item file..\")\n\tLoadItems(itemCsv)\n\tfmt.Printf(\"OK\\n\")\n}", "func (d *Dao) load(loadingContext data.Map, source *url.Resource, scanner *bufio.Scanner) (map[string]interface{}, error) {\n\tvar objectContainer = data.NewMap()\n\tvar referenceValues = newReferenceValues()\n\tlines := readLines(scanner)\n\tdecoder := d.factory.Create(strings.NewReader(lines[0]))\n\trecord, tag, err := d.processRootHeaderLine(source, objectContainer, decoder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar rootObject = objectContainer.GetMap(tag.Name)\n\tvar context = newTagContext(loadingContext, source, tag, objectContainer, referenceValues, rootObject, rootObject)\n\tfor i := 1; i < len(lines); i++ {\n\t\tvar recordHeight = 0\n\t\tline := lines[i]\n\t\tif strings.HasPrefix(line, arrayRowTerminator) { //replace array terminator\n\t\t\tline = strings.Replace(line, arrayRowTerminator, \"\", 1)\n\t\t}\n\t\tvar hasActiveIterator = tag.HasActiveIterator()\n\t\tline = d.expandMeta(context, line)\n\n\t\tisHeaderLine := !strings.HasPrefix(line, \",\")\n\t\tdecoder := d.factory.Create(strings.NewReader(line))\n\t\tif isHeaderLine {\n\t\t\tif hasActiveIterator {\n\t\t\t\tif tag.Iterator.Next() {\n\t\t\t\t\tcontext.tag.Subpath = \"\"\n\t\t\t\t\ti = tag.LineNumber\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\trecord, tag, err = d.processHeaderLine(context, decoder, i)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\trecord.Record = make(map[string]interface{})\n\t\terr := decoder.Decode(record)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !record.IsEmpty() {\n\t\t\tcontext.virtualObjects = data.NewMap()\n\t\t\tcontext.fieldIndex = make(map[string]int)\n\t\t\ttag.setTagObject(context, record.Record, d.includeMeta)\n\n\t\t\tif strings.Contains(line, \"$\") {\n\t\t\t\tfor k, v := range record.Record {\n\t\t\t\t\tif !toolbox.IsString(v) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\trecord.Record[k] = d.expandMeta(context, toolbox.AsString(v))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor j := 1; j < len(record.Columns); j++ {\n\t\t\t\tif recordHeight, err = d.processCell(context, record, lines, i, j, recordHeight, true); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor j := 1; j < len(record.Columns); j++ {\n\t\t\t\tif recordHeight, err = d.processCell(context, record, lines, i, j, recordHeight, false); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tremoveEmptyElements(context.tagObject)\n\t\t}\n\n\t\ti += recordHeight\n\t\tvar isLast = i+1 == len(lines)\n\t\tif isLast && tag.HasActiveIterator() {\n\t\t\tif tag.Iterator.Next() {\n\t\t\t\tcontext.tag.Subpath = \"\"\n\t\t\t\ti = tag.LineNumber\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\terr = referenceValues.CheckUnused()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn rootObject, nil\n}", "func (mdb MongoDBConnection) Load() (a []Agent, err error) {\n\tmdb.session = mdb.GetSession()\n\tdefer mdb.session.Close()\n\tc := mdb.session.DB(\"dockmaster\").C(\"containers\")\n\n\titer := c.Find(nil).Iter()\n\terr = iter.All(&a)\n\n\treturn a, err\n}", "func (s *EventStore) Load(ctx context.Context, id uuid.UUID) ([]eh.Event, error) {\n\tns := eh.NamespaceFromContext(ctx)\n\n\tcmd := s.db.HGetAll(fmt.Sprintf(\"%s:%s\", ns, id.String()))\n\tvar events []eh.Event\n\n\tfor _, dbEvent := range cmd.Val() {\n\t\te := AggregateEvent{}\n\n\t\tif err := json.Unmarshal([]byte(dbEvent), &e); err != nil {\n\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\tBaseErr: err,\n\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\tNamespace: ns,\n\t\t\t}\n\t\t}\n\n\t\tif e.RawEventData != nil {\n\t\t\tif eventData, err := s.encoder.Unmarshal(e.EventType, e.RawEventData); err != nil {\n\t\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\t\tBaseErr: err,\n\t\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te.data = eventData\n\t\t\t}\n\t\t}\n\t\te.RawEventData = nil\n\n\t\tif e.RawMetaData != nil {\n\t\t\tif err := json.Unmarshal(e.RawMetaData, &e.MetaData); err != nil {\n\t\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\t\tBaseErr: err,\n\t\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor key, val := range e.MetaData {\n\t\t\t\tif _, ok := val.(float64); ok {\n\t\t\t\t\tintValue := int32(e.MetaData[key].(float64))\n\t\t\t\t\te.MetaData[key] = intValue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\te.RawEventData = nil\n\n\t\tevents = append(events, event{\n\t\t\tAggregateEvent: e,\n\t\t})\n\t}\n\n\tsort.Slice(events, func(i, j int) bool {\n\t\treturn events[i].Version() < events[j].Version()\n\t})\n\treturn events, nil\n}", "func load(url, companyFile string, computeLengths []int) error {\n\n\t// Allow only one load to be happening at a time\n\tloadMutex.Lock()\n\tdefer loadMutex.Unlock()\n\n\tloadRegistry.UnregisterAll()\n\n\tstartTime := time.Now()\n\tlog.Infof(\"Started load of company data from %v\", companyFile)\n\tcompanyData, err := loadCompanies(companyFile)\n\tif err != nil {\n\t\tlog.WithError(err).WithFields(log.Fields{\"duration\": time.Since(startTime).Seconds(),\n\t\t\t\"company-file\": companyFile}).Error(\"Completed company data load\")\n\t\treturn errors.Wrapf(err, \"loading company data\")\n\t}\n\n\tstartTime = time.Now()\n\tfi, err := os.Stat(url)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"checking url type\")\n\t}\n\n\tvar loadErrors error\n\tbaseLogger := log.WithField(\"url\", url)\n\tswitch mode := fi.Mode(); {\n\tcase mode.IsDir():\n\t\tbaseLogger := baseLogger.WithField(\"url-type\", \"directory\")\n\t\tbaseLogger.Infof(\"Started load\")\n\t\tloadErrors = loadDir(url, companyData, computeLengths)\n\n\tcase mode.IsRegular():\n\t\tif utils.IsZip(url) {\n\t\t\tbaseLogger := baseLogger.WithField(\"url-type\", \"archive\")\n\t\t\tbaseLogger.Infof(\"Started load\")\n\t\t\tloadErrors = loadZip(url, companyData, computeLengths)\n\t\t} else {\n\t\t\tbaseLogger := baseLogger.WithField(\"url-type\", \"file\")\n\t\t\tbaseLogger.Infof(\"Started load\")\n\t\t\tloadErrors = loadFile(url, companyData, computeLengths)\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"unrecognized load type\")\n\t}\n\n\treturn loadErrors\n}", "func (d *dataUpdateTracker) load(ctx context.Context, drives ...string) {\n\tif len(drives) <= 0 {\n\t\tlogger.LogIf(ctx, errors.New(\"dataUpdateTracker.load: No drives specified\"))\n\t\treturn\n\t}\n\tfor _, drive := range drives {\n\n\t\tcacheFormatPath := pathJoin(drive, dataUpdateTrackerFilename)\n\t\tf, err := os.Open(cacheFormatPath)\n\t\tif err != nil {\n\t\t\tif osIsNotExist(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlogger.LogIf(ctx, err)\n\t\t\tcontinue\n\t\t}\n\t\terr = d.deserialize(f, d.Saved)\n\t\tif err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {\n\t\t\tlogger.LogIf(ctx, err)\n\t\t}\n\t\tf.Close()\n\t}\n}", "func (gdb *Gdb) ReLoadDb() (TimeRows, error) {\n\t// check whether is syncing historical data\n\tt := time.NewTicker(time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tif !gdb.syncStatus {\n\t\t\t\tt.Stop()\n\t\t\t\tgoto next\n\t\t\t}\n\t\t}\n\t}\nnext:\n\tst := time.Now()\n\tgdb.isReloading = true // lock gdb\n\tdefer func() {\n\t\tgdb.isReloading = false\n\t}()\n\tdataTypeMap := map[string]map[string][]string{} // dataType==>{groupName: []string{itemName}}\n\tfor item := range gdb.rtDbFilter.IterBuffered() {\n\t\tswitch item.Val.(string) {\n\t\tcase \"float32\":\n\t\t\tgroupName := strings.Split(item.Key, joiner)[1] // get groupName\n\t\t\tif _, ok := dataTypeMap[\"float32\"]; ok {\n\t\t\t\tdataTypeMap[\"float32\"][groupName] = append(dataTypeMap[\"float32\"][groupName], item.Key)\n\t\t\t} else {\n\t\t\t\tdataTypeMap[\"float32\"] = map[string][]string{groupName: {item.Key}}\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"int32\":\n\t\t\tgroupName := strings.Split(item.Key, joiner)[1] // get groupName\n\t\t\tif _, ok := dataTypeMap[\"int32\"]; ok {\n\t\t\t\tdataTypeMap[\"int32\"][groupName] = append(dataTypeMap[\"int32\"][groupName], item.Key)\n\t\t\t} else {\n\t\t\t\tdataTypeMap[\"int32\"] = map[string][]string{groupName: {item.Key}}\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"string\":\n\t\t\tgroupName := strings.Split(item.Key, joiner)[1] // get groupName\n\t\t\tif _, ok := dataTypeMap[\"string\"]; ok {\n\t\t\t\tdataTypeMap[\"string\"][groupName] = append(dataTypeMap[\"string\"][groupName], item.Key)\n\t\t\t} else {\n\t\t\t\tdataTypeMap[\"string\"] = map[string][]string{groupName: {item.Key}}\n\t\t\t}\n\t\t\tbreak\n\t\tdefault:\n\t\t\tgroupName := strings.Split(item.Key, joiner)[1] // get groupName\n\t\t\tif _, ok := dataTypeMap[\"bool\"]; ok {\n\t\t\t\tdataTypeMap[\"bool\"][groupName] = append(dataTypeMap[\"bool\"][groupName], item.Key)\n\t\t\t} else {\n\t\t\t\tdataTypeMap[\"bool\"] = map[string][]string{groupName: {item.Key}}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tg := errgroup.Group{}\n\tcounts := [4]int{}\n\tfor index, dataType := range dataTypes {\n\t\tdt, i := dataType, index\n\t\tg.Go(func() error {\n\t\t\tfor groupName, itemNames := range dataTypeMap[dt] {\n\t\t\t\tdb := gdb.hisDb[dt][groupName]\n\t\t\t\tif r, err := reload(db, itemNames...); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t} else {\n\t\t\t\t\tcounts[i] = r\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\treturn TimeRows{}, err\n\t}\n\treturn TimeRows{Times: time.Since(st).Milliseconds(), EffectedRows: counts[0] + counts[1] + counts[2] + counts[3]}, nil\n}", "func Load(source interface{}, others ...interface{}) (_ *File, err error) {\n\tsources := make([]dataSource, len(others)+1)\n\tsources[0], err = parseDataSource(source)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := range others {\n\t\tsources[i+1], err = parseDataSource(others[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tf := newFile(sources)\n\treturn f, f.Reload()\n}", "func load(ctx context.Context, ds *localdatasource.DataSource, pathList string) {\n\tpaths := strings.Split(pathList, \",\")\n\tloaded := len(paths)\n\tfor _, path := range paths {\n\t\tvar err error\n\t\tif *gopathMode {\n\t\t\terr = ds.LoadFromGOPATH(ctx, path)\n\t\t} else {\n\t\t\terr = ds.Load(ctx, path)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Error(ctx, err)\n\t\t\tloaded--\n\t\t}\n\t}\n\n\tif loaded == 0 {\n\t\tlog.Fatalf(ctx, \"failed to load module(s) at %s\", pathList)\n\t}\n}", "func (t *ATrains) Load() {\n\tfile, _ := os.Open(\"../configs/trains.txt\")\n\tscanner := bufio.NewScanner(file)\n\n\t/* SKIP ALL COMMENTS */\n\tfor scanner.Scan() && scanner.Text()[0] == '#' {\n\t}\n\n\t/* for each line ( train ) DO */\n\tfor i := 0; i < configs.Conf.NumTrains(); i++ {\n\t\tline := scanner.Text()\n\n\t\t/* Start from begining */\n\t\toc := 0\n\t\tc := 0\n\n\t\t/* find ID value */\n\t\tfor line[c] != ';' {\n\t\t\tc++\n\t\t}\n\n\t\t/* Get ID value */\n\t\tid, _ := strconv.Atoi(line[oc:c])\n\t\tc++\n\t\toc = c\n\n\t\t/* find MaxSpeed value */\n\t\tfor line[c] != ';' {\n\t\t\tc++\n\t\t}\n\n\t\t/* Get MaxSpeed value */\n\t\tspeed, _ := strconv.Atoi(line[oc:c])\n\t\tc++\n\t\toc = c\n\n\t\t/* find Capacity value */\n\t\tfor line[c] != ';' {\n\t\t\tc++\n\t\t}\n\n\t\t/* Get Capacity value */\n\t\tcapacity, _ := strconv.Atoi(line[oc:c])\n\t\tc++\n\t\toc = c\n\n\t\t/* find StartPoint value */\n\t\tfor line[c] != ';' {\n\t\t\tc++\n\t\t}\n\n\t\t/* Get StartPoint value */\n\t\tstartPoint, _ := strconv.Atoi(line[oc:c])\n\t\tc = c + 2\n\t\toc = c\n\n\t\t/* Create Train and add to global array */\n\t\ttrain := NewTrain(id, speed, capacity, startPoint, configs.Conf.NumTracks())\n\t\tTrains.Insert(train)\n\n\t\t/* Parse Route */\n\t\tfor line[c-1] != ']' {\n\t\t\tfor line[c] != ';' && line[c] != ']' {\n\t\t\t\tc++\n\t\t\t}\n\n\t\t\troute, _ := strconv.Atoi(line[oc:c])\n\t\t\tc++\n\t\t\toc = c\n\n\t\t\ttrain.AddRoute(route)\n\t\t}\n\t\tscanner.Scan()\n\t}\n\tfile.Close()\n}", "func loadmetadate() (tables jsonobject) {\n\tfile, err := ioutil.ReadFile(\"./config/data.json\")\n\tif err != nil {\n\t\tfmt.Printf(\"file error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Printf(\"%s\\n\", string(file))\n\n\terr = json.Unmarshal(file, &tables)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tsort.Sort(tables.Tables)\n\t// fmt.Println(tables)\n\treturn tables\n}", "func (s *EventStore) Load(ctx context.Context, id string) ([]eh.Event, context.Context, error) {\n\tsess := s.session.Copy()\n\tdefer sess.Close()\n\n\tbatch := false\n\tvar err error\n\tvar minVersion int\n\tlimit, ok := ctx.Value(\"limit\").(int)\n\tif ok {\n\t\tbatch = true\n\t\tminVersion, _ = ctx.Value(\"minVersion\").(int)\n\t}\n\t//load dbEvents\n\tquery := bson.M{\n\t\t\"aggregate_id\": id,\n\t\t\"version\": bson.M{\"$gte\": minVersion},\n\t}\n\tvar result []dbEvent\n\tif batch {\n\t\terr = sess.DB(s.dbName(ctx)).C(s.colName(ctx) + \".events\").Find(query).Sort(\"version\").Limit(limit).All(&result)\n\t} else {\n\t\terr = sess.DB(s.dbName(ctx)).C(s.colName(ctx) + \".events\").Find(query).Sort(\"version\").All(&result)\n\t}\n\n\tif err == mgo.ErrNotFound {\n\t\treturn []eh.Event{}, ctx, nil\n\t} else if err != nil {\n\t\treturn nil, ctx, eh.EventStoreError{\n\t\t\tBaseErr: err,\n\t\t\tErr: err,\n\t\t\tNamespace: eh.NamespaceFromContext(ctx),\n\t\t}\n\t}\n\tevents := make([]eh.Event, len(result))\n\n\tfor i, dbEvent := range result {\n\t\t// Create an event of the correct type.\n\t\tif data, err := eh.CreateEventData(dbEvent.EventType); err == nil {\n\t\t\t// Manually decode the raw BSON event.\n\t\t\tif err := dbEvent.RawData.Unmarshal(data); err != nil {\n\t\t\t\treturn nil, ctx, eh.EventStoreError{\n\t\t\t\t\tBaseErr: err,\n\t\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\t\tNamespace: eh.NamespaceFromContext(ctx),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set conrcete event and zero out the decoded event.\n\t\t\tdbEvent.data = data\n\t\t\tdbEvent.RawData = bson.Raw{}\n\t\t}\n\n\t\tevents[i] = event{dbEvent: dbEvent}\n\t}\n\n\treturn events, ctx, nil\n}", "func (d *DBV0) load(db *DB) error {\n\tfn := func(tx *sql.Tx) error {\n\t\tvar err error\n\t\td.aciinfos, err = getAllACIInfosV0_1(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.remotes, err = getAllRemoteV0_1(tx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err := db.Do(fn); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func loadBiolatencyBeforeObjects(obj interface{}, opts *ebpf.CollectionOptions) error {\n\tspec, err := loadBiolatencyBefore()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn spec.LoadAndAssign(obj, opts)\n}", "func (w *WorkflowInstances) LoadAll(opt *db.Options) error {\n\tif err := db.SelectStruct(constants.TableCoreBPMInstances, w, opt); err != nil {\n\t\treturn customerror.New(http.StatusInternalServerError, \"workflow instances load\", err.Error())\n\t}\n\treturn nil\n}", "func Load() {\n\tpostgres.Load()\n}", "func (s *OnlineDDLStorage) Load(tctx *tcontext.Context) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tquery := fmt.Sprintf(\"SELECT `ghost_schema`, `ghost_table`, `ddls` FROM %s WHERE `id`= ?\", s.tableName)\n\trows, err := s.dbConn.querySQL(tctx, query, s.id)\n\tif err != nil {\n\t\treturn terror.WithScope(err, terror.ScopeDownstream)\n\t}\n\tdefer rows.Close()\n\n\tvar (\n\t\tschema string\n\t\ttable string\n\t\tddls string\n\t)\n\tfor rows.Next() {\n\t\terr := rows.Scan(&schema, &table, &ddls)\n\t\tif err != nil {\n\t\t\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeDownstream)\n\t\t}\n\n\t\tmSchema, ok := s.ddls[schema]\n\t\tif !ok {\n\t\t\tmSchema = make(map[string]*GhostDDLInfo)\n\t\t\ts.ddls[schema] = mSchema\n\t\t}\n\n\t\tmSchema[table] = &GhostDDLInfo{}\n\t\terr = json.Unmarshal([]byte(ddls), mSchema[table])\n\t\tif err != nil {\n\t\t\treturn terror.ErrSyncerUnitOnlineDDLInvalidMeta.Delegate(err)\n\t\t}\n\t\ttctx.L().Info(\"loaded online ddl meta from checkpoint\",\n\t\t\tzap.String(\"db\", schema),\n\t\t\tzap.String(\"table\", table))\n\t}\n\n\treturn terror.WithScope(terror.DBErrorAdapt(rows.Err(), terror.ErrDBDriverError), terror.ScopeDownstream)\n}", "func (s Store) Load(aggregateID string) ([]midgard.Event, error) {\n\ts.mux.Lock()\n\tsession := s.getFreshSession()\n\n\tdefer func() {\n\t\ts.mux.Unlock()\n\t\tsession.Close()\n\t}()\n\n\tdocument, err := s.getDocument(aggregateID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents := make([]midgard.Event, 0)\n\n\tfor _, v := range document.getHistory() {\n\t\tevent, err := s.serializer.Unmarshal(v)\n\n\t\tif err != nil {\n\t\t\treturn []midgard.Event{}, err\n\t\t}\n\n\t\tevents = append(events, event)\n\t}\n\n\treturn events, nil\n}", "func (s *Service) doFullLoad(pkg factset.Package, currentLoadedFileMetadata factset.PackageMetadata) (factset.PackageVersion, error) {\n\tvar loadedVersions factset.PackageVersion\n\n\tlatestDataArchive, err := s.factset.GetLatestFile(pkg, true)\n\tif err != nil {\n\t\treturn loadedVersions, err\n\t}\n\n\tif currentLoadedFileMetadata.PackageVersion.FeedVersion == 0 ||\n\t\t(currentLoadedFileMetadata.PackageVersion.FeedVersion == latestDataArchive.Version.FeedVersion && currentLoadedFileMetadata.PackageVersion.Sequence < latestDataArchive.Version.Sequence) {\n\n\t\t//if err = s.db.DropTablesWithProductAndBundle(pkg.Dataset, pkg.Product); err != nil {\n\t\t//\treturn loadedVersions, err\n\t\t//}\n\n\t\tvar localDataArchive *os.File\n\t\tlocalDataArchive, err = s.factset.Download(latestDataArchive, pkg.Product)\n\t\tif err != nil {\n\t\t\treturn loadedVersions, err\n\t\t}\n\n\t\tvar localDataFiles []string\n\t\tlocalDataFiles, err = s.unzipFile(localDataArchive, pkg.Product)\n\t\tif err != nil {\n\t\t\treturn loadedVersions, err\n\t\t}\n\n\t\tfor _, file := range localDataFiles {\n\t\t\t//TODO version the file name to be table_sequence\n\t\t\ttableName := getTableFromFilename(file)\n\t\t\tif err = s.db.DropDataFromTable(tableName, pkg.Product); err != nil {\n\t\t\t\treturn loadedVersions, err\n\t\t\t}\n\n\t\t\tlog.WithFields(log.Fields{\"fs_product\": pkg.Product}).Debugf(\"Loading table %s with data from file %s\", tableName, file)\n\t\t\terr = s.db.LoadTable(file, tableName)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).WithFields(log.Fields{\"fs_product\": pkg.Product}).Errorf(\"Error whilst loading table %s with data from file %s\", tableName, file)\n\t\t\t\treturn loadedVersions, err\n\t\t\t}\n\n\t\t\terr = s.db.UpdateLoadedTableVersion(tableName, latestDataArchive.Version, pkg)\n\t\t\tif err != nil {\n\t\t\t\treturn loadedVersions, err\n\t\t\t}\n\n\t\t\tloadedVersions.FeedVersion = latestDataArchive.Version.FeedVersion\n\t\t\tloadedVersions.Sequence = latestDataArchive.Version.Sequence\n\t\t\tlog.WithFields(log.Fields{\"fs_product\": pkg.Product}).Infof(\"Updated table %s with data version v%d_%d\", tableName, latestDataArchive.Version.FeedVersion, latestDataArchive.Version.Sequence)\n\t\t}\n\t\t// Update the package metadata, has the schema changed though?\n\t} else {\n\t\tlog.Infof(\"%s data is up-to-date as version v%d_%d has already been loaded into db\", pkg.Product, currentLoadedFileMetadata.PackageVersion.FeedVersion, currentLoadedFileMetadata.PackageVersion.Sequence)\n\t\tloadedVersions = currentLoadedFileMetadata.PackageVersion\n\t}\n\n\treturn loadedVersions, err\n}", "func LoadAll(loader ValuesLoader) (Values, error) {\n\treturn nil, nil\n}", "func loadEvents(t time.Time, cal ...*Calendar) ([]*Event, error) {\n\tvar (\n\t\tevents = []*Event{}\n\t\tdateStr = t.Format(timeFormat)\n\t\tname = fmt.Sprintf(\"events-%s.json\", dateStr)\n\t\tjobName = \"update-events\"\n\t)\n\n\tif wf.Cache.Expired(name, opts.MaxAgeEvents()) {\n\t\twf.Rerun(0.1)\n\t\tif !wf.IsRunning(jobName) {\n\t\t\tcmd := exec.Command(os.Args[0], \"update\", \"events\", dateStr)\n\t\t\tif err := wf.RunInBackground(jobName, cmd); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tif wf.Cache.Exists(name) {\n\t\tif err := wf.Cache.LoadJSON(name, &events); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Set map URL\n\tfor _, e := range events {\n\t\te.MapURL = mapURL(e.Location)\n\t}\n\treturn events, nil\n}", "func (sys *BucketMetadataSys) load(ctx context.Context, buckets []BucketInfo, objAPI ObjectLayer) {\n\tcount := 100 // load 100 bucket metadata at a time.\n\tfor {\n\t\tif len(buckets) < count {\n\t\t\tsys.concurrentLoad(ctx, buckets, objAPI)\n\t\t\treturn\n\t\t}\n\t\tsys.concurrentLoad(ctx, buckets[:count], objAPI)\n\t\tbuckets = buckets[count:]\n\t}\n}", "func LoadAll(ctx context.Context, cfg Config) ([]*Person, error) {\n\tdb, err := getDB(cfg)\n\tif err != nil {\n\t\tcfg.Logger().Error(\"failed to get DB connection. err: %s\", err)\n\t\treturn nil, err\n\t}\n\n\t// set latency budget for the database call\n\tsubCtx, cancel := context.WithTimeout(ctx, 1*time.Second)\n\tdefer cancel()\n\n\t// perform DB select\n\trows, err := db.QueryContext(subCtx, sqlLoadAll)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\t_ = rows.Close()\n\t}()\n\n\tvar out []*Person\n\n\tfor rows.Next() {\n\t\t// retrieve columns and populate the person object\n\t\trecord, err := populatePerson(rows.Scan)\n\t\tif err != nil {\n\t\t\tcfg.Logger().Error(\"failed to convert query result. err: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tout = append(out, record)\n\t}\n\n\tif len(out) == 0 {\n\t\tcfg.Logger().Warn(\"no people found in the database.\")\n\t\treturn nil, ErrNotFound\n\t}\n\n\treturn out, nil\n}", "func LoadAutoRollData(dbClient *influxdb.Client, workdir string) {\n\trollCheckoutsDir := path.Join(workdir, \"autoroll_git\")\n\tskiaRepo, err := gitinfo.CloneOrUpdate(SKIA_REPO, path.Join(rollCheckoutsDir, \"skia\"), false)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to check out skia: %s\", err)\n\t\treturn\n\t}\n\tchromiumRepo, err := gitinfo.CloneOrUpdate(CHROMIUM_REPO, path.Join(rollCheckoutsDir, \"chromium\"), false)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to check out chromium: %s\", err)\n\t\treturn\n\t}\n\n\tfor _ = range time.Tick(time.Minute) {\n\t\ts, err := autoroll.CurrentStatus(skiaRepo, chromiumRepo)\n\t\tif err != nil {\n\t\t\tglog.Error(err)\n\t\t} else {\n\t\t\terr := writeAutoRollDataPoint(dbClient, s)\n\t\t\tif err != nil {\n\t\t\t\tglog.Error(err)\n\t\t\t}\n\t\t}\n\t\tskiaRepo.Update(true, false)\n\t\tchromiumRepo.Update(true, false)\n\t}\n}", "func (p *Processor) Load(incomingLoad Load) *Response {\n\t// approve status set to true be default\n\tapproved := true\n\n\t// parse load amount to float to use it mathematically\n\tincomingLoadAmount, err := strconv.ParseFloat(incomingLoad.LoadAmount[1:], 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// reject any incoming load amount greater than 5000, as it already fails the daily limit check\n\tif incomingLoadAmount > dailyLimit {\n\t\treturn p.newResponse(incomingLoad, false)\n\t}\n\n\t// ignore load with duplicate ID\n\tif p.processedLoads[incomingLoad.ID].CustomerID == incomingLoad.CustomerID {\n\t\treturn nil\n\t}\n\n\t// iterate over processed load to get daily and weekly data per customer\n\tvar totalDailyAmount float64 = 0\n\tvar totalWeeklyAmount float64 = 0\n\tvar transactionCount = 0\n\tfor _, processedLoad := range p.approvedLoads[incomingLoad.CustomerID] {\n\n\t\t// parse processed load amount to float to use it mathematically\n\t\tprocessedLoadAmount, err := strconv.ParseFloat(processedLoad.LoadAmount[1:], 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// add daily total and incrment cout for same day loads\n\t\tif IsSameDay(incomingLoad.Time, processedLoad.Time) {\n\t\t\ttotalDailyAmount += processedLoadAmount\n\t\t\ttransactionCount++\n\t\t}\n\n\t\t// add weekly total for same week loads\n\t\tif IsSameWeek(incomingLoad.Time, processedLoad.Time) {\n\t\t\ttotalWeeklyAmount += processedLoadAmount\n\t\t}\n\t}\n\n\t// reject load if daily transaction count is exceeded\n\tif transactionCount == maxLoadCount {\n\t\tapproved = false\n\t\treturn p.newResponse(incomingLoad, approved)\n\t}\n\n\t// reject load if daily trasaction limit is exceeded\n\tif totalDailyAmount+incomingLoadAmount > dailyLimit {\n\t\tapproved = false\n\t\treturn p.newResponse(incomingLoad, approved)\n\t}\n\n\t// reject load if weekly trasaction limit is exceeded\n\tif totalWeeklyAmount+incomingLoadAmount > weeklyLimit {\n\t\tapproved = false\n\t\treturn p.newResponse(incomingLoad, approved)\n\t}\n\n\t// store load into approved loads\n\tp.approvedLoads[incomingLoad.CustomerID] = append(p.approvedLoads[incomingLoad.CustomerID], incomingLoad)\n\n\treturn p.newResponse(incomingLoad, approved)\n}", "func (n *mockAgent) load(s persistapi.AgentState) {}", "func (*jsonLoad) Meta() workload.Meta { return jsonLoadMeta }", "func (b *QueryBuilder) Load() []map[string]interface{} {\n\treturn nil\n}", "func (g *gm) loadPve() {\n\tfileName := \"stage.txt\"\n\tdata, err := g.source.Fetch(fileName)\n\tif err != nil {\n\t\tlog.Logger.Fatal(\"Fetch Pve Stage List\",\n\t\t\tlog.ErrorField(err))\n\t}\n\n\tstages := make(map[string]interface{})\n\tif err := json.Unmarshal(data, &stages); err != nil {\n\t\tlog.Logger.Fatal(\"Unmarshal Stage List\",\n\t\t\tlog.ErrorField(err))\n\t}\n\n\tg.pveNum = len(stages) - 1\n}", "func (o *Objects) LoadObjects() error {\n\tdata, err := o.Read(\".stencil/objects.json\")\n\tif err == nil {\n\t\treturn json.Unmarshal(data, o.Before)\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn nil\n\t}\n\treturn err\n}", "func (t *TimeEventRepository) LoadAllEvents() []TimeEvent {\n\tstmt, err := t.db.Prepare(\"SELECT id, dia, tipo, quem, tempo_ocupado, tema, departamento, recorrente FROM time_event\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer stmt.Close()\n\n\trows, err := stmt.Query()\n\tdefer rows.Close()\n\tvar result []TimeEvent\n\n\tfor rows.Next() {\n\t\tr := TimeEvent{}\n\t\terr := rows.Scan(&r.ID, &r.Day, &r.Type, &r.Who, &r.Duration, &r.Subject, &r.Department, &r.Recurrent)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tresult = append(result, r)\n\t}\n\n\treturn result\n}", "func (this *Manager) load() error{\n bytes, err := ioutil.ReadFile(this.filename())\n if err != nil {\n return err\n }\n mp := dynmap.NewDynMap()\n err = mp.UnmarshalJSON(bytes)\n if err != nil {\n return err\n }\n table,err := ToRouterTable(mp)\n if err != nil {\n return err\n }\n this.SetRouterTable(table) \n return nil\n}", "func (c *Context) Load(input []byte) {\n\tc.cleanup()\n\td := &data{}\n\tyaml.Unmarshal(input, d)\n\n\tif d.Tournament == nil {\n\t\treturn\n\t}\n\n\tc.Tournament = NewTournament(d.Tournament.Name, c)\n\tc.Tournament.Public = d.Tournament.Public\n\tc.Tournament.Authorization = d.Tournament.Authorization\n\tfor _, val := range d.Jingles {\n\t\ts, err := NewSong(val.File, c)\n\t\tif err != nil {\n\t\t\tc.Log.Error(err.Error())\n\t\t} else {\n\t\t\tc.Songs.AddUniq(s, c.Log)\n\t\t\tc.Jingles.AddUniq(NewJingle(val.Name, s, val.TimeBeforePoint, val.Point, c), c.Log)\n\t\t}\n\t}\n\tfor _, val := range d.Applications {\n\t\tc.Log.Debug(\"adding application: \" + val)\n\t\tc.Sound.AddUniq(val, c.Log)\n\t}\n\tfor _, val := range d.Tournament.MatchSlots {\n\t\tif val != nil {\n\t\t\tc.Tournament.AddMatchSlot(NewMatchSlot(val.StartsAt, val.Duration, c))\n\t\t}\n\t}\n}", "func Load() (string, test.TestStepFactory, []event.Name) {\n\treturn Name, New, Events\n}", "func loadTestObjects(obj interface{}, opts *ebpf.CollectionOptions) error {\n\tspec, err := loadTest()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn spec.LoadAndAssign(obj, opts)\n}", "func (suite *EventStoreTestSuite) TestLoadAll() {\n\tid, _ := uuid.Parse(\"c1138e5f-f6fb-4dd0-8e79-255c6c8d3756\")\n\ttimestamp := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)\n\n\texpectedEvents := []eh.Event{\n\t\teh.NewEventForAggregate(mocks.EventType, &mocks.EventData{Content: \"event1\"},\n\t\t\ttimestamp, mocks.AggregateType, id, 1),\n\t\teh.NewEventForAggregate(mocks.EventType, &mocks.EventData{Content: \"event2\"},\n\t\t\ttimestamp, mocks.AggregateType, id, 2),\n\t}\n\n\t_ = suite.store.Save(context.Background(), expectedEvents, 0)\n\n\tevents, err := suite.store.LoadAll(context.Background())\n\tassert.Nil(suite.T(), err)\n\tassert.Len(suite.T(), events, 2)\n\n\tfor i, event := range events {\n\t\tif err := eh.CompareEvents(event, expectedEvents[i]); err != nil {\n\t\t\tsuite.T().Error(\"the event was incorrect:\", err)\n\t\t}\n\t\tif event.Version() != i+1 {\n\t\t\tsuite.T().Error(\"the event version should be correct:\", event, event.Version())\n\t\t}\n\t}\n}", "func (s *DbRecorder) Load() error {\n\twhereParts := s.WhereIds()\n\tdest := s.FieldReferences(false)\n\n\tq := s.builder.Select(s.colList(false, false)...).From(s.table).Where(whereParts)\n\terr := q.QueryRow().Scan(dest...)\n\n\treturn err\n}", "func (s *Store) loadAll() error {\n\tfiles, err := s.ListFiles(s.Dir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to list %s: %v\", s.Dir, err)\n\t}\n\n\tfor _, file := range files {\n\t\tfilepath := path.Join(s.Dir, file)\n\t\terr := s.loadPath(filepath)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to load %s: %v\", filepath, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (rrb *RRBalancer) Load(elements []interface{}) error {\n\trrb.mu.Lock()\n\tdefer rrb.mu.Unlock()\n\trrb.currentBackends.Store(newCircularArray(elements))\n\treturn nil\n}", "func (r *BonusRewarder) LoadStakingDataset() error {\n\ttask := LoadStakingDatasetTask{\n\t\tfilepath: r.config.Pool.DatasetFilepath(),\n\t\tpoolAddress: r.config.Pool.Address,\n\t\tstartBlock: r.config.Pool.Dataset.StartBlock,\n\t}\n\n\tif err := task.Execute(); err != nil {\n\t\treturn err\n\t}\n\n\tr.stakingEventMap = task.stakingDataset.EventMap\n\n\treturn nil\n}", "func (tui *TUI) LoadData() {\n\ttui.Tables.Clear()\n\ttui.PreviewTable.Clear().SetTitle(TitlePreviewView)\n\ttui.Schemas.Clear()\n\n\tschemas, err := tui.dc.Current().ListSchemas()\n\tif err != nil {\n\t\ttui.showError(err)\n\t\treturn\n\t}\n\n\tvar firstSchema string\n\tif len(schemas) > 0 {\n\t\tfirstSchema = schemas[0]\n\t} else {\n\t\ttui.showWarning(\"no schema to select\")\n\t\treturn\n\t}\n\n\ttables, err := tui.dc.Current().ListTables(firstSchema)\n\tif err != nil {\n\t\ttui.showError(err)\n\t\treturn\n\t}\n\n\ttui.queueUpdateDraw(func() {\n\t\tfor _, table := range tables {\n\t\t\ttui.Tables.AddItem(table, \"\", 0, nil)\n\t\t}\n\t\tfor _, schema := range schemas {\n\t\t\ttui.Schemas.AddItem(schema, \"\", 0, nil)\n\t\t}\n\t\ttui.App.SetFocus(tui.Sources)\n\t})\n}", "func (list *List) Load(sources ...ProxySource) {\n\tfor _, source := range sources {\n\t\tgo Fetch(list.in, source)\n\t}\n}", "func (s *MockStore) Load(collection string) ([]string, error) {\n\titems := []string{}\n\tfor _, item := range s.Data[collection] {\n\t\titems = append(items, item)\n\t}\n\treturn items, nil\n}", "func LoadFromDB(g *Game) error {\n\n db, err := GetDBConnection(g.databaseURL)\n if err != nil {\n return err\n }\n defer db.Close()\n\n rows, err := db.Query(\"SELECT \" +\n \"id, \" +\n \"COALESCE(hero_name, '') AS hero_name, \" +\n \"COALESCE(player_name, '') AS player_name,\" +\n \"COALESCE(player_lastname, '') AS player_lastname, \" +\n \"COALESCE(token, '') AS token, \" +\n \"COALESCE(twitter, '') AS twiter, \" +\n \"COALESCE(email, 'NoEmail') AS email, \" +\n \"hero_level, \" +\n \"COALESCE(hclass, '') AS hclass , +\" +\n \"COALESCE(race, '') AS race , +\" +\n \"COALESCE(title, '') AS title , +\" +\n \" ttl, hero_online, xpos, ypos, \" +\n \"IFNULL(weapon, 0), IFNULL(tunic, 0), IFNULL(shield, 0), IFNULL(leggings, 0), IFNULL(ring, 0), \" +\n \"IFNULL(gloves, 0), IFNULL(boots, 0), IFNULL(helm, 0), IFNULL(charm, 0) , IFNULL(amulet, 0) \" +\n \"total_equipment FROM hero\")\n\n if err != nil {\n return err\n }\n defer rows.Close()\n\n for rows.Next() {\n hero := &Hero{Equipment: &Equipment{}}\n var ttl int\n\n err = rows.Scan(&hero.id, &hero.HeroName, &hero.FirstName, &hero.LastName, &hero.token, &hero.Twitter, &hero.Email,\n &hero.Level, &hero.HeroClass, &hero.HeroRace, &hero.HeroTitle, &ttl, &hero.Enabled,\n &hero.Xpos, &hero.Ypos, &hero.Equipment.Weapon, &hero.Equipment.Tunic, &hero.Equipment.Shield, &hero.Equipment.Leggings, &hero.Equipment.Ring, &hero.Equipment.Gloves,\n &hero.Equipment.Boots, &hero.Equipment.Helm, &hero.Equipment.Charm, &hero.Equipment.Amulet)\n\n if err != nil {\n log.Error(err)\n continue\n }\n\n hero.nextLevelAt = time.Now().Add(time.Duration(ttl) * time.Second)\n g.heroes = append(g.heroes, hero)\n }\n err = rows.Err()\n if err != nil {\n return err\n }\n\n log.Infof(\"Loaded %d Heros from database.\", len(g.heroes))\n\n return nil\n}", "func (s *LiftingStorage) Load(repetitions []lifting.Repetition) error {\n\ttx, err := s.db.Beginx()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, rep := range repetitions {\n\t\tworkout, err := lifting.RepetitionToWorkout(rep)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\n\t\tif workout.ID == nil {\n\t\t\tfmt.Println(workout.Sets)\n\t\t\t_, err = tx.NamedExec(\n\t\t\t\tnamedInsert,\n\t\t\t\t&workout,\n\t\t\t)\n\t\t} else {\n\t\t\tfmt.Println(workout.Sets)\n\t\t\t_, err = tx.NamedExec(\n\t\t\t\tnamedUpdate,\n\t\t\t\t&workout,\n\t\t\t)\n\n\t\t}\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func (e *Element) LoadGoml(paths ...string) error {\n\tfor _, p := range paths {\n\t\tbts, err := ioutil.ReadFile(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = e.AddGoml(bts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (api *api) load() {\n\tcontent, err := ioutil.ReadFile(api.ConfigFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tv := map[string]string{}\n\terr = json.Unmarshal(content, &v)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tfor k, t := range v {\n\t\terr = api.addService(k, t)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}", "func (d *DataLoader) LoadMany(keys []interface{}) ([]interface{}, error) {\n\treturn FutureAll(keys, d.Load)\n}", "func (s *store) LoadChunks(\n\tctx context.Context,\n\tprojectID, appID string,\n\tkind model.InsightMetricsKind,\n\tstep model.InsightStep,\n\tfrom time.Time,\n\tcount int,\n) (insight.Chunks, error) {\n\tfrom = insight.NormalizeTime(from, step)\n\tpaths := insight.DetermineFilePaths(projectID, appID, kind, step, from, count)\n\tvar chunks []insight.Chunk\n\tfor _, p := range paths {\n\t\tc, err := s.getChunk(ctx, p, kind)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tchunks = append(chunks, c)\n\t}\n\n\treturn chunks, nil\n}", "func (j *JobLog) BeforeLoad() {\n}", "func (e *engine) load() error {\n\tdatabaseNames, err := listDir(e.cfg.Dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, databaseName := range databaseNames {\n\t\t_, err := e.CreateDatabase(databaseName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func edgesToLoad(n *gen.Type, action string) (EdgesToLoad, error) {\n\tg, err := groupsForAction(n, action)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn edgesToLoadHelper(n, walk{}, g)\n}", "func d14loadNodes(nodeA, nodeB *d14nodeT, parVars *d14partitionVarsT) {\n\tfor index := 0; index < parVars.total; index++ {\n\t\ttargetNodeIndex := parVars.partition[index]\n\t\ttargetNodes := []*d14nodeT{nodeA, nodeB}\n\n\t\t// It is assured that d14addBranch here will not cause a node split.\n\t\td14addBranch(&parVars.branchBuf[index], targetNodes[targetNodeIndex], nil)\n\t}\n}", "func (s *ShardFamily) Load(slice *Slice) (err error) {\n\n}", "func init() {\n\tcdb = &classDB{classMap: make(map[int]Class)}\n\tif err := loadData(cdb); err != nil {\n\t\tlog.Print(\"Panic in loading data\")\n\t}\n\tlog.Print(\"Class Data from file is loaded!!\")\n\n}", "func LoadPeriods(api *eos.API, includePast, includeFuture bool) []Period {\n\n\tvar periods []Period\n\tvar periodRequest eos.GetTableRowsRequest\n\tperiodRequest.Code = \"dao.hypha\"\n\tperiodRequest.Scope = \"dao.hypha\"\n\tperiodRequest.Table = \"periods\"\n\tperiodRequest.Limit = 1000\n\tperiodRequest.JSON = true\n\n\tperiodResponse, err := api.GetTableRows(context.Background(), periodRequest)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tperiodResponse.JSONToStructs(&periods)\n\n\tvar returnPeriods []Period\n\tcurrentPeriod, err := CurrentPeriod(&periods)\n\tif (includePast || includeFuture) && err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, period := range periods {\n\t\tif includePast || includeFuture {\n\t\t\tif includePast && period.PeriodID <= uint64(currentPeriod) {\n\t\t\t\treturnPeriods = append(returnPeriods, period)\n\t\t\t} else if includeFuture && period.PeriodID >= uint64(currentPeriod) {\n\t\t\t\treturnPeriods = append(returnPeriods, period)\n\t\t\t}\n\t\t}\n\t}\n\treturn returnPeriods\n}", "func TestLoad(t *testing.T) {\n\tfilename := \"../test.json\"\n\thost := \"http://localhost:9200\"\n\n\tLoad(host, filename, nil)\n\n}", "func (d *dht) Load(slots map[SlotID]*SlotInfo) error {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\td.slotVsNodes = slots // TODO: Verify if this will share memory\n\treturn nil\n}", "func train() {\n\tvar dataPoints []TransferData\n\tfor _, source := range *AgentRouter.Agents {\n\t\tdata, err := getHistory(source)\n\t\tif err == nil {\n\t\t\tdataPoints = append(dataPoints, data...)\n\t\t}\n\t}\n\tif len(dataPoints) == 0 {\n\t\treturn\n\t}\n\n\t// Reinitialize the model\n\tlr := new(regression.Regression)\n\tlr.SetObserved(\"Get throughput\")\n\tlr.SetVar(0, \"CPU usage\")\n\tlr.SetVar(1, \"Memory usage\")\n\tAgentRouter.LinearRegression = lr\n\n\tfor _, obj := range dataPoints {\n\t\tAgentRouter.LinearRegression.Train(regression.DataPoint(obj.Throughput, []float64{obj.CpuUsage, obj.MemUsage}))\n\t}\n\tAgentRouter.LinearRegression.Run()\n\tlogs.WithFields(logs.Fields{\n\t\t\"CronInterval\": AgentRouter.CronInterval,\n\t\t\"Data\": AgentRouter.CSVfile,\n\t}).Println(\"Router successfully retrained\")\n\n\terr := convertToCSV(dataPoints)\n\tif err != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"Error\": err,\n\t\t}).Println(\"Error while saving data\")\n\t}\n}", "func LoadPipelines(db gorp.SqlExecutor, projectID int64, loadDependencies bool) ([]sdk.Pipeline, error) {\n\tvar pip []sdk.Pipeline\n\tquery := `SELECT id, name, description, project_id, last_modified, from_repository\n\t\t\t FROM pipeline\n\t\t\t WHERE project_id = $1\n\t\t\t ORDER BY pipeline.name`\n\n\trows, errquery := db.Query(query, projectID)\n\tif errquery != nil {\n\t\treturn nil, errquery\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar p sdk.Pipeline\n\t\tvar lastModified time.Time\n\n\t\t// scan pipeline id\n\t\tif err := rows.Scan(&p.ID, &p.Name, &p.Description, &p.ProjectID, &lastModified, &p.FromRepository); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp.LastModified = lastModified.Unix()\n\n\t\tif loadDependencies {\n\t\t\t// load pipeline stages\n\t\t\tif err := LoadPipelineStage(context.TODO(), db, &p); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tpip = append(pip, p)\n\t}\n\n\tfor i := range pip {\n\t\tparams, err := GetAllParametersInPipeline(context.TODO(), db, pip[i].ID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpip[i].Parameter = params\n\t}\n\n\treturn pip, nil\n}", "func (c *Client) LoadAll() ([]*eskip.Route, error) {\n\trouteInfo, err := c.LoadAndParseAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn infoToRoutesLogged(routeInfo), nil\n}", "func (env *Solo) LoadSnapshot(fname string) {\n\tenv.glbMutex.Lock()\n\tdefer env.glbMutex.Unlock()\n\n\tb, err := os.ReadFile(fname)\n\trequire.NoError(env.T, err)\n\tvar snapshot soloSnapshot\n\terr = json.Unmarshal(b, &snapshot)\n\trequire.NoError(env.T, err)\n\n\tenv.utxoDB.SetState(snapshot.UtxoDB)\n\tfor _, chainSnapshot := range snapshot.Chains {\n\t\tsckp, err := rwutil.ReadFromBytes(chainSnapshot.StateControllerKeyPair, new(cryptolib.KeyPair))\n\t\trequire.NoError(env.T, err)\n\n\t\tchainID, err := isc.ChainIDFromBytes(chainSnapshot.ChainID)\n\t\trequire.NoError(env.T, err)\n\n\t\tokp, err := rwutil.ReadFromBytes(chainSnapshot.OriginatorPrivateKey, new(cryptolib.KeyPair))\n\t\trequire.NoError(env.T, err)\n\n\t\tval, err := isc.AgentIDFromBytes(chainSnapshot.ValidatorFeeTarget)\n\t\trequire.NoError(env.T, err)\n\n\t\tdb, err := env.chainStateDatabaseManager.ChainStateKVStore(chainID)\n\t\trequire.NoError(env.T, err)\n\t\tfor i := 0; i < len(chainSnapshot.DB); i += 2 {\n\t\t\terr = db.Set(chainSnapshot.DB[i], chainSnapshot.DB[i+1])\n\t\t\trequire.NoError(env.T, err)\n\t\t}\n\n\t\tchainData := chainData{\n\t\t\tName: chainSnapshot.Name,\n\t\t\tStateControllerKeyPair: sckp,\n\t\t\tChainID: chainID,\n\t\t\tOriginatorPrivateKey: okp,\n\t\t\tValidatorFeeTarget: val,\n\t\t\tdb: db,\n\t\t}\n\t\tenv.addChain(chainData)\n\t}\n}", "func loadWorkloadBatches(sqlDB *gosql.DB, table workload.Table) ([]time.Time, int64, error) {\n\tif _, err := sqlDB.Exec(`CREATE TABLE \"` + table.Name + `\" ` + table.Schema); err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tvar now time.Time\n\tvar timestamps []time.Time\n\tvar benchBytes int64\n\tvar numRows int\n\n\tvar insertStmtBuf bytes.Buffer\n\tvar params []interface{}\n\tfor batchIdx := 0; batchIdx < table.InitialRows.NumBatches; batchIdx++ {\n\t\tif _, err := sqlDB.Exec(`BEGIN`); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\n\t\tparams = params[:0]\n\t\tinsertStmtBuf.Reset()\n\t\tinsertStmtBuf.WriteString(`INSERT INTO \"` + table.Name + `\" VALUES `)\n\t\tfor _, row := range table.InitialRows.BatchRows(batchIdx) {\n\t\t\tnumRows++\n\t\t\tif len(params) != 0 {\n\t\t\t\tinsertStmtBuf.WriteString(`,`)\n\t\t\t}\n\t\t\tinsertStmtBuf.WriteString(`(`)\n\t\t\tfor colIdx, datum := range row {\n\t\t\t\tif colIdx != 0 {\n\t\t\t\t\tinsertStmtBuf.WriteString(`,`)\n\t\t\t\t}\n\t\t\t\tbenchBytes += workload.ApproxDatumSize(datum)\n\t\t\t\tparams = append(params, datum)\n\t\t\t\tfmt.Fprintf(&insertStmtBuf, `$%d`, len(params))\n\t\t\t}\n\t\t\tinsertStmtBuf.WriteString(`)`)\n\t\t}\n\t\tif _, err := sqlDB.Exec(insertStmtBuf.String(), params...); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\n\t\tif err := sqlDB.QueryRow(`SELECT transaction_timestamp(); COMMIT;`).Scan(&now); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\ttimestamps = append(timestamps, now)\n\t}\n\n\tvar totalRows int\n\tif err := sqlDB.QueryRow(\n\t\t`SELECT count(*) FROM \"` + table.Name + `\"`,\n\t).Scan(&totalRows); err != nil {\n\t\treturn nil, 0, err\n\t}\n\tif numRows != totalRows {\n\t\treturn nil, 0, errors.Errorf(`sanity check failed: expected %d rows got %d`, numRows, totalRows)\n\t}\n\n\treturn timestamps, benchBytes, nil\n}", "func TestLoadConcurrent(t *testing.T) {\n\tvar wg sync.WaitGroup\n\n\tfor i := 0; i < 100; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\t_ = Load(testCfg, true)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}", "func LoadTestThroughput(intervals IntervalGenerator, requests chan interface{}, requestExec RequestExecutor) {\n\t\t//start := time.Now().UnixNano()\n\t\t//recorder <- &StartEvent{start}\n\n\t\tvar overage int64\n\t\toverageStart := time.Now().UnixNano()\n\t\tfor request := range requests {\n\t\t\twait := intervals(overageStart)\n\t\t\tadjust := int64(math.Min(float64(wait), float64(overage)))\n\t\t\twait -= adjust\n\t\t\toverage -= adjust\n\t\t//\trecorder <- &WaitEvent{wait, overage}\n\t\t\ttime.Sleep(time.Duration(wait))\n\n\t\t//\trecorder <- &StartRequestEvent{time.Now().UnixNano(), request}\n\t\t// reqStart := time.Now().UnixNano()\n\t\t\t_, _ = requestExec(time.Now().UnixNano(), request)\n\t\t//\trecorder <- &EndRequestEvent{reqStart, time.Now().UnixNano(), res, err}\n\n\t\t\toverage += time.Now().UnixNano() - overageStart - wait\n\t\t\toverageStart = time.Now().UnixNano()\n\t\t}\n\t\t//recorder <- &EndEvent{start, time.Now().UnixNano()}\n\t\t//close(recorder)\n}", "func d18loadNodes(nodeA, nodeB *d18nodeT, parVars *d18partitionVarsT) {\n\tfor index := 0; index < parVars.total; index++ {\n\t\ttargetNodeIndex := parVars.partition[index]\n\t\ttargetNodes := []*d18nodeT{nodeA, nodeB}\n\n\t\t// It is assured that d18addBranch here will not cause a node split.\n\t\td18addBranch(&parVars.branchBuf[index], targetNodes[targetNodeIndex], nil)\n\t}\n}", "func loadAirports(db *bolt.DB, dataDir string) error {\n\tapts, err := os.Open(fmt.Sprintf(\"%s/%s\", dataDir, \"airports.csv\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer apts.Close()\n\n\tr := csv.NewReader(apts)\n\t_, err = r.Read() // skip header\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(\"Airports\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb := tx.Bucket([]byte(\"Airports\"))\n\n\t\tfor {\n\t\t\trecord, err := r.Read()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"airport read\")\n\t\t\t}\n\n\t\t\tlatitude, _ := strconv.ParseFloat(record[4], 64)\n\t\t\tlongitude, _ := strconv.ParseFloat(record[5], 64)\n\t\t\televation, _ := strconv.ParseInt(record[6], 10, 64)\n\t\t\tapt := Airport{record[1],\n\t\t\t\trecord[3],\n\t\t\t\tlatitude,\n\t\t\t\tlongitude,\n\t\t\t\televation,\n\t\t\t\trecord[10],\n\t\t\t\trecord[9],\n\t\t\t\trecord[8],\n\t\t\t\trecord[7],\n\t\t\t\trecord[13]}\n\n\t\t\tm, err := msgpack.Marshal(&apt)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"airport marshal\")\n\t\t\t}\n\n\t\t\terr = b.Put([]byte(record[1]), m)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"database put\")\n\t\t\t}\n\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn err\n}", "func (c *Cab) Load() chan error {\n\treturn goroutine(func(out chan error) {\n\t\tr := c.db.QueryRow(\"select id, type, driverId, number from Cab where id = ?\", c.ID)\n\t\tout <- c.loader(r)\n\t})\n\n}", "func (s *Store) Load(ctx context.Context, aggregateID string, fromVersion, toVersion int) (eventsource.History, error) {\n\tdb, err := s.accessor.Open(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"load failed; unable to connect to db\")\n\t}\n\tdefer s.accessor.Close(db)\n\n\treturn s.doLoad(ctx, db, aggregateID, fromVersion, toVersion)\n}", "func LoadExecutions(db database.QueryExecuter) ([]WorkerExecution, error) {\n\tquery := `\n\t\tselect poller_execution.id, application.name, pipeline.name, poller_execution.execution_date, poller_execution.status, poller_execution.data\n\t\tfrom poller_execution, application, pipeline\n\t\twhere poller_execution.application_id = application.id\n\t\tand poller_execution.pipeline_id = pipeline.id\n\t\torder by poller_execution.execution_date desc\n\t`\n\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tvar es []WorkerExecution\n\n\tfor rows.Next() {\n\t\tvar e WorkerExecution\n\t\tvar j sql.NullString\n\n\t\tif err := rows.Scan(&e.ID, &e.Application, &e.Pipeline, &e.Execution, &e.Status, &j); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif j.Valid {\n\t\t\tb := []byte(j.String)\n\t\t\tjson.Unmarshal(b, &e.Events)\n\t\t}\n\t\tes = append(es, e)\n\t}\n\n\treturn es, nil\n}", "func (r *batchRangeVectorIterator) load(start, end int64) {\n\tfor lbs, sample, hasNext := r.iter.Peek(); hasNext; lbs, sample, hasNext = r.iter.Peek() {\n\t\tif sample.Timestamp > end {\n\t\t\t// not consuming the iterator as this belong to another range.\n\t\t\treturn\n\t\t}\n\t\t// the lower bound of the range is not inclusive\n\t\tif sample.Timestamp <= start {\n\t\t\t_ = r.iter.Next()\n\t\t\tcontinue\n\t\t}\n\t\t// adds the sample.\n\t\tvar series *promql.Series\n\t\tvar ok bool\n\t\tseries, ok = r.window[lbs]\n\t\tif !ok {\n\t\t\tvar metric labels.Labels\n\t\t\tif metric, ok = r.metrics[lbs]; !ok {\n\t\t\t\tvar err error\n\t\t\t\tmetric, err = promql_parser.ParseMetric(lbs)\n\t\t\t\tif err != nil {\n\t\t\t\t\t_ = r.iter.Next()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr.metrics[lbs] = metric\n\t\t\t}\n\n\t\t\tseries = getSeries()\n\t\t\tseries.Metric = metric\n\t\t\tr.window[lbs] = series\n\t\t}\n\t\tp := promql.Point{\n\t\t\tT: sample.Timestamp,\n\t\t\tV: sample.Value,\n\t\t}\n\t\tseries.Points = append(series.Points, p)\n\t\t_ = r.iter.Next()\n\t}\n}", "func Load(fs *axis2.FileSystem, log rblutil.Logger) (data *Database, err error) {\n\tdefer errors.TrapError(&err, log)\n\n\trblutil.LogSeparator(log)\n\tlog.Println(\"Loading Addons...\")\n\n\tdata = &Database{\n\t\tTable: map[string]*Addon{},\n\t\tMeta: map[string]*Meta{},\n\t\tPacks: map[string]*PackMeta{},\n\t\tBanks: map[string]string{},\n\n\t\ttagsFirst: map[string][]string{},\n\t\ttagsLast: map[string][]string{},\n\n\t\tupdateBlacklist: map[string]bool{},\n\n\t\tGlobals: NewFileList(),\n\t}\n\n\tlog.Println(\" Loading Global Settings...\")\n\tglobal := NewPackMeta()\n\tcontent, err := fs.ReadAll(\"addons/global.meta\")\n\tif err == nil {\n\t\terr := json.Unmarshal(killMetaComments.ReplaceAllLiteral(content, []byte(\"\\n\")), global)\n\t\tif err != nil {\n\t\t\terrors.RaiseWrappedError(\"While loading global.meta\", err)\n\t\t}\n\t}\n\tdata.Writers = append(data.Writers, global.Writers...)\n\tfor k, v := range global.TagsFirst {\n\t\tdata.tagsFirst[k] = v\n\t}\n\tfor k, v := range global.TagsLast {\n\t\tdata.tagsLast[k] = v\n\t}\n\n\t// Import any tags defined by native APIs (generally script runners).\n\tfor k, v := range DefaultFirst {\n\t\tdata.tagsFirst[k] = v\n\t}\n\tfor k, v := range DefaultLast {\n\t\tdata.tagsLast[k] = v\n\t}\n\n\tlog.Println(\" Attempting to Read Auto-Update Blacklist...\")\n\tcontent, err = fs.ReadAll(\"addons/update_blacklist.txt\")\n\tif err == nil {\n\t\tlog.Println(\" Read OK, loading...\")\n\t\tfor _, line := range strings.Split(string(content), \"\\n\") {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tif line == \"\" || line[0] == '#' {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata.updateBlacklist[line] = true\n\t\t}\n\t} else {\n\t\tlog.Println(\" Read failed (this is most likely ok)\\n Error:\", err)\n\t}\n\n\tlog.Println(\" Attempting to Read Content Server List...\")\n\tcontent, err = fs.ReadAll(\"addons/content_servers.txt\")\n\tif err == nil {\n\t\tlog.Println(\" Read OK, loading...\")\n\t\tfor _, line := range strings.Split(string(content), \"\\n\") {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tif line == \"\" || line[0] == '#' {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata.Servers = append(data.Servers, line)\n\t\t}\n\t} else {\n\t\tlog.Println(\" Read failed (this is most likely ok)\\n Error:\", err)\n\t}\n\n\tlog.Println(\" Loading Addons From Local Directories...\")\n\n\tloadGlobals(fs, data, nil, nil, \"addons\")\n\tpmeta := loadMeta(fs, \"\", \"addons\", nil)\n\n\tfor _, dir := range fs.ListDirs(\"addons\") {\n\t\tloadDir(fs, data, dir, \"addons/\"+dir, nil, nil, pmeta)\n\t}\n\n\tlog.Println(\" Loading Addons From Globally Requested Addon Packs...\")\n\n\tfor _, pack := range global.Dependencies {\n\t\tloadPack(fs, log, data, pack, fs.Exists(\"addons/\"+pack+\".zip\"))\n\t}\n\n\tlog.Println(\" Loading Addons From Addon Packs...\")\n\n\tfor _, filename := range fs.ListFiles(\"addons\") {\n\t\tif strings.HasSuffix(filename, \".zip\") {\n\t\t\tname := rblutil.StripExt(filename)\n\t\t\tloadPack(fs, log, data, name, true)\n\t\t}\n\t}\n\n\tlog.Println(\" Checking Loaded Data...\")\n\n\t// Sort the addon list\n\tsort.Sort(addonSorter(data.List))\n\n\t// Add global files from addons\n\tdata.Globals.UpdateGlobals(data.List)\n\n\t// Fill in extra fields.\n\tfor _, addon := range data.List {\n\t\tdata.Table[addon.Meta.Name] = addon\n\t\tdata.Meta[addon.Meta.Name] = addon.Meta\n\t\tif addon.Meta.Tags[\"DocPack\"] {\n\t\t\tdata.DocPacks = append(data.DocPacks, addon.Meta)\n\t\t}\n\t}\n\n\t// Find any duplicates.\n\tdups := map[string]bool{}\n\tfor i := range data.List {\n\t\tif dups[data.List[i].Meta.Name] {\n\t\t\terrors.RaiseError(\" Duplicate addon found: \\\"\" + data.List[i].Meta.Name + \"\\\"\")\n\t\t}\n\t\tdups[data.List[i].Meta.Name] = true\n\t}\n\treturn data, nil\n}", "func loadData(filePath string, numRecords int) []Record {\n\n\tvar records []Record\n\n\t// Load lines from CSV\n\tlines, err := getLinesFromCSV(filePath)\n\tcheck(err)\n\n\t// get rid of column names\n\tlines = lines[1:]\n\n\t// convert lines to records slice\n\tfor i := 0; i < numRecords && i < len(lines); i++ {\n\t\trecords = append(records, lineToRecord(lines[i]))\n\t}\n\t\n\n\treturn records\n}", "func Loadlangdata(id1 string, id2 int) {\n\n\t/*\n\t\t// arcanesData\n\n\t\turl := \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/arcanesData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/arcanesData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ := http.NewRequest(\"GET\", url, nil)\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ := ioutil.ReadAll(res.Body)\n\t\tarcanesData[id1] = string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// conclaveData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/conclaveData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/conclaveData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tconclaveData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// eventsData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/eventsData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/eventsData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\teventsData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// operationTypes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/operationTypes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/operationTypes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\toperationTypes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// persistentEnemyData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/persistentEnemyData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/persistentEnemyData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tpersistentEnemyData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\t*/\n\t// solNodes\n\turl := Dirpath + \"data/\" + id1 + \"/solNodes.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"solNodes.json\"\n\t}\n\treq, err := os.Open(url)\n\t// if we os.Open returns an error then handle it\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tdefer req.Close()\n\tbody, _ := ioutil.ReadAll(req)\n\tfmt.Println(id1)\n\tvar result map[string]interface{}\n\tjson.Unmarshal([]byte(body), &result)\n\tSortieloc[id1] = result\n\n\t// sortieData\n\turl = Dirpath + \"data/\" + id1 + \"/sortieData.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"sortieData.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\terr = json.Unmarshal(body, &Sortielang)\n\tSortiemodtypes[id1] = make(LangMap)\n\tSortiemodtypes[id1] = Sortielang[\"modifierTypes\"]\n\tSortiemoddesc[id1] = Sortielang[\"modifierDescriptions\"]\n\tSortiemodbosses[id1] = Sortielang[\"bosses\"]\n\n\t// FissureModifiers\n\turl = Dirpath + \"data/\" + id1 + \"/fissureModifiers.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"fissureModifiers.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tFissureModifiers[id1] = result\n\n\t// MissionTypes\n\turl = Dirpath + \"data/\" + id1 + \"/missionTypes.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"missionTypes.json\"\n\t}\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tMissionTypes[id1] = result\n\n\t// languages\n\turl = Dirpath + \"data/\" + id1 + \"/languages.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"languages.json\"\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tLanguages[id1] = result\n\n\t// FactionsData\n\turl = Dirpath + \"data/\" + id1 + \"/factionsData.json\"\n\tif id1 == \"en\" {\n\t\turl = Dirpath + \"data/\" + \"factionsData.json\"\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tjson.Unmarshal([]byte(body), &result)\n\tFactionsData[id1] = result\n\n\t// sortieRewards\n\turl = Dirpath + \"data/\" + id1 + \"/sortieRewards.json\"\n\tif id1 != \"en\" {\n\t\t// url = \"https://drops.warframestat.us/data/sortieRewards.json\"\n\t\treturn\n\t}\n\t// fmt.Println(\"url:\", url)\n\treq, err = os.Open(url)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer req.Close()\n\tbody, _ = ioutil.ReadAll(req)\n\tvar result2 string\n\n\tjson.Unmarshal([]byte(body), &result2)\n\tSortieRewards = body\n\n\t/*\n\t\t// syndicatesData\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/syndicatesData.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/syndicatesData.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tsyndicatesData[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// synthTargets\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/synthTargets.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/synthTargets.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tsynthTargets[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// upgradeTypes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/upgradeTypes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/upgradeTypes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tupgradeTypes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// warframes\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/warframes.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/warframes.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\twarframes[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\n\t\t// weapons\n\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/\"+id1+\"/weapons.json\"\n\t\tif (id1 ==\"en\"){\n\t\t\t\turl = \"https://raw.githubusercontent.com/WFCD/warframe-worldstate-data/master/data/weapons.json\"\n\t\t}\n\t\t// fmt.Println(\"url:\", url)\n\t\treq, _ = http.NewRequest(\"GET\", url, nil)\n\t\tres, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Errored when sending request to the server\")\n\t\t\treturn\n\t\t}\n\t\tdefer res.Body.Close()\n\t\tbody, _ = ioutil.ReadAll(res.Body)\n\t\tweapons[id1]= string(body[:])\n\t\t_, _ = io.Copy(ioutil.Discard, res.Body)\n\t*/\n\treturn\n}", "func LoadData(startDate, endDate time.Time, interval time.Duration, exchangeName string, dataType int64, fPair currency.Pair, a asset.Item, isUSDTrackingPair bool) (*kline.DataFromKline, error) {\n\tresp := kline.NewDataFromKline()\n\tswitch dataType {\n\tcase common.DataCandle:\n\t\tklineItem, err := getCandleDatabaseData(\n\t\t\tstartDate,\n\t\t\tendDate,\n\t\t\tinterval,\n\t\t\texchangeName,\n\t\t\tfPair,\n\t\t\ta)\n\t\tif err != nil {\n\t\t\tif isUSDTrackingPair {\n\t\t\t\treturn nil, fmt.Errorf(\"%w for %v %v %v. Please save USD candle pair data to the database or set `disable-usd-tracking` to `true` in your config. %v\", errNoUSDData, exchangeName, a, fPair, err)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"could not retrieve database candle data for %v %v %v, %v\", exchangeName, a, fPair, err)\n\t\t}\n\t\tresp.Item = klineItem\n\t\tfor i := range klineItem.Candles {\n\t\t\tif klineItem.Candles[i].ValidationIssues != \"\" {\n\t\t\t\tlog.Warnf(common.Data, \"Candle validation issue for %v %v %v: %v\", klineItem.Exchange, klineItem.Asset, klineItem.Pair, klineItem.Candles[i].ValidationIssues)\n\t\t\t}\n\t\t}\n\tcase common.DataTrade:\n\t\ttrades, err := trade.GetTradesInRange(\n\t\t\texchangeName,\n\t\t\ta.String(),\n\t\t\tfPair.Base.String(),\n\t\t\tfPair.Quote.String(),\n\t\t\tstartDate,\n\t\t\tendDate)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklineItem, err := trade.ConvertTradesToCandles(\n\t\t\tgctkline.Interval(interval),\n\t\t\ttrades...)\n\t\tif err != nil {\n\t\t\tif isUSDTrackingPair {\n\t\t\t\treturn nil, fmt.Errorf(\"%w for %v %v %v. Please save USD pair trade data to the database or set `disable-usd-tracking` to `true` in your config. %v\", errNoUSDData, exchangeName, a, fPair, err)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"could not retrieve database trade data for %v %v %v, %v\", exchangeName, a, fPair, err)\n\t\t}\n\t\tresp.Item = klineItem\n\tdefault:\n\t\tif isUSDTrackingPair {\n\t\t\treturn nil, fmt.Errorf(\"%w for %v %v %v. Please add USD pair data to your CSV or set `disable-usd-tracking` to `true` in your config\", errNoUSDData, exchangeName, a, fPair)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"could not retrieve database data for %v %v %v, %w\", exchangeName, a, fPair, common.ErrInvalidDataType)\n\t}\n\tresp.Item.Exchange = strings.ToLower(resp.Item.Exchange)\n\n\treturn resp, nil\n}", "func test1() {\n\n\t// Read the list of villages\n\tfname := path.Join(conf.Path, \"villages.csv.gz\")\n\tvillages, err := ziparray.ReadStringArray(fname)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor k, v := range villages {\n\t\tu := strings.Split(v, \",\")\n\t\tvillages[k] = u[1]\n\t}\n\n\t// Read some records from the raw file and check them\n\tfname = path.Join(conf.Path, conf.ViRawFile)\n\tfid, err := os.Open(fname)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trdr, err := gzip.NewReader(fid)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tscanner := bufio.NewScanner(rdr)\n\tfor k := 0; k < 100; k++ {\n\t\tnskip := rand.Int() % 1000\n\t\tfor j := 0; j < nskip; j++ {\n\t\t\tscanner.Scan()\n\t\t}\n\t\tline := scanner.Text()\n\t\tfields := strings.Split(line, \",\")\n\t\tdate := fields[conf.ViDateCol]\n\t\tdates := strings.Split(date, \"-\")\n\t\tyear := dates[0]\n\t\tmonth := dates[1]\n\t\tday := dates[2]\n\t\tvid := fields[conf.ViIdCol]\n\n\t\tvix := -1\n\t\tfor jj, v := range villages {\n\t\t\tif vid == v {\n\t\t\t\tvix = jj\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif vix == -1 {\n\t\t\terr = fmt.Errorf(\"cannot find village %s\", vid)\n\t\t\tpanic(err)\n\t\t}\n\n\t\tbucket := vix / conf.ChunkSize\n\t\tposn := vix % conf.ChunkSize\n\n\t\tfname = fmt.Sprintf(\"vis_observed_%02d.gz\", bucket)\n\t\tfname = path.Join(conf.Path, conf.ViBaseDir, year, month, day, fname)\n\t\tvec, err := ziparray.ReadFloat64Array(fname)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\trvis, err := strconv.ParseFloat(fields[conf.ViVisCol], 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif vec[posn] != rvis {\n\t\t\tpanic(\"mismatch in test1\")\n\t\t}\n\t}\n\n\tfmt.Printf(\"test1 passed\\n\")\n}", "func loadAndTrainData(symbol, companyName string, r *csv.Reader,\n\tcomputeLengths []int) error {\n\n\tvals, err := r.ReadAll()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error reading csv\")\n\t}\n\n\tif vals == nil {\n\t\treturn errors.New(fmt.Sprintf(\"empty or invalid CSV for '%v'\", symbol))\n\t}\n\n\t// Only allow if there are enough periods for train and compute\n\tif len(vals) <= 2 {\n\t\treturn errors.New(fmt.Sprintf(\"[%v] not enough periods\", symbol))\n\t}\n\n\tvar periods model.PeriodSlice\n\tfor i, v := range vals {\n\n\t\tvar parseErrors error\n\n\t\tif i == 0 {\n\t\t\t// TODO jpirkey build header to field map index here\n\t\t\tcontinue\n\t\t}\n\n\t\trow := CsvRow{}\n\t\tif row.Date, err = convertTime(v[csvDate]); err != nil {\n\t\t\tparseErrors = multierror.Append(parseErrors, errors.Wrapf(err, \"[%v] date field\", symbol))\n\t\t}\n\t\tif row.Open, err = convertFloat(v[csvOpen]); err != nil {\n\t\t\tparseErrors = multierror.Append(parseErrors, errors.Wrapf(err, \"[%v] open field\", symbol))\n\t\t}\n\t\tif row.High, err = convertFloat(v[csvHigh]); err != nil {\n\t\t\tparseErrors = multierror.Append(parseErrors, errors.Wrapf(err, \"[%v] high field\", symbol))\n\t\t}\n\t\tif row.Low, err = convertFloat(v[csvLow]); err != nil {\n\t\t\tparseErrors = multierror.Append(parseErrors, errors.Wrapf(err, \"[%v] low field\", symbol))\n\t\t}\n\t\tif row.Close, err = convertFloat(v[csvClose]); err != nil {\n\t\t\tparseErrors = multierror.Append(parseErrors, errors.Wrapf(err, \"[%v] close field\", symbol))\n\t\t}\n\t\tif row.Volume, err = convertInt(v[csvVolume]); err != nil {\n\t\t\tparseErrors = multierror.Append(parseErrors, errors.Wrapf(err, \"[%v] volume field\", symbol))\n\t\t}\n\n\t\tif parseErrors == nil {\n\t\t\tp := model.Period{Symbol: symbol, Date: row.Date, Open: row.Open, High: row.High,\n\t\t\t\tLow: row.Low, Close: row.Close, Volume: row.Volume}\n\t\t\tperiods = append(periods, &p)\n\t\t} else {\n\t\t\tlog.Warn(parseErrors)\n\t\t}\n\t}\n\n\tif len(periods) < 2 {\n\t\treturn errors.New(fmt.Sprintf(\"[%v] not enough parsed periods\", symbol))\n\t}\n\n\tsort.Sort(periods)\n\n\ttimer := metrics.GetOrRegisterTimer(\"training-timer\", loadRegistry)\n\ttimer.Time(func() { trainDaily(periods) })\n\n\tinsertCount, err := Repos.PeriodRepo.InsertMany(periods)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[%v] inserting periods\", symbol)\n\t}\n\tif len(periods) != insertCount {\n\t\treturn fmt.Errorf(\"[%v] periods parsed count does not match inserted count\", symbol)\n\t}\n\n\tticker := model.Ticker{Symbol: symbol, Company: companyName}\n\terr = Repos.TickerRepo.InsertOne(&ticker)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[%v] inserting ticker\", symbol)\n\t}\n\n\tif len(computeLengths) > 0 {\n\t\tfor _, computeLength := range computeLengths {\n\t\t\tif len(periods) < computeLength+1 {\n\t\t\t\tlog.Warnf(\"[%v] not enough periods to compute %v length series\",\n\t\t\t\t\tsymbol, computeLength)\n\t\t\t} else {\n\t\t\t\ttimer := metrics.GetOrRegisterTimer(\"compute-timer\", loadRegistry)\n\t\t\t\ttimer.Time(func() { computeSeries(computeLength, symbol, periods) })\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func LoadArrays() {\n\t//SetCSVReader params\n\tgocsv.SetCSVReader(func(in io.Reader) gocsv.CSVReader {\n\t\tr := csv.NewReader(in)\n\t\tr.LazyQuotes = true\n\t\tr.Comma = ';'\n\t\treturn r // Allows use dot as delimiter and use quotes in CSV\n\t})\n\n\t//Viis.csv\n\tViisiFile, err := os.Open(\"Viis.csv\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer ViisiFile.Close()\n\n\tif err := gocsv.UnmarshalFile(ViisiFile, &ViisiArray); err != nil {\n\t\tpanic(err)\n\t}\n\t//rytmityybid.csv\n\tRytmiFile, err := os.Open(\"rytmityybid.csv\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer RytmiFile.Close()\n\n\tif err := gocsv.UnmarshalFile(RytmiFile, &RytmiArray); err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func (v Var[V]) EagerLoading(s *Spec) Var[V] {\n\ts.testingTB.Helper()\n\ts.Before(func(t *T) { _ = v.Get(t) })\n\treturn v\n}", "func (c *Client) load(line string) error {\n\ttbk, dataFD, loaderFD, cleanup, err := parseLine(line)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse line: %w\", err)\n\t}\n\tdefer cleanup()\n\t/*\n\t\tVerify the presence of a bucket with the input key\n\t*/\n\tresp, err := c.GetBucketInfo(tbk)\n\tif err != nil {\n\t\tlog.Error(\"Error finding existing bucket: %v\\n\", err)\n\t\treturn fmt.Errorf(\"error finding existing bucket: %w\", err)\n\t}\n\tlog.Info(\"Latest Year: %v\\n\", resp.LatestYear)\n\n\t/*\n\t\tRead the metadata about the CSV file\n\t*/\n\tcsvReader, cvm, err := loader.ReadMetadata(dataFD, loaderFD, resp.DSV)\n\tif err != nil {\n\t\tlog.Error(\"Error: \", err.Error())\n\t\treturn fmt.Errorf(\"error: %w\", err)\n\t}\n\n\t/*\n\t\tRead the CSV data in chunks until the end of the file\n\t*/\n\tfor {\n\t\tchunkSize := 1000000\n\t\t// chunkSize := 100\n\n\t\tnpm, endReached, err := loader.CSVtoNumpyMulti(csvReader, *tbk, cvm, chunkSize, resp.RecordType == io.VARIABLE)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error: \", err.Error())\n\t\t\treturn fmt.Errorf(\"error: %w\", err)\n\t\t}\n\t\tif npm != nil { // npm will be empty if we've read the whole file in the last pass\n\t\t\t// LAL ================= DEBUG\n\t\t\t/*\n\t\t\t\t//fmt.Println(\"LAL: npm:\", npm)\n\t\t\t\tcsmT, err := npm.ToColumnSeriesMap()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"LAL Error: \", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfmt.Println(\"LAL: csm:\", csmT)\n\t\t\t\tfmt.Println(\"LAL: cs:\", csmT[tbk])\n\t\t\t*/\n\t\t\t// LAL ^^^^^^^^^^^^^^^^^^ DEBUG\n\n\t\t\terr = writeNumpy(c, npm, resp.RecordType == io.VARIABLE)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"Error: \", err.Error())\n\t\t\t\treturn fmt.Errorf(\"error: %w\", err)\n\t\t\t}\n\t\t\t// LAL ================= DEBUG\n\t\t\t/*\n\t\t\t\treturn\n\t\t\t*/\n\t\t\t// LAL ^^^^^^^^^^^^^^^^^^ DEBUG\n\t\t}\n\t\tif endReached {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.6516506", "0.6347956", "0.61831176", "0.5677068", "0.5658918", "0.5573051", "0.5475211", "0.5449381", "0.5438672", "0.54160637", "0.54029816", "0.53700936", "0.5336872", "0.5336363", "0.5317149", "0.53148144", "0.5312098", "0.52779335", "0.5253924", "0.523492", "0.5209779", "0.52026105", "0.5200005", "0.5196331", "0.51960444", "0.5192959", "0.5187873", "0.518482", "0.51743007", "0.5156137", "0.51543134", "0.5151723", "0.5147245", "0.5139636", "0.51186955", "0.5065695", "0.5064372", "0.5063172", "0.50582343", "0.5056276", "0.5044537", "0.50425893", "0.5032263", "0.5028322", "0.5015822", "0.501252", "0.5006568", "0.50010794", "0.5000725", "0.4994291", "0.49937266", "0.49831223", "0.49630255", "0.49579805", "0.49503243", "0.49477997", "0.49454728", "0.4932987", "0.4932878", "0.49179646", "0.49011558", "0.48897284", "0.48855886", "0.48821893", "0.48801088", "0.48684743", "0.4868414", "0.48682287", "0.48651227", "0.48650378", "0.48628917", "0.4860692", "0.48592684", "0.4858177", "0.48571277", "0.48518208", "0.48493144", "0.48468992", "0.48450407", "0.48211414", "0.48158133", "0.4811888", "0.480573", "0.47962943", "0.47913435", "0.47888255", "0.47855756", "0.478433", "0.4783045", "0.47820815", "0.47812107", "0.4778314", "0.47754", "0.4773829", "0.47678307", "0.476091", "0.47571453", "0.47555462", "0.47538224", "0.47509053" ]
0.65898174
0
Convert a data payload from the web handler into a ServiceEvent
func dataPayloadtoServiceEvent(dataPayload string) (ServiceEvent, error) { var newServiceEvent ServiceEvent var newEventDescription EventDescription var newEventDescriptionType EventType var vehicle Vehicle var garage Garage log.Print(string(newServiceEvent.Identifier) + string(newEventDescription.VehicleMilage) + string(newEventDescriptionType.EventId) + string(vehicle.V5c) + string(garage.GarageId)) return newServiceEvent, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func EventFromPayload(eventId int, data interface{}) *swf.HistoryEvent {\n\tevent := &swf.HistoryEvent{}\n\tevent.EventId = I(eventId)\n\tswitch t := data.(type) {\n\tcase *swf.ActivityTaskCancelRequestedEventAttributes:\n\t\tevent.ActivityTaskCancelRequestedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskCancelRequested)\n\tcase *swf.ActivityTaskCanceledEventAttributes:\n\t\tevent.ActivityTaskCanceledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskCanceled)\n\tcase *swf.ActivityTaskCompletedEventAttributes:\n\t\tevent.ActivityTaskCompletedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskCompleted)\n\tcase *swf.ActivityTaskFailedEventAttributes:\n\t\tevent.ActivityTaskFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskFailed)\n\tcase *swf.ActivityTaskScheduledEventAttributes:\n\t\tevent.ActivityTaskScheduledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskScheduled)\n\tcase *swf.ActivityTaskStartedEventAttributes:\n\t\tevent.ActivityTaskStartedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskStarted)\n\tcase *swf.ActivityTaskTimedOutEventAttributes:\n\t\tevent.ActivityTaskTimedOutEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeActivityTaskTimedOut)\n\tcase *swf.CancelTimerFailedEventAttributes:\n\t\tevent.CancelTimerFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeCancelTimerFailed)\n\tcase *swf.CancelWorkflowExecutionFailedEventAttributes:\n\t\tevent.CancelWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeCancelWorkflowExecutionFailed)\n\tcase *swf.ChildWorkflowExecutionCanceledEventAttributes:\n\t\tevent.ChildWorkflowExecutionCanceledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeChildWorkflowExecutionCanceled)\n\tcase *swf.ChildWorkflowExecutionCompletedEventAttributes:\n\t\tevent.ChildWorkflowExecutionCompletedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeChildWorkflowExecutionCompleted)\n\tcase *swf.ChildWorkflowExecutionFailedEventAttributes:\n\t\tevent.ChildWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeChildWorkflowExecutionFailed)\n\tcase *swf.ChildWorkflowExecutionStartedEventAttributes:\n\t\tevent.ChildWorkflowExecutionStartedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeChildWorkflowExecutionStarted)\n\tcase *swf.ChildWorkflowExecutionTerminatedEventAttributes:\n\t\tevent.ChildWorkflowExecutionTerminatedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeChildWorkflowExecutionTerminated)\n\tcase *swf.ChildWorkflowExecutionTimedOutEventAttributes:\n\t\tevent.ChildWorkflowExecutionTimedOutEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeChildWorkflowExecutionTimedOut)\n\tcase *swf.CompleteWorkflowExecutionFailedEventAttributes:\n\t\tevent.CompleteWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeCompleteWorkflowExecutionFailed)\n\tcase *swf.ContinueAsNewWorkflowExecutionFailedEventAttributes:\n\t\tevent.ContinueAsNewWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeContinueAsNewWorkflowExecutionFailed)\n\tcase *swf.DecisionTaskCompletedEventAttributes:\n\t\tevent.DecisionTaskCompletedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeDecisionTaskCompleted)\n\tcase *swf.DecisionTaskScheduledEventAttributes:\n\t\tevent.DecisionTaskScheduledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeDecisionTaskScheduled)\n\tcase *swf.DecisionTaskStartedEventAttributes:\n\t\tevent.DecisionTaskStartedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeDecisionTaskStarted)\n\tcase *swf.DecisionTaskTimedOutEventAttributes:\n\t\tevent.DecisionTaskTimedOutEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeDecisionTaskTimedOut)\n\tcase *swf.ExternalWorkflowExecutionCancelRequestedEventAttributes:\n\t\tevent.ExternalWorkflowExecutionCancelRequestedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeExternalWorkflowExecutionCancelRequested)\n\tcase *swf.ExternalWorkflowExecutionSignaledEventAttributes:\n\t\tevent.ExternalWorkflowExecutionSignaledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeExternalWorkflowExecutionSignaled)\n\tcase *swf.FailWorkflowExecutionFailedEventAttributes:\n\t\tevent.FailWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeFailWorkflowExecutionFailed)\n\tcase *swf.MarkerRecordedEventAttributes:\n\t\tevent.MarkerRecordedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeMarkerRecorded)\n\tcase *swf.RecordMarkerFailedEventAttributes:\n\t\tevent.RecordMarkerFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeRecordMarkerFailed)\n\tcase *swf.RequestCancelActivityTaskFailedEventAttributes:\n\t\tevent.RequestCancelActivityTaskFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeRequestCancelActivityTaskFailed)\n\tcase *swf.RequestCancelExternalWorkflowExecutionFailedEventAttributes:\n\t\tevent.RequestCancelExternalWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeRequestCancelExternalWorkflowExecutionFailed)\n\tcase *swf.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes:\n\t\tevent.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeRequestCancelExternalWorkflowExecutionInitiated)\n\tcase *swf.ScheduleActivityTaskFailedEventAttributes:\n\t\tevent.ScheduleActivityTaskFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeScheduleActivityTaskFailed)\n\tcase *swf.SignalExternalWorkflowExecutionFailedEventAttributes:\n\t\tevent.SignalExternalWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeSignalExternalWorkflowExecutionFailed)\n\tcase *swf.SignalExternalWorkflowExecutionInitiatedEventAttributes:\n\t\tevent.SignalExternalWorkflowExecutionInitiatedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeSignalExternalWorkflowExecutionInitiated)\n\tcase *swf.StartChildWorkflowExecutionFailedEventAttributes:\n\t\tevent.StartChildWorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeStartChildWorkflowExecutionFailed)\n\tcase *swf.StartChildWorkflowExecutionInitiatedEventAttributes:\n\t\tevent.StartChildWorkflowExecutionInitiatedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeStartChildWorkflowExecutionInitiated)\n\tcase *swf.StartTimerFailedEventAttributes:\n\t\tevent.StartTimerFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeStartTimerFailed)\n\tcase *swf.TimerCanceledEventAttributes:\n\t\tevent.TimerCanceledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeTimerCanceled)\n\tcase *swf.TimerFiredEventAttributes:\n\t\tevent.TimerFiredEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeTimerFired)\n\tcase *swf.TimerStartedEventAttributes:\n\t\tevent.TimerStartedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeTimerStarted)\n\tcase *swf.WorkflowExecutionCancelRequestedEventAttributes:\n\t\tevent.WorkflowExecutionCancelRequestedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionCancelRequested)\n\tcase *swf.WorkflowExecutionCanceledEventAttributes:\n\t\tevent.WorkflowExecutionCanceledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionCanceled)\n\tcase *swf.WorkflowExecutionCompletedEventAttributes:\n\t\tevent.WorkflowExecutionCompletedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionCompleted)\n\tcase *swf.WorkflowExecutionContinuedAsNewEventAttributes:\n\t\tevent.WorkflowExecutionContinuedAsNewEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionContinuedAsNew)\n\tcase *swf.WorkflowExecutionFailedEventAttributes:\n\t\tevent.WorkflowExecutionFailedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionFailed)\n\tcase *swf.WorkflowExecutionSignaledEventAttributes:\n\t\tevent.WorkflowExecutionSignaledEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionSignaled)\n\tcase *swf.WorkflowExecutionStartedEventAttributes:\n\t\tevent.WorkflowExecutionStartedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionStarted)\n\tcase *swf.WorkflowExecutionTerminatedEventAttributes:\n\t\tevent.WorkflowExecutionTerminatedEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionTerminated)\n\tcase *swf.WorkflowExecutionTimedOutEventAttributes:\n\t\tevent.WorkflowExecutionTimedOutEventAttributes = t\n\t\tevent.EventType = S(swf.EventTypeWorkflowExecutionTimedOut)\n\t}\n\treturn event\n}", "func main() {\n apex.HandleFunc(func(event json.RawMessage, ctx *apex.Context) (interface{}, error) {\n\n var m interface{}\n\n if err := json.Unmarshal(event, &m); err != nil {\n return nil, err\n }\n return &m, nil\n })\n}", "func (e *Event) Data(out interface{}) error {\n\treturn json.Unmarshal([]byte(e.data), out)\n}", "func (self *Server) RawEventToEvent(e) error {\n\n}", "func (b *Bot) parseData(data map[string]interface{}) *eventPayload {\n\treturn data[\"payload\"].(*eventPayload)\n}", "func (e *EventCollectorClient) Data(data interface{}) error {\n\tformattedEvent := map[string]interface{}{\"event\": data}\n\tb, err := json.Marshal(formattedEvent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the body to your jsonize'd map[string]interface{}\n\te.Request.Body = ioutil.NopCloser(strings.NewReader(string(b)))\n\treturn nil\n}", "func TestEventMarshaling(t *testing.T) {\n\tassert := asserts.NewTesting(t, asserts.FailStop)\n\n\tevtIn, err := mesh.NewEvent(\"test\")\n\tassert.NoError(err)\n\tdata, err := json.Marshal(evtIn)\n\tassert.NoError(err)\n\n\tevtOut := mesh.Event{}\n\terr = json.Unmarshal(data, &evtOut)\n\tassert.NoError(err)\n\tassert.Equal(evtOut, evtIn)\n\n\tplEvtA, err := mesh.NewEvent(\"payload-a\")\n\tassert.NoError(err)\n\tplEvtB, err := mesh.NewEvent(\"payload-b\")\n\tassert.NoError(err)\n\tplEvtC, err := mesh.NewEvent(\"payload-c\")\n\tassert.NoError(err)\n\n\tevtIn, err = mesh.NewEvent(\"test\", plEvtA, plEvtB, plEvtC)\n\tassert.NoError(err)\n\tdata, err = json.Marshal(evtIn)\n\tassert.NoError(err)\n\n\tevtOut = mesh.Event{}\n\terr = json.Unmarshal(data, &evtOut)\n\tassert.NoError(err)\n\tassert.Equal(evtOut, evtIn)\n\tpl := []mesh.Event{}\n\terr = evtOut.Payload(&pl)\n\tassert.NoError(err)\n\tassert.Equal(pl[0], plEvtA)\n\tassert.Equal(pl[1], plEvtB)\n\tassert.Equal(pl[2], plEvtC)\n}", "func UnmarshalEvent(data []byte) (Event, error) {\n\t//first we extract the generic part\n\taux := struct {\n\t\tStreamTCStr string `json:\"stream-timecode\"`\n\t\tRecTCStr string `json:\"rec-timecode\"`\n\t\tUpdateType string `json:\"update-type\"`\n\t}{}\n\n\tif err := json.Unmarshal(data, &aux); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(aux.UpdateType) == 0 {\n\t\treturn nil, ErrNotEventMessage{}\n\t}\n\trawE := &rawEvent{\n\t\teventType: aux.UpdateType,\n\t\trecTC: -1,\n\t\tstreamTC: -1,\n\t}\n\n\tif len(aux.StreamTCStr) > 0 {\n\t\tvar err error\n\t\trawE.streamTC, err = parseTC(aux.StreamTCStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(aux.RecTCStr) > 0 {\n\t\tvar err error\n\t\trawE.recTC, err = parseTC(aux.RecTCStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// now we extract the generic part\n\tevType, ok := eventFactory[rawE.UpdateType()]\n\tif ok == false {\n\t\treturn nil, ErrUnknownEventType{rawE.UpdateType()}\n\t}\n\n\tevInst := reflect.New(evType)\n\tev := evInst.Interface().(Event)\n\n\terr := json.Unmarshal(data, &ev)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// copy back initial data\n\tev.copyFromOther(rawE)\n\treturn ev, nil\n}", "func (e *Event) Data() map[string]interface{} {\n\tif e.data == nil {\n\t\terr := json.Unmarshal(e.encoded, &e.data)\n\t\tif err != nil {\n\t\t\te.data = make(map[string]interface{})\n\t\t\te.data[\"message\"] = err.Error()\n\t\t\te.data[\"@timestamp\"] = Timestamp(time.Now())\n\t\t\te.data[\"@metadata\"] = Metadata{}\n\t\t\te.data[\"tags\"] = Tags{\"_unmarshal_failure\"}\n\t\t} else {\n\t\t\te.convertData()\n\t\t}\n\t}\n\treturn e.data\n}", "func (rc *Router) handleEvent(request *http.Request) ([]byte, []byte, error) {\n\tvar err error\n\tvar response []byte\n\tvar data []byte\n\tbody, err := getRequestBody(request)\n\tif err != nil {\n\t\treturn data, response, errors.Wrap(err, \"failed to fetch request body\")\n\t}\n\n\teventsAPIEvent, err := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionVerifyToken(&slackevents.TokenComparator{VerificationToken: rc.token}))\n\tif err != nil {\n\t\treturn data, response, errors.Wrap(err, \"failed to extract event\")\n\t}\n\n\tif eventsAPIEvent.Type == slackevents.URLVerification {\n\t\tvar r *slackevents.ChallengeResponse\n\t\terr = json.Unmarshal(body, &r)\n\t\tif err != nil {\n\t\t\treturn data, response, errors.Wrap(err, \"failed to verify the challenge\")\n\t\t}\n\t\tresponse = []byte(r.Challenge)\n\t}\n\n\tif eventsAPIEvent.Type == slackevents.CallbackEvent {\n\t\tdata, err = json.Marshal(&eventsAPIEvent.InnerEvent)\n\t\tif err != nil {\n\t\t\treturn data, response, errors.Wrap(err, \"failed to marshal event data, rejecting the event...\")\n\t\t}\n\t}\n\n\treturn data, response, nil\n}", "func eventHandler(ctx context.Context, client ce.Client) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodPost {\n\t\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\t// TODO (@mgasch): support inbound rate limiting\n\n\t\tlog := logger.Get(ctx)\n\t\tb, err := io.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.Error(\"read body\", zap.Error(err))\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tvar event model.Payload\n\t\tif err = json.Unmarshal(b, &event); err != nil {\n\t\t\tlog.Error(\"could not decode harbor notification event\", zap.Error(err))\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tid := uuid.New().String()\n\t\tlog = log.With(zap.String(\"eventID\", id))\n\n\t\tlog.Debug(\"received request\", zap.String(\"request\", string(b)))\n\n\t\te := ce.NewEvent()\n\t\te.SetID(id)\n\t\te.SetSource(fmt.Sprintf(sourceFormat, os.Getenv(\"K_SERVICE\")))\n\t\te.SetSubject(event.Operator) // might be empty\n\n\t\t// sanity check\n\t\tif event.Type == \"\" {\n\t\t\tlog.Error(\"harbor event type must not be empty\", zap.String(\"type\", event.Type))\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tt := strings.ToLower(event.Type)\n\t\te.SetType(fmt.Sprintf(eventTypeFormat, t))\n\n\t\tts := time.Unix(event.OccurAt, 0)\n\t\te.SetTime(ts)\n\n\t\tif err = e.SetData(ce.ApplicationJSON, event); err != nil {\n\t\t\tlog.Error(\"could not set cloudevent data\", zap.Error(err))\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tctx = cectx.WithRetriesExponentialBackoff(ctx, retryDelay, retries)\n\t\tif err = client.Send(ctx, e); ce.IsUndelivered(err) || ce.IsNACK(err) {\n\t\t\tlog.Error(\"could not send cloudevent\", zap.Error(err), zap.String(\"event\", e.String()))\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debug(\"successfully sent cloudevent\", zap.Any(\"event\", e))\n\t})\n}", "func processEvent(w http.ResponseWriter, r *http.Request) {\n\n root, output, filename, err := processAndLogRequest(eventsPath, w, r)\n defer output.Close()\n\n if err != nil {\n log.Panicln(err)\n return\n }\n\n // read the event type from the XML body // /Envelope/soap:Body/AFEEvent/event:Event\n eventType := \"\"\n if node := xmlquery.FindOne(root, \"//event:Event\"); node != nil {\n eventType = node.InnerText()\n }\n\n // pull out AFE's DocumentID\n docID := \"\"\n if node := xmlquery.FindOne(root, \"//event:AFE/afe:DocumentID\"); node != nil {\n docID = node.InnerText()\n }\n\n log.Printf(\"Event[%v on %v] - (%v %v // Action=%v) >> %v\\n\", eventType, docID, r.Method, r.URL.EscapedPath(), r.Header[\"Soapaction\"][0], filename)\n\n writeEmptySoapBody(output)\n}", "func (e *Event) convertData() {\n\t// Normalize \"tags\" first (other resolutions ignore it)\n\tif entry, ok := e.data[\"tags\"]; ok {\n\t\tswitch value := entry.(type) {\n\t\tcase Tags:\n\t\tcase string:\n\t\t\te.data[\"tags\"] = Tags{value}\n\t\tcase []interface{}:\n\t\t\t// From unmarshaled over the wire we get []interface{}\n\t\t\ttags := Tags{}\n\t\t\tfor _, tag := range value {\n\t\t\t\ttagString, ok := tag.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\ttags = Tags{\"_tags_parse_failure\"}\n\t\t\t\t\te.data[\"tags_parse_error\"] = fmt.Sprintf(\"tags list must contain only strings, found a %T\", tag)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttags = append(tags, tagString)\n\t\t\t}\n\t\t\te.data[\"tags\"] = tags\n\t\tdefault:\n\t\t\te.data[\"tags\"] = Tags{\"_tags_parse_failure\"}\n\t\t\te.data[\"tags_parse_error\"] = fmt.Sprintf(\"tags was not a string or string list, was %T\", value)\n\t\t}\n\t} else {\n\t\te.data[\"tags\"] = Tags{}\n\t}\n\t// Normalize \"@timestamp\" to a time.Time\n\tif entry, ok := e.data[\"@timestamp\"]; ok {\n\t\tswitch value := entry.(type) {\n\t\tcase Timestamp:\n\t\tcase time.Time:\n\t\t\te.data[\"@timestamp\"] = Timestamp(value)\n\t\tcase string:\n\t\t\tparsed, err := time.Parse(time.RFC3339, value)\n\t\t\tif err != nil {\n\t\t\t\te.data[\"@timestamp\"] = Timestamp(time.Now())\n\t\t\t\te.data[\"timestamp_parse_error\"] = err\n\t\t\t\te.AddTag(\"_timestamp_parse_failure\")\n\t\t\t} else {\n\t\t\t\te.data[\"@timestamp\"] = Timestamp(parsed)\n\t\t\t}\n\t\tdefault:\n\t\t\te.data[\"@timestamp\"] = Timestamp(time.Now())\n\t\t\te.data[\"timestamp_parse_error\"] = fmt.Sprintf(\"@timestamp was not a string, was %T\", value)\n\t\t\te.AddTag(\"_timestamp_parse_failure\")\n\t\t}\n\t} else {\n\t\te.data[\"@timestamp\"] = Timestamp(time.Now())\n\t}\n\t// Normalize \"@metadata\"\n\te.data[\"@metadata\"] = Metadata{}\n}", "func EventHandler(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\tvar remote string\n\tif tmp := r.Header.Get(\"X-Forwarded-For\"); tmp != \"\" {\n\t\tremote = tmp\n\t} else {\n\t\tremote = r.RemoteAddr\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"module\": \"adwo\",\n\t}).Debugln(\"Incomming event from:\", remote, \"With Header:\", r.Header)\n\tlog.WithFields(logrus.Fields{\n\t\t\"module\": \"adwo\",\n\t}).Debugln(\"Request params:\", r.Form)\n\t// required fields\n\tif len(r.Form[\"appid\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No appid\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"adname\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No adname\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"adid\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No adid\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"device\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No device\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"idfa\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No idfa\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"point\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No point\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"ts\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No ts\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"sign\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No sign\", 400)\n\t\treturn\n\t}\n\tif len(r.Form[\"keyword\"]) < 1 {\n\t\tErrorAndReturnCode(w, \"Missing Required field: No keyword\", 400)\n\t\treturn\n\t}\n\t// set a new avro record\n\tstr := fmt.Sprintf(\"adid=%sadname=%sappid=%sdevice=%sidfa=%spoint=%sts=%skey=%s\", r.Form[\"adid\"][0], r.Form[\"adname\"][0], r.Form[\"appid\"][0], r.Form[\"device\"][0], r.Form[\"idfa\"][0], r.Form[\"point\"][0], r.Form[\"ts\"][0], conf.Extension.Anwo.Key)\n\tcrypted := md5.Sum([]byte(str))\n\tif fmt.Sprintf(\"%x\", crypted) != strings.Split(r.Form[\"sign\"][0], \",\")[0] {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"module\": \"adwo\",\n\t\t}).Warnf(\"Sign not matched!: %x :%s\\n, bypass sign check? %s\", crypted, r.Form[\"sign\"][0], *sign_check)\n\t\tif !*sign_check {\n\t\t\tErrorAndReturnCode(w, \"Sign mismatched!\", 400)\n\t\t\treturn\n\t\t}\n\t}\n\trecord, err := avro.NewRecord()\n\tif err != nil {\n\t\tErrorAndReturnCode(w, \"Failed to set a new avro record:\"+err.Error(), 500)\n\t\treturn\n\t}\n\t// optional fields\n\tif len(r.Form[\"ip\"]) > 0 {\n\t\trecord.Set(\"ip\", r.Form[\"ip\"][0])\n\t}\n\t// set required fields\n\trecord.Set(\"did\", r.Form[\"idfa\"][0])\n\tnsec, err := strconv.ParseInt(r.Form[\"ts\"][0], 10, 64)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"module\": \"adwo\",\n\t\t}).Errorln(\"Failed to parse ts to int:\", err)\n\t\tErrorAndReturnCode(w, \"Failed to parse ts:\"+err.Error(), 500)\n\t\treturn\n\t}\n\tt := time.Unix(0, nsec*1000000)\n\trecord.Set(\"timestamp\", t.Format(time.RFC3339))\n\trecord.Set(\"id\", r.Form[\"keyword\"][0])\n\trecord.Set(\"event\", \"anwo_postback\")\n\trecord.Set(\"os\", \"ios\")\n\t// extensions fields\n\textension := map[string](interface{}){}\n\tfor k, v := range r.Form {\n\t\tif k != \"ip\" && k != \"aid\" && k != \"idfa\" && k != \"timestamp\" && k != \"keyword\" && k != \"sign\" && k != \"ts\" {\n\t\t\textension[k] = v[0]\n\t\t}\n\t}\n\tif len(extension) != 0 {\n\t\trecord.Set(\"extension\", extension)\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"module\": \"adwo\",\n\t\t\"record\": record.String(),\n\t}).Infoln(\"Recieved post back.\")\n\t// encode avro\n\tbuf := new(bytes.Buffer)\n\tif err = avro.Encode(buf, record); err != nil {\n\t\tErrorAndReturnCode(w, \"Failed to encode avro record:\"+err.Error(), 500)\n\t\treturn\n\t}\n\turl := fmt.Sprintf(\"%s?params=%s\", conf.Extension.Anwo.Td_postback_url, r.Form[\"keyword\"][0])\n\tgo func(url string) {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"module\": \"adwo\",\n\t\t\t\"url\": url,\n\t\t}).Infoln(\"Send postback to adserver with request url.\")\n\n\t\trequest, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"module\": \"adwo\",\n\t\t\t}).Errorln(\"Failed to create request:\", err)\n\t\t\treturn\n\t\t}\n\t\trequest.Header.Add(\"Connection\", \"keep-alive\")\n\t\tresp, err := client.Do(request)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"module\": \"adwo\",\n\t\t\t}).Errorln(\"Failed to send clk to remote server:\", err)\n\t\t\treturn\n\t\t}\n\t\tif resp.StatusCode != 200 {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"module\": \"adwo\",\n\t\t\t}).Errorln(\"Error when send td_postback:\", resp.Status)\n\t\t\tstr, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"module\": \"adwo\",\n\t\t\t}).Debugln(\"Resp body:\", string(str))\n\t\t\tresp.Body.Close()\n\t\t\treturn\n\t\t}\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t\tresp.Body.Close()\n\t}(url)\n\n\t// send to kafka\n\tpart, offset, err := kafka.SendByteMessage(buf.Bytes(), \"default\")\n\tif err != nil {\n\t\tfail_safe.Println(\"error:\", err)\n\t\tfail_safe.Println(\"record:\", record)\n\t\tfail_safe.Println(\"data:\", buf.Bytes())\n\t\tErrorAndReturnCode(w, \"Failed to send message to kafka:\"+err.Error()+\"Data has been writen to a backup file. Please contact us.\", 200)\n\t\treturn\n\t}\n\t// done\n\tlog.WithFields(logrus.Fields{\n\t\t\"module\": \"adwo\",\n\t}).Debugf(\"New record partition=%d\\toffset=%d\\n\", part, offset)\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, \"1 messages have been writen.\")\n}", "func (a Application) Handler(event json.RawMessage, ctx *apex.Context) (interface{}, error) {\n\tlog.Println(string(event))\n\treq, err := ParseRequest(a.ID, bytes.NewReader(event))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := NewResponse()\n\n\tswitch req.Type() {\n\tcase \"LaunchRequest\":\n\t\tif a.LaunchHandler != nil {\n\t\t\ta.LaunchHandler(req, res)\n\t\t}\n\tcase \"IntentRequest\":\n\t\tif a.IntentHandler != nil {\n\t\t\ta.IntentHandler(req, res)\n\t\t}\n\tcase \"SessionEndedRequest\":\n\t\tif a.SessionEndedHandler != nil {\n\t\t\ta.SessionEndedHandler(req, res)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"invalid request type\")\n\t}\n\n\treturn res, nil\n}", "func (event Event) CreateEvent(data [][]byte) []domain.Event {\n\tvar events []domain.Event\n\tfor _, item := range data {\n\t\tvar event domain.Event\n\t\tjson.Unmarshal(item, &event)\n\t\tevents = append(events, event)\n\t}\n\treturn events\n}", "func parseWebhook(r *http.Request) (payload interface{}, err error) {\n\teventType := r.Header.Get(EventTypeHeader)\n\tswitch eventType {\n\tcase PostCommitEvent:\n\t\tpayload = &PostCommit{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"event type %v not support\", eventType)\n\t}\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fail to read request body\")\n\t}\n\n\tif err := json.Unmarshal(body, &payload); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn payload, nil\n}", "func Handler(rw http.ResponseWriter, req *http.Request) {\n\tshkeptncontext := \"\"\n\tlogger := keptnutils.NewLogger(shkeptncontext, \"\", \"alertmanager-service\")\n\tlogger.Debug(\"receiving event from prometheus alertmanager\")\n\n\tdecoder := json.NewDecoder(req.Body)\n\tvar event alertManagerEvent\n\terr := decoder.Decode(&event)\n\tif err != nil {\n\t\tlogger.Error(\"Could not map received event to datastructure: \" + err.Error())\n\t}\n\n\tproblemState := \"\"\n\tif event.Status == \"firing\" {\n\t\tproblemState = \"OPEN\"\n\t}\n\n\tnewProblemData := keptnevents.ProblemEventData{\n\t\tState: problemState,\n\t\tProblemID: \"\",\n\t\tProblemTitle: event.Alerts[0].Annotations.Summary,\n\t\tProblemDetails: event.Alerts[0].Annotations.Description,\n\t\tImpactedEntity: event.Alerts[0].Labels.PodName,\n\t}\n\n\tlogger.Debug(\"sending event to eventbroker\")\n\terr = createAndSendCE(shkeptncontext, newProblemData)\n\tif err != nil {\n\t\tlogger.Error(\"could not send cloud event: \" + err.Error())\n\t\trw.WriteHeader(500)\n\t} else {\n\t\tlogger.Debug(\"event successfully dispatched to eventbroker\")\n\t\trw.WriteHeader(201)\n\t}\n\n}", "func (e DomainEvent) Payload() interface{} {\n\treturn e.payload\n}", "func eventsHandler(stream store.Stream) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Check authentication by asking the caller to use notification client_id/client_secret pair as basic auth.\n\t\tif !checkBasicAuth(w, r) {\n\t\t\treturn\n\t\t}\n\t\t// Validate request and get event.\n\t\terr := service.ValidatePost(w, r)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tevent := new(Event)\n\t\terr = service.ValidateJson(w, r, event)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t// Validate provided data.\n\t\tif event.User == nil {\n\t\t\thttp.Error(w, \"Missing 'user' relationship\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// TODO authorize request.\n\n\t\tvalue := map[string]interface{}{\n\t\t\t\"name\": event.Name,\n\t\t\t\"source\": event.Source,\n\t\t\t\"user\": event.User.Id,\n\t\t\t\"time\": event.Time.String(),\n\t\t\t\"code\": event.Code,\n\t\t}\n\n\t\tif event.Transfer != nil {\n\t\t\tvalue[\"transfer\"] = event.Transfer.Href\n\t\t}\n\n\t\t// Enqueue event to the stream.\n\t\tid, err := stream.Add(r.Context(), value)\n\t\tif err != nil {\n\t\t\t// Unexpected error\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t\t// Return success following JSON:API spec https://jsonapi.org/format/#crud-creating-responses.\n\t\tw.Header().Set(service.ContentType, jsonapi.MediaType)\n\t\tw.WriteHeader(http.StatusCreated)\n\t\t// Not adding Location header since events are not accessible (by the moment).\n\t\t// Send response, which is the same as the request but with the id.\n\t\tevent.Id = id\n\t\terr = jsonapi.MarshalPayload(w, event)\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\tlog.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n}", "func TestEventService(t *testing.T) {\n\tvar result EventService\n\terr := json.NewDecoder(strings.NewReader(eventServiceBody)).Decode(&result)\n\n\tif err != nil {\n\t\tt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\tif result.ID != \"EventService\" {\n\t\tt.Errorf(\"Received invalid ID: %s\", result.ID)\n\t}\n\n\tif result.Name != \"Event Service\" {\n\t\tt.Errorf(\"Received invalid name: %s\", result.Name)\n\t}\n\n\tif result.DeliveryRetryAttempts != 4 {\n\t\tt.Errorf(\"Expected 4 retry attempts, got: %d\", result.DeliveryRetryAttempts)\n\t}\n\n\tif result.DeliveryRetryIntervalSeconds != 30 {\n\t\tt.Errorf(\"Expected 30 second retry interval, got: %d\", result.DeliveryRetryIntervalSeconds)\n\t}\n\n\tif result.SSEFilterPropertiesSupported.MetricReportDefinition {\n\t\tt.Error(\"MetricReportDefinition filter should be false\")\n\t}\n\n\tif !result.SSEFilterPropertiesSupported.MessageID {\n\t\tt.Error(\"Message ID filter should be true\")\n\t}\n\n\tif result.submitTestEventTarget != \"/redfish/v1/EventService/Actions/EventService.SubmitTestEvent\" {\n\t\tt.Errorf(\"Invalid SubmitTestEvent target: %s\", result.submitTestEventTarget)\n\t}\n\n\tfor _, et := range result.EventTypesForSubscription {\n\t\tif !et.IsValidEventType() {\n\t\t\tt.Errorf(\"invalid event type: %s\", et)\n\t\t}\n\t}\n\n}", "func (c *Client) handleEvent(m map[string]interface{}) {\n\tt := m[\"update-type\"].(string)\n\n\tswitch t {\n\tcase \"Heartbeat\":\n\n\t\tbreak\n\tcase \"SceneItemTransformChanged\":\n\n\t\tbreak\n\tcase \"MediaRestarted\":\n\n\t\tbreak\n\tcase \"MediaStarted\":\n\n\t\tbreak\n\tcase \"SceneItemVisibilityChanged\":\n\n\t\tbreak\n\tcase \"MediaEnded\":\n\n\t\tbreak\n\tcase \"SourceDestroyed\":\n\n\t\tbreak\n\tcase \"SceneItemSelected\":\n\n\t\tbreak\n\tcase \"SceneItemRemoved\":\n\n\t\tbreak\n\tcase \"SceneItemDeselected\":\n\n\t\tbreak\n\tdefault:\n\t\tglobal.LOG.Info(\"data\", zap.Any(\"m\", m))\n\t\tbreak\n\t}\n}", "func transformHttpStartStopEvent(cfEvent *events.Envelope, nrEvent map[string]interface{}) {\n\t// event: origin:\"gorouter\" eventType:HttpStartStop timestamp:1497038373295178447 deployment:\"cf\" job:\"router\" index:\"1276dbaa-f5a4-4c48-bcbe-d06ff0dba58d\" ip:\"192.168.16.16\" httpStartStop:<startTimestamp:1497038373206213992 stopTimestamp:1497038373295152451 requestId:<low:7513566559519661218 high:8828490834936076361 > peerType:Client method:GET uri:\"http://api.sys.pie-22.cfplatformeng.com/v2/syslog_drain_urls\" remoteAddress:\"130.211.2.63:61939\" userAgent:\"Go-http-client/1.1\" statusCode:200 contentLength:42 instanceId:\"89a53ed9-cf20-404b-5728-33a19c1e13ef\" forwarded:\"104.197.98.14\" forwarded:\"35.186.215.103\" forwarded:\"130.211.2.63\" >\n\thttpEvent := cfEvent.HttpStartStop\n\tprefix := \"http\"\n\tstart := time.Unix(0, httpEvent.GetStartTimestamp())\n\tend := time.Unix(0, httpEvent.GetStopTimestamp())\n\tduration := float64(end.Sub(start)) / float64(time.Millisecond)\n\tnrEvent[prefix+\"StartTimestamp\"] = start\n\tnrEvent[prefix+\"StopTimestamp\"] = end\n\tnrEvent[prefix+\"DurationMs\"] = duration\n\tif httpEvent.RequestId != nil {\n\t\tnrEvent[prefix+\"RequestId\"] = httpEvent.GetRequestId().String()\n\t}\n\tif httpEvent.PeerType != nil {\n\t\tnrEvent[prefix+\"PeerType\"] = httpEvent.GetPeerType().String()\n\t}\n\tif httpEvent.Method != nil {\n\t\tnrEvent[prefix+\"Method\"] = httpEvent.GetMethod().String()\n\t}\n\tif httpEvent.Uri != nil {\n\t\tnrEvent[prefix+\"Uri\"] = httpEvent.GetUri()\n\t}\n\tif httpEvent.RemoteAddress != nil {\n\t\tnrEvent[prefix+\"RemoteAddress\"] = httpEvent.GetRemoteAddress()\n\t}\n\tif httpEvent.UserAgent != nil {\n\t\tnrEvent[prefix+\"UserAgent\"] = httpEvent.GetUserAgent()\n\t}\n\tif httpEvent.StatusCode != nil {\n\t\tnrEvent[prefix+\"StatusCode\"] = httpEvent.GetStatusCode()\n\t}\n\tif httpEvent.ContentLength != nil {\n\t\tnrEvent[prefix+\"ContentLength\"] = httpEvent.GetContentLength()\n\t}\n\tif httpEvent.ApplicationId != nil {\n\t\tnrEvent[prefix+\"ApplicationId\"] = httpEvent.GetApplicationId()\n\t}\n\tif httpEvent.InstanceIndex != nil {\n\t\tnrEvent[prefix+\"InstanceIndex\"] = httpEvent.GetInstanceIndex()\n\t}\n\tif httpEvent.InstanceId != nil {\n\t\tnrEvent[prefix+\"InstanceId\"] = httpEvent.GetInstanceId()\n\t}\n\tfor i, forwardedIp := range httpEvent.Forwarded {\n\t\tindex := strconv.Itoa(i)\n\t\tnrEvent[prefix+\"Forwarded\"+index] = forwardedIp\n\t}\n}", "func (pe *ProwJobEvent) FromPayload(data []byte) error {\n\tif err := json.Unmarshal(data, pe); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func FromRawPayload(data []byte, topic, pubsub string) map[string]interface{} {\n\t// Limitations of generating the CloudEvent on the subscriber side based on raw payload:\n\t// - The CloudEvent ID will be random, so the same message can be redelivered as a different ID.\n\t// - TraceID is not useful since it is random and not from publisher side.\n\t// - Data is always returned as `data_base64` since we don't know the actual content type.\n\treturn map[string]interface{}{\n\t\tIDField: uuid.New().String(),\n\t\tSpecVersionField: CloudEventsSpecVersion,\n\t\tDataContentTypeField: \"application/octet-stream\",\n\t\tSourceField: DefaultCloudEventSource,\n\t\tTypeField: DefaultCloudEventType,\n\t\tTopicField: topic,\n\t\tPubsubField: pubsub,\n\t\tDataBase64Field: base64.StdEncoding.EncodeToString(data),\n\t}\n}", "func (s service) Create(ctx context.Context, email, component, environment, message string, data map[string]string) (*models.Event, error) {\n\tval, _ := json.Marshal(data)\n\te := &models.Event{\n\t\tEmail: email,\n\t\tComponent: component,\n\t\tEnvironment: environment,\n\t\tMessage: message,\n\t\tData: datatypes.JSON([]byte(val)),\n\t}\n\tevent, err := e.Create(s.DB)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\teventType := r.Header.Get(gitHubEventHeader)\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed to read the request body: %s\", err.Error())\n\t\thttp.Error(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\th, ok := eventHandlerMap[eventType]\n\n\tif !ok {\n\t\tlog.Printf(\"failed to handle event %s\\n\", eventType)\n\t\tw.Header().Set(\"Content-Type\", r.Header.Get(\"Content-Type\"))\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tlog.Printf(\"handling event %s\\n\", eventType)\n\tnewBody, err := h(r, body)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"failed handling the event: %s\", err.Error())\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif len(newBody) > 0 {\n\t\tw.Header().Set(\"Content-Type\", r.Header.Get(\"Content-Type\"))\n\t\tw.Write(newBody)\n\t\treturn\n\t}\n\n\thttp.Error(w, \"failed interception\", http.StatusPreconditionFailed)\n}", "func eventHandler(w http.ResponseWriter, r *http.Request) {\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Unable to read body\"))\n\t\treturn\n\t}\n\n\treq := &event{} // the req is used to fetch data from the json that comes with the post request\n\tif err = json.Unmarshal(body, req); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Unable to unmarshal JSON request\"))\n\t\treturn\n\t}\n\t// mappedData as defined in line 63 is the Data struct that will be printed for each stage of its construction\n\tmappedData.WebsiteUrl = req.WebsiteUrl\n\tmappedData.SessionId = req.Session\n\t// maping json requests depending on the EventType (screenResize,timeTaken,copyAndPaste)\n\tswitch event := req.EventType; event {\n\n\tcase \"screenResize\" :\n\t\tmappedData.ResizeFrom = req.ODimension\t\n\t\tmappedData.ResizeTo = req.NDimension\n\t\tlog.Printf(\"\\nEvent : screenResize , Current state of the data : \") \n\t\tfmt.Println(\"WebsiteUrl : \" , mappedData.WebsiteUrl) \n\t\tfmt.Println(\"SessionId : \" , mappedData.SessionId) \n\t\tfmt.Println(\"ResizeFrom : {Width , Height} = \" , mappedData.ResizeFrom) \n\t\tfmt.Println(\"ResizeTo : {Width , Height} = \" , mappedData.ResizeTo) \n\n\tcase \"timeTaken\": \n\t\tmappedData.FormCompletionTime = req.Time\n\t\tmappedData.ResizeFrom = req.ODimension\t\n\t\tmappedData.ResizeTo = req.NDimension\n\t\tlog.Printf(\"\\nEvent : Form submitted , Final state of the data : %+v\", mappedData)\n\tcase \"copyAndPaste\":\n\t\tmappedData.CopyAndPaste[req.FormId] = req.Copie || req.Paste\n\t\tlog.Printf(\"Event : Copy and Paste detected , Current state of the data : \")\n\t\tfmt.Println(\"WebsiteUrl : \" + mappedData.WebsiteUrl) \n\t\tfmt.Println(\"SessionId : \" + mappedData.SessionId) \n\t\tfmt.Println(\"CopyAndPaste : \" , mappedData.CopyAndPaste )\t\t\n\n\t}\n\tw.WriteHeader(http.StatusOK)\n \n\n}", "func EventToInput(e interface{}) (sarah.Input, error) {\n\tswitch typed := e.(type) {\n\tcase *event.Message:\n\t\treturn &Input{\n\t\t\tEvent: e,\n\t\t\tsenderKey: fmt.Sprintf(\"%s|%s\", typed.ChannelID.String(), typed.UserID.String()),\n\t\t\ttext: typed.Text,\n\t\t\ttimestamp: typed.TimeStamp,\n\t\t\tthreadTimeStamp: typed.ThreadTimeStamp,\n\t\t\tchannelID: typed.ChannelID,\n\t\t}, nil\n\n\tcase *event.ChannelMessage:\n\t\treturn &Input{\n\t\t\tEvent: e,\n\t\t\tsenderKey: fmt.Sprintf(\"%s|%s\", typed.ChannelID.String(), typed.UserID.String()),\n\t\t\ttext: typed.Text,\n\t\t\ttimestamp: typed.TimeStamp,\n\t\t\tthreadTimeStamp: typed.ThreadTimeStamp,\n\t\t\tchannelID: typed.ChannelID,\n\t\t}, nil\n\n\tdefault:\n\t\treturn nil, ErrNonSupportedEvent\n\t}\n}", "func DecodePayload(evtID EventType, payload []byte) (interface{}, error) {\n\tt, ok := EvtDataMap[evtID]\n\n\tif !ok {\n\t\tif _, ok := EventsToStringMap[evtID]; ok {\n\t\t\t// valid event\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, &UnknownEventError{Evt: evtID}\n\t}\n\n\tif t == nil {\n\t\treturn nil, nil\n\t}\n\n\tclone := reflect.New(reflect.TypeOf(t)).Interface()\n\terr := msgpack.Unmarshal(payload, clone)\n\treturn clone, err\n}", "func (m *EventLog) Payload() map[string]interface{} {\n\treturn m.MapPayload(m)\n}", "func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\n\tbodyEvent := MyEvent{}\n\n\t// Unmarshal the json, return 404 if error\n\terr := json.Unmarshal([]byte(request.Body), &bodyEvent)\n\tif err != nil {\n\t\tlog.Println(\"Failed run: \", err)\n\t\treturn events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, nil\n\t}\n\n\t// stdout and stderr are sent to AWS CloudWatch Logs\n\tlog.Printf(\"Processing Lambda request %s\\n\", bodyEvent.User)\n\n\tvar result string\n\tfor _, v := range bodyEvent.Message {\n\t\tresult = string(v) + result\n\t}\n\n\tresponse := map[string]string{\"message\": \"Hello \" + bodyEvent.User + \", \" + result}\n\n\t//marshall output\n\tjsonString, err := json.Marshal(response)\n\tif err != nil {\n\t\tlog.Printf(\"error: %s \\n\", err)\n\t\treturn events.APIGatewayProxyResponse{}, ErrJsonEncode\n\t}\n\n\treturn events.APIGatewayProxyResponse{\n\t\tBody: string(jsonString),\n\t\tStatusCode: 200,\n\t}, nil\n\n}", "func handleEvent(w http.ResponseWriter, r *http.Request) {\n\tev := &Event{}\n\n\t// get writekey, timestamp, and sample rate out of HTTP headers\n\tif err := getHeaders(r, ev); err != nil {\n\t\tuserFacingErr(r.Context(), err, apierrParseFailure, w)\n\t\treturn\n\t}\n\n\t// authenticate writekey or return 401\n\tteam, err := validateWritekey(r.Context(), ev.WriteKey)\n\tif err != nil {\n\t\tuserFacingErr(r.Context(), err, apierrAuthFailure, w)\n\t\treturn\n\t}\n\tbeeline.AddField(r.Context(), \"team\", team)\n\n\t// use the dataset name to get back a dataset object\n\tvars := mux.Vars(r)\n\tdatasetName := vars[\"datasetName\"]\n\tdataset, err := resolveDataset(r.Context(), datasetName)\n\tif err != nil {\n\t\tuserFacingErr(r.Context(), err, apierrDatasetLookupFailure, w)\n\t\treturn\n\t}\n\tbeeline.AddField(r.Context(), \"dataset\", dataset)\n\n\t// parse JSON body\n\terr = unmarshal(r, ev)\n\tif err != nil {\n\t\tuserFacingErr(r.Context(), err, apierrJSONFailure, w)\n\t\treturn\n\t}\n\tbeeline.AddField(r.Context(), \"event_columns\", len(ev.Data))\n\n\t// get partition info - stub out\n\tpartition, err := getPartition(r.Context(), dataset)\n\tif err != nil {\n\t\tuserFacingErr(r.Context(), err, apierrDatasetLookupFailure, w)\n\t\treturn\n\t}\n\tev.ChosenPartition = partition\n\tbeeline.AddField(r.Context(), \"chosen_partition\", partition)\n\n\t// check time - use or set to now if broken\n\tif ev.Timestamp.IsZero() {\n\t\tev.Timestamp = time.Now()\n\t} else {\n\t\t// record the difference between the event's timestamp and now to help identify lagging events\n\t\teventTimeDelta := float64(time.Since(ev.Timestamp)) / float64(time.Second)\n\t\tbeeline.AddField(r.Context(), \"event_time_delta_sec\", eventTimeDelta)\n\t}\n\tbeeline.AddField(r.Context(), \"event_time\", ev.Timestamp)\n\n\t// verify schema - stub out\n\terr = getSchema(r.Context(), dataset)\n\tif err != nil {\n\t\tuserFacingErr(r.Context(), err, apierrSchemaLookupFailure, w)\n\t\treturn\n\t}\n\n\t// ok, everything checks out. Hand off to external service (aka write to\n\t// local disk)\n\twriteEvent(r.Context(), ev)\n\treturn\n}", "func HandleEvent(data interface{}, api *slack.Client) {\n\tlogger.Log(logger.Debug, \"Event will be handled!\")\n\tswitch ev := data.(type) {\n\tcase *slack.HelloEvent:\n\t\tlogger.Log(logger.Debug, \"Hello event done!\")\n\n\tcase *slack.ConnectedEvent:\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Infos: %v\", ev.Info))\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Connection counter: %v\", ev.ConnectionCount))\n\n\tcase *slack.MessageEvent:\n\t\tgo HandleMessage(ev, api)\n\n\tcase *slack.PresenceChangeEvent:\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Presence Change: %v\", ev))\n\n\tcase *slack.LatencyReport:\n\t\tlogger.Log(logger.Debug, fmt.Sprintf(\"Current latency: %v\", ev.Value))\n\n\tcase *slack.RTMError:\n\t\tlogger.Log(logger.Warning, fmt.Sprintf(\"Error: %s\", ev.Error()))\n\n\tcase *slack.InvalidAuthEvent:\n\t\tlogger.Log(logger.Warning, \"Invalid credentials\")\n\t\treturn\n\n\tdefault:\n\t\tlogger.Log(logger.Debug, \"The Event is unknown!\")\n\t}\n}", "func (s *server) createEvent(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdefer r.Body.Close()\n\n\t// Read the body out into a buffer.\n\tbuf, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"%s\", err)\n\t\treturn\n\t}\n\n\t// Read the body as generic JSON, so we can perform JDDF validation on it.\n\t//\n\t// If the request body is invalid JSON, send the user a 400 Bad Request.\n\tvar eventRaw interface{}\n\tif err := json.Unmarshal(buf, &eventRaw); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"%s\", err)\n\t\treturn\n\t}\n\n\t// Validate the event (in eventRaw) against our schema for JDDF events.\n\t//\n\t// In practice, there will never be errors arising here -- see the jddf-go\n\t// docs for details, but basically jddf.Validator.Validate can only error if\n\t// you use \"ref\" in a cyclic manner in your schemas.\n\t//\n\t// Therefore, we ignore the possibility of an error here.\n\tvalidator := jddf.Validator{}\n\tvalidationResult, _ := validator.Validate(s.EventSchema, eventRaw)\n\n\t// If there were validation errors, then we write them out to the response\n\t// body, and send the user a 400 Bad Request.\n\tif len(validationResult.Errors) != 0 {\n\t\tencoder := json.NewEncoder(w)\n\t\tif err := encoder.Encode(validationResult.Errors); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"%s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// If we made it here, the request body contained JSON that passed our schema.\n\t// Let's now write it into the database.\n\t//\n\t// The events table has a \"payload\" column of type \"jsonb\". In Golang-land,\n\t// you can send that to Postgres by just using []byte. The user's request\n\t// payload is already in that format, so we'll use that.\n\t_, err = s.DB.ExecContext(r.Context(), `\n\t\tinsert into events (payload) values ($1)\n\t`, buf)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"%s\", err)\n\t\treturn\n\t}\n\n\t// We're done!\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"%s\", buf)\n}", "func ParseEventData(event *Event) (proto.Message, error) {\n\td := &ptypes.DynamicAny{}\n\terr := ptypes.UnmarshalAny(event.Data, d)\n\tif err != nil {\n\t\treturn nil, ErrCorruptedEventPayload.WithEvent(event).WithError(err)\n\t}\n\treturn d.Message, nil\n}", "func StoreEventHandler(w http.ResponseWriter, r *http.Request) {\n\tvar incEvent models.Event\n\tlog.Println(\"Processing event: \", r.Body)\n\ttoken := r.Header.Get(\"CANARY_TOKEN\")\n\n\tproject := models.Project{}\n\tdatabase.DB.Where(\"token = ?\", token).\n\t\tFirst(&project)\n\tif project.Name == \"\" {\n\t\tlog.Println(\"Could not find project with token\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Invalid Token\"))\n\t\treturn\n\t}\n\n\t// Obtain Event info from JSON\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(&incEvent)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Error decoding JSON\"))\n\t\treturn\n\t}\n\n\tincEvent.ProjectID = project.ID\n\n\t// Attempt to store the Event in the database\n\tevent, err := models.StoreEvent(&incEvent)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"Error saving event\"))\n\t\treturn\n\t}\n\n\tlog.Println(\"Created new event: \", event.ID)\n\n\teventJson, err := json.Marshal(event)\n\tif err != nil {\n\t\tlog.Println(\"Error encoding event\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Send an awknowledge response\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(eventJson)\n\treturn\n}", "func (m SQSMonitor) processLifecycleEventFromASG(message *sqs.Message) (EventBridgeEvent, error) {\n\teventBridgeEvent := EventBridgeEvent{}\n\tlifecycleEvent := LifecycleDetail{}\n\terr := json.Unmarshal([]byte(*message.Body), &lifecycleEvent)\n\n\tswitch {\n\tcase err != nil:\n\t\tlog.Err(err).Msg(\"only lifecycle events from ASG to SQS are supported outside EventBridge\")\n\t\treturn eventBridgeEvent, err\n\n\tcase lifecycleEvent.Event == TEST_NOTIFICATION || lifecycleEvent.LifecycleTransition == TEST_NOTIFICATION:\n\t\terr := fmt.Errorf(\"message is a test notification\")\n\t\tif errs := m.deleteMessages([]*sqs.Message{message}); errs != nil {\n\t\t\terr = multierr.Append(err, errs[0])\n\t\t}\n\t\treturn eventBridgeEvent, skip{err}\n\n\tcase lifecycleEvent.LifecycleTransition != \"autoscaling:EC2_INSTANCE_TERMINATING\":\n\t\tlog.Err(err).Msg(\"only lifecycle termination events from ASG to SQS are supported outside EventBridge\")\n\t\terr = fmt.Errorf(\"unsupported message type (%s)\", message.String())\n\t\treturn eventBridgeEvent, err\n\t}\n\n\teventBridgeEvent.Source = \"aws.autoscaling\"\n\teventBridgeEvent.Time = lifecycleEvent.Time\n\teventBridgeEvent.ID = lifecycleEvent.RequestID\n\teventBridgeEvent.Detail, err = json.Marshal(lifecycleEvent)\n\n\tlog.Debug().Msg(\"processing lifecycle termination event from ASG\")\n\treturn eventBridgeEvent, err\n}", "func (sce ServiceCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func transformLogMessage(cfEvent *events.Envelope, nrEvent map[string]interface{}) {\n\t// event: origin:\"rep\" eventType:LogMessage timestamp:1497038366041617814 deployment:\"cf\" job:\"diego_cell\" index:\"0f4dc7bd-c941-42bf-a835-7c29445ddf8b\" ip:\"192.168.16.24\" logMessage:<message:\"[{\\\"DatasetName\\\":\\\"Metric Messages\\\",\\\"FirehoseEventType\\\":\\\"CounterEvent\\\",\\\"ceDelta\\\":166908,\\\"ceName\\\":\\\"dropsondeListener.receivedByteCount\\\",\\\"ceTotal\\\":25664179951,\\\"deployment\\\":\\\"cf\\\",\\\"eventType\\\":\\\"FirehoseEventTest\\\",\\\"index\\\":\\\"ca858dc5-2a09-465a-831d-c31fa5fb8802\\\",\\\"ip\\\":\\\"192.168.16.26\\\",\\\"job\\\":\\\"doppler\\\",\\\"origin\\\":\\\"DopplerServer\\\",\\\"timestamp\\\":1497038161107}]\" message_type:OUT timestamp:1497038366041615818 app_id:\"f22aac70-c5a9-47a9-b74c-355dd99abbe2\" source_type:\"APP/PROC/WEB\" source_instance:\"0\" >\n\tmessage := cfEvent.LogMessage\n\t// if debug {\n\t// \tlogger.Printf(\">>>>> raw log message: %v\\n\", cfEvent)\n\t// }\n\tprefix := \"log\"\n\tif message.Message != nil {\n\t\tmsgContent := message.GetMessage()\n\t\tif len(msgContent) > 4096 {\n\t\t\tmsgContent = msgContent[0:4095]\n\t\t}\n\t\t// re := regexp.MustCompile(\"=>\")\n\t\t// payload := string([]byte(`payload: {\"instance\"=>\"a305bf1e-f869-4307-5bdc-7f7b\", \"index\"=>0, \"reason\"=>\"CRASHED\", \"exit_description\"=>\"Instance never healthy after 1m0s: Failed to make TCP connection to port 8080: connection refused\", \"crash_count\"=>2, \"crash_timestamp\"=>1522812923161363839, \"version\"=>\"68a457a6-2f43-4ed7-af5f-038f2e1da1fc\"}`))\n\t\t// fmt.Println(re.ReplaceAllString(payload, \": \"))\n\t\t// logger.Printf(\">>>>> log message payload: %v\\n\", string(msgContent))\n\t\tnrEvent[prefix+\"Message\"] = string(msgContent)\n\t\tparsedContent := make(map[string]interface{})\n\t\tif err := json.Unmarshal(msgContent, &parsedContent); err == nil {\n\t\t\tfor k, v := range parsedContent {\n\t\t\t\tnrEvent[prefix+\"Message\"+k] = v\n\t\t\t}\n\t\t}\n\t\taddAppDetailInfo(nrEvent, message.GetAppId()) // add app detail info to Insights LogMessage event\n\t}\n\tif message.MessageType != nil {\n\t\tnrEvent[prefix+\"MessageType\"] = message.GetMessageType().String()\n\t}\n\tif message.Timestamp != nil {\n\t\tnrEvent[prefix+\"Timestamp\"] = time.Unix(0, message.GetTimestamp())\n\t}\n\tif message.AppId != nil {\n\t\tnrEvent[prefix+\"AppId\"] = message.GetAppId()\n\t}\n\tif message.SourceType != nil {\n\t\tnrEvent[prefix+\"SourceType\"] = message.GetSourceType()\n\t}\n\tif message.SourceInstance != nil {\n\t\tnrEvent[prefix+\"SourceInstance\"] = message.GetSourceInstance()\n\t}\n}", "func (e *DepositedEvent) Data() (*eventstore.EventData, error) {\n\teventData := depositedEventData{e.Amount}\n\tbytes, err := json.Marshal(eventData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &eventstore.EventData{e.StreamID, e.EventNumber, EventTypeDeposited, string(bytes), time.Time{}}, nil\n}", "func (e event) Data() eh.EventData {\n\treturn e.AggregateEvent.data\n}", "func (s *service) Trigger(eventName string, payload interface{}) error {\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata := struct {\n\t\tToken string `json:\"token\"`\n\t\tEvent string `json:\"event\"`\n\t\tPayload string `json:\"payload\"`\n\t}{\n\t\tToken: s.token,\n\t\tEvent: eventName,\n\t\tPayload: string(b),\n\t}\n\tif err := post(s.getServerURL(\"/handle\"), &data, nil); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func PostEvent(client *http.Client, hookURL string, message EventMessage) (*http.Response, error) {\n\tbuf := new(bytes.Buffer)\n\terr := json.NewEncoder(buf).Encode(message)\n\tif err != nil {\n\t\tlog.Printf(\"Encode json failed: %+v\\n\", err)\n\t\treturn nil, err\n\t}\n\tresp, err := client.Post(hookURL, \"application/json; charset=utf-8\", buf)\n\treturn resp, err\n}", "func EventSubscriber(event interface{}) {\n\tbyteData, _ := json.Marshal(&event)\n\tvar message common.Events\n\n\terr := json.Unmarshal(byteData, &message)\n\tif err != nil {\n\t\tl.Log.Error(\"error while unmarshal the event\" + err.Error())\n\t\treturn\n\t}\n\twriteEventToJobQueue(message)\n}", "func ParseWebhookEvent(e *WebhookEvent, payload []byte) error {\n\treturn e.parse(payload)\n}", "func (c *NATSTestClient) event(ns string, event string, payload interface{}) {\n\tc.mu.Lock()\n\n\ts, ok := c.subs[ns]\n\tif !ok {\n\t\tc.mu.Unlock()\n\t\tpanic(\"test: no subscription for \" + ns)\n\t}\n\n\tvar data []byte\n\tvar err error\n\tif data, ok = payload.([]byte); !ok {\n\t\tdata, err = json.Marshal(payload)\n\t\tif err != nil {\n\t\t\tc.mu.Unlock()\n\t\t\tpanic(\"test: error marshaling event: \" + err.Error())\n\t\t}\n\t}\n\n\tc.mu.Unlock()\n\tsubj := ns + \".\" + event\n\tc.Tracef(\"=>> %s: %s\", subj, data)\n\ts.cb(subj, data, nil)\n}", "func TestEventPayload(t *testing.T) {\n\tassert := asserts.NewTesting(t, asserts.FailStop)\n\n\tpayloadIn := []string{\"a\", \"b\", \"c\"}\n\tpayloadOutA := []string{}\n\tevt, err := mesh.NewEvent(\"test\", payloadIn)\n\tassert.NoError(err)\n\tassert.Equal(evt.Topic(), \"test\")\n\tassert.True(evt.HasPayload())\n\terr = evt.Payload(&payloadOutA)\n\tassert.NoError(err)\n\tassert.Length(payloadOutA, 3)\n\tassert.Equal(payloadOutA, payloadIn)\n\n\tpayloadOutB := []int{}\n\tevt, err = mesh.NewEvent(\"test\", 1, 2, 3, 4, 5)\n\tassert.NoError(err)\n\tassert.Equal(evt.Topic(), \"test\")\n\tassert.True(evt.HasPayload())\n\terr = evt.Payload(&payloadOutB)\n\tassert.NoError(err)\n\tassert.Length(payloadOutB, 5)\n\tassert.Equal(payloadOutB, []int{1, 2, 3, 4, 5})\n}", "func (app *Configurable) WrapIntoEvent(parameters map[string]string) interfaces.AppFunction {\n\tprofileName, ok := parameters[ProfileName]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find %s\", ProfileName)\n\t\treturn nil\n\t}\n\tdeviceName, ok := parameters[DeviceName]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find %s\", DeviceName)\n\t\treturn nil\n\t}\n\tresourceName, ok := parameters[ResourceName]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find %s\", ResourceName)\n\t\treturn nil\n\t}\n\tvalueType, ok := parameters[ValueType]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find %s\", ValueType)\n\t\treturn nil\n\t}\n\n\tprofileName = strings.TrimSpace(profileName)\n\tdeviceName = strings.TrimSpace(deviceName)\n\tresourceName = strings.TrimSpace(resourceName)\n\tvalueType = strings.TrimSpace(valueType)\n\n\tvar transform *transforms.EventWrapper\n\n\t// Converts to upper case and validates it is a valid ValueType\n\tvalueType, err := common.NormalizeValueType(valueType)\n\tif err != nil {\n\t\tapp.lc.Error(err.Error())\n\t\treturn nil\n\t}\n\n\tswitch valueType {\n\tcase common.ValueTypeBinary:\n\t\tmediaType, ok := parameters[MediaType]\n\t\tif !ok {\n\t\t\tapp.lc.Error(\"Could not find \" + MediaType)\n\t\t\treturn nil\n\t\t}\n\n\t\tmediaType = strings.TrimSpace(mediaType)\n\n\t\tif len(mediaType) == 0 {\n\t\t\tapp.lc.Error(\"MediaType can not be empty when ValueType=Binary\")\n\t\t\treturn nil\n\t\t}\n\n\t\ttransform = transforms.NewEventWrapperBinaryReading(profileName, deviceName, resourceName, mediaType)\n\tcase common.ValueTypeObject:\n\t\ttransform = transforms.NewEventWrapperObjectReading(profileName, deviceName, resourceName)\n\n\tdefault:\n\t\ttransform = transforms.NewEventWrapperSimpleReading(profileName, deviceName, resourceName, valueType)\n\t}\n\n\treturn transform.Wrap\n}", "func (serv *Server) GenericEvent(ctx context.Context, message *event_listener.GenericEventMessage) (*event_listener.GenericEventResponse, error) {\n\tresponse := event_listener.GenericEventResponse{}\n\tfmt.Printf(\"Received message : '%s'\\n\", message.Message)\n\n\treturn &response, nil\n}", "func (jp *jsonPatcher) EventFromBytes(data []byte) (core.Event, error) {\n\tevent := &patchEvent{}\n\tif err := cbornode.DecodeInto(data, &event); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar op operation\n\tif err := json.Unmarshal(event.Patch, &op); err != nil {\n\t\tlog.Errorf(\"error while unmarshaling patch: %v\", err)\n\t\treturn event, nil\n\t}\n\tlog.Debug(\"unmarshaled event patch: %s\", op.JSONPatch)\n\treturn event, nil\n}", "func (shrce ServiceHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (tg *TradesGroup) handleEvent(msg []byte) (err error) {\n\tvar event event\n\tif err = json.Unmarshal(msg, &event); err != nil {\n\t\treturn\n\t}\n\tif event.Event == eventInfo {\n\t\tif event.Code == wsCodeStopping {\n\t\t\ttg.restart()\n\t\t\treturn\n\t\t}\n\t}\n\tif event.Event == eventSubscribed {\n\t\tif event.Channel == channelCandles {\n\t\t\tevent.Symbol = strings.Replace(event.Key, \"trade:1m:t\", \"\", 1)\n\t\t\tevent.Pair = event.Symbol\n\t\t}\n\t\ttg.add(event)\n\t\treturn\n\t}\n\tlog.Println(\"[BITFINEX] Unprocessed event: \", string(msg))\n\treturn\n}", "func (ahrce ApplicationHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (se ServiceEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn &se, true\n}", "func (conn *Connection) handleEvent(data []byte) bool {\n\tvar i interface{}\n\terr := json.Unmarshal(data, &i)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t// should be an array.\n\tc := i.([]interface{})\n\n\tvar (\n\t\tcommand string\n\t\tparams map[string]interface{}\n\t)\n\n\tswitch c[0].(type) {\n\tcase string:\n\t\tcommand = c[0].(string)\n\t}\n\tswitch c[1].(type) {\n\tcase map[string]interface{}:\n\t\tparams = c[1].(map[string]interface{})\n\t}\n\n\t// if a handler for this command exists, run it\n\tconn.service.handleEvent(command, params)\n\n\treturn true\n}", "func (aurse ApplicationUpgradeRollbackStartEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (p *EventProcessor) ProcessEvent(newEvents []publisher.Event, event publisher.Event) ([]publisher.Event, error) {\n\t// Get the message from the log file\n\teventMsgFieldVal, err := event.Content.Fields.GetValue(\"message\")\n\tif err != nil {\n\t\treturn newEvents, coreerrors.Wrap(ErrEventNoMsg, err.Error()).FormatError(event)\n\t}\n\teventMsg, ok := eventMsgFieldVal.(string)\n\tif !ok {\n\t\treturn newEvents, nil\n\t}\n\n\t// Unmarshal the message into a Log Entry Event\n\tvar springLogEntry SpringLogEntry\n\terr = json.Unmarshal([]byte(eventMsg), &springLogEntry)\n\tif err != nil {\n\t\tmsgErr := coreerrors.Wrap(ErrEventMsgStructure, err.Error()).FormatError(eventMsg)\n\t\tlogp.Error(msgErr)\n\t\treturn newEvents, msgErr\n\t}\n\n\tfmt.Printf(\"*** JSON : %v\", springLogEntry)\n\texternalAPIID, name := getAPIServiceByExternalAPIID(springLogEntry)\n\n\tnewEvents, err = p.processTransactions(newEvents, event, springLogEntry, externalAPIID, name)\n\tif err != nil {\n\t\ttrxnErr := coreerrors.Wrap(ErrTrxnDataProcess, err.Error())\n\t\tlogp.Error(trxnErr)\n\t\treturn newEvents, trxnErr\n\t}\n\n\treturn newEvents, nil\n}", "func (ae ApplicationEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (d *azure) HandleWebhook(c *gin.Context) {\n\tlog.Debug(\"Got azure webhook event\")\n\n\tpayload := webhookPayload{}\n\n\tif err := c.BindJSON(&payload); err != nil {\n\t\tlog.WithError(err).Error(\"Failed to bind payload JSON to expected structure\")\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tvar s []string = strings.Split(payload.Target.Repository, \"/\")\n\tpayload.Target.Name = strings.Join(s[1:len(s)], \"\")\n\n\tif payload.Action != \"push\" {\n\t\tlog.Debug(fmt.Sprintf(\"Skip event %s\", payload.Action))\n\t\treturn\n\t}\n\n\tevent := hermes.NewNormalizedEvent()\n\teventURI := constructEventURI(&payload, c.Query(\"account\"))\n\tpayloadJSON, err := json.Marshal(payload)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to covert webhook payload structure to JSON\")\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\t// keep original JSON\n\tevent.Original = string(payloadJSON)\n\n\t// get image push details\n\tevent.Variables[\"event\"] = payload.Action\n\tns := strings.Split(payload.Request.Host, \".\")\n\tevent.Variables[\"namespace\"] = ns[0]\n\tevent.Variables[\"name\"] = payload.Target.Repository\n\tevent.Variables[\"tag\"] = payload.Target.Tag\n\tevent.Variables[\"type\"] = \"registry\"\n\tevent.Variables[\"provider\"] = \"azure\"\n\tevent.Variables[\"pushed_at\"] = payload.Timestamp\n\n\t// get secret from URL query\n\tevent.Secret = c.Query(\"secret\")\n\n\tlog.Debug(\"Event url \" + eventURI)\n\n\t// invoke trigger\n\terr = d.hermesSvc.TriggerEvent(eventURI, event)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to trigger event pipelines\")\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tc.Status(http.StatusOK)\n}", "func (ause ApplicationUpgradeStartEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (nde NodeDownEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func azureValidationEvent(req []byte) *string {\n\tv := []SubscriptionValidationEvent{}\n\tif err := json.Unmarshal(req, &v); err == nil {\n\t\tif len(v) > 0 && len(v[0].Data.ValidationCode) > 0 {\n\t\t\tr := SubscriptionValidationResp{}\n\t\t\tr.ValidationResponse = v[0].Data.ValidationCode\n\t\t\tif b, err := json.Marshal(r); err == nil {\n\t\t\t\tresp := string(b)\n\t\t\t\treturn &resp\n\t\t\t}\n\t\t\tlog.Fatalf(\"Unable to marshal Azure validation response\")\n\t\t}\n\t}\n\treturn nil\n}", "func (d *DevClient) CreateEventHandler(systemKey, name string, data map[string]interface{}) (map[string]interface{}, error) {\n\treturn createEventHandler(d, _EVENTS_HDLRS_PREAMBLE+systemKey+\"/\"+name, data)\n}", "func parseMongoDataAsEvt(res bson.Raw, forceAddedEvent bool) (*event, error) {\n\n\t// We unmarshal the mongo record from the BSON\n\trecord := MongoRecord{}\n\tif err := bson.Unmarshal(res, &record); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We decode the currentValue. We're only interested in the\n\t// currentValue and not the previousValue. Why? Because the\n\t// previousValue is only needed for delete/update events.\n\t// In this case, we know that we're emitting an ADDED event\n\tvar err error\n\tif record.CurrentValue != nil && len(record.CurrentValue) > 0 {\n\t\trecord.CurrentBytes, err = json.Marshal(record.CurrentValue)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif record.PreviousValue != nil && len(record.PreviousValue) > 0 {\n\t\trecord.PreviousBytes, err = json.Marshal(record.PreviousValue)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisDeleted := record.IsDeleted\n\tisCreated := record.IsCreated\n\tif forceAddedEvent {\n\t\tisDeleted = false\n\t\tisCreated = true\n\t}\n\n\t// This is the ADDED event we want to build from the current\n\t// state of the object\n\tevt := &event{\n\t\tkey: record.Key,\n\t\tvalue: record.CurrentBytes,\n\t\tprevValue: record.PreviousBytes,\n\t\t// We're using the record timestamp as a revision\n\t\t// This is now extraordinary, but it works.\n\t\t// If anyone has a better idea that doesn't include\n\t\t// global atomic counters, feel free to contribute.\n\t\trev: record.Timestamp,\n\t\tisDeleted: isDeleted,\n\t\tisCreated: isCreated,\n\t\tisProgressNotify: false,\n\t}\n\n\treturn evt, nil\n}", "func createServiceHandler(event *api.Event) error {\n\tlogdog.Infof(\"create service handler\")\n\topts := workerOptions.DeepCopy()\n\tworker, err := CloudController.Provision(string(event.EventID), opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = worker.Do()\n\tif err != nil {\n\t\tlogdog.Error(\"run worker err\", logdog.Fields{\"err\": err})\n\t\treturn err\n\t}\n\n\t// set worker info to event\n\tevent.Worker = worker.GetWorkerInfo()\n\tSaveEventToEtcd(event)\n\tgo CheckWorkerTimeout(event)\n\n\treturn nil\n}", "func eventHandler(evt *elemental.Event) {\n\n\tswitch evt.Identity {\n\n\tcase gaia.ExternalNetworkIdentity.Name:\n\n\t\te := gaia.NewExternalNetwork()\n\t\tif err := evt.Decode(&e); err != nil {\n\t\t\tzap.L().Error(\"Failed to decode event\", zap.Reflect(\"event\", evt))\n\t\t}\n\n\t\tfmt.Printf(\"External network name: %s type %s\\n\", e.Name, evt.Type)\n\n\tcase gaia.NetworkAccessPolicyIdentity.Name:\n\n\t\tp := gaia.NewNetworkAccessPolicy()\n\t\tif err := evt.Decode(&p); err != nil {\n\t\t\tzap.L().Error(\"Failed to decode event\", zap.Reflect(\"event\", evt))\n\t\t}\n\n\t\tfmt.Printf(\"Policy name: %s type %s\\n\", p.Name, evt.Type)\n\n\tdefault:\n\t\tzap.L().Error(\"Received event that was not subscribed\", zap.Reflect(\"event\", evt))\n\t}\n}", "func getProxyUpdateEvent(msg events.PubSubMessage) *proxyUpdateEvent {\n\tswitch msg.Kind {\n\tcase\n\t\t//\n\t\t// K8s native resource events\n\t\t//\n\t\t// Endpoint event\n\t\tannouncements.EndpointAdded, announcements.EndpointDeleted, announcements.EndpointUpdated,\n\t\t// k8s Ingress event\n\t\tannouncements.IngressAdded, announcements.IngressDeleted, announcements.IngressUpdated,\n\t\t//\n\t\t// OSM resource events\n\t\t//\n\t\t// Egress event\n\t\tannouncements.EgressAdded, announcements.EgressDeleted, announcements.EgressUpdated,\n\t\t// IngressBackend event\n\t\tannouncements.IngressBackendAdded, announcements.IngressBackendDeleted, announcements.IngressBackendUpdated,\n\t\t// MulticlusterService event\n\t\tannouncements.MultiClusterServiceAdded, announcements.MultiClusterServiceDeleted, announcements.MultiClusterServiceUpdated,\n\t\t//\n\t\t// SMI resource events\n\t\t//\n\t\t// SMI HTTPRouteGroup event\n\t\tannouncements.RouteGroupAdded, announcements.RouteGroupDeleted, announcements.RouteGroupUpdated,\n\t\t// SMI TCPRoute event\n\t\tannouncements.TCPRouteAdded, announcements.TCPRouteDeleted, announcements.TCPRouteUpdated,\n\t\t// SMI TrafficSplit event\n\t\tannouncements.TrafficSplitAdded, announcements.TrafficSplitDeleted, announcements.TrafficSplitUpdated,\n\t\t// SMI TrafficTarget event\n\t\tannouncements.TrafficTargetAdded, announcements.TrafficTargetDeleted, announcements.TrafficTargetUpdated,\n\t\t//\n\t\t// Proxy events\n\t\t//\n\t\tannouncements.ProxyUpdate:\n\t\treturn &proxyUpdateEvent{\n\t\t\tmsg: msg,\n\t\t\ttopic: announcements.ProxyUpdate.String(),\n\t\t}\n\n\tcase announcements.MeshConfigUpdated:\n\t\tprevMeshConfig, okPrevCast := msg.OldObj.(*v1alpha1.MeshConfig)\n\t\tnewMeshConfig, okNewCast := msg.NewObj.(*v1alpha1.MeshConfig)\n\t\tif !okPrevCast || !okNewCast {\n\t\t\tlog.Error().Msgf(\"Expected MeshConfig type, got previous=%T, new=%T\", okPrevCast, okNewCast)\n\t\t\treturn nil\n\t\t}\n\n\t\tprevSpec := prevMeshConfig.Spec\n\t\tnewSpec := newMeshConfig.Spec\n\t\t// A proxy config update must only be triggered when a MeshConfig field that maps to a proxy config\n\t\t// changes.\n\t\tif prevSpec.Traffic.EnableEgress != newSpec.Traffic.EnableEgress ||\n\t\t\tprevSpec.Traffic.EnablePermissiveTrafficPolicyMode != newSpec.Traffic.EnablePermissiveTrafficPolicyMode ||\n\t\t\tprevSpec.Observability.Tracing != newSpec.Observability.Tracing ||\n\t\t\tprevSpec.Traffic.InboundExternalAuthorization.Enable != newSpec.Traffic.InboundExternalAuthorization.Enable ||\n\t\t\t// Only trigger an update on InboundExternalAuthorization field changes if the new spec has the 'Enable' flag set to true.\n\t\t\t(newSpec.Traffic.InboundExternalAuthorization.Enable && (prevSpec.Traffic.InboundExternalAuthorization != newSpec.Traffic.InboundExternalAuthorization)) ||\n\t\t\tprevSpec.FeatureFlags != newSpec.FeatureFlags {\n\t\t\treturn &proxyUpdateEvent{\n\t\t\t\tmsg: msg,\n\t\t\t\ttopic: announcements.ProxyUpdate.String(),\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tcase announcements.PodUpdated:\n\t\t// Only trigger a proxy update for proxies associated with this pod based on the proxy UUID\n\t\tprevPod, okPrevCast := msg.OldObj.(*corev1.Pod)\n\t\tnewPod, okNewCast := msg.NewObj.(*corev1.Pod)\n\t\tif !okPrevCast || !okNewCast {\n\t\t\tlog.Error().Msgf(\"Expected *Pod type, got previous=%T, new=%T\", okPrevCast, okNewCast)\n\t\t\treturn nil\n\t\t}\n\t\tprevMetricAnnotation := prevPod.Annotations[constants.PrometheusScrapeAnnotation]\n\t\tnewMetricAnnotation := newPod.Annotations[constants.PrometheusScrapeAnnotation]\n\t\tif prevMetricAnnotation != newMetricAnnotation {\n\t\t\tproxyUUID := newPod.Labels[constants.EnvoyUniqueIDLabelName]\n\t\t\treturn &proxyUpdateEvent{\n\t\t\t\tmsg: msg,\n\t\t\t\ttopic: GetPubSubTopicForProxyUUID(proxyUUID),\n\t\t\t}\n\t\t}\n\t\treturn nil\n\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (cmpfse ChaosMovePrimaryFaultScheduledEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (fe FabricEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (this *Device) mapEvent(event []byte) (api.INotification, error) {\n if this.eventProcessor == nil {\n return nil, errors.New(fmt.Sprintf(ERR_NO_EVENT_PROCESSOR, this.Info().String()))\n }\n\n var evt messages.IEvent\n var msg api.INotification\n var err error\n\n if evt ,err = this.eventProcessor(this.Info().Mapify(), event); err == nil {\n msg = api.NewNotification(evt.Sender(), evt.PropertyName(), evt.PropertyValue())\n }\n\n return msg, err\n}", "func (pde ProcessDeactivatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (dahrce DeployedApplicationHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func newEvent(values map[string]interface{}, machineId string) interface{} {\n\tswitch values[\"event\"].(string) {\n\n\tcase \"ping.offline\", \"ping.online\":\n\t\treturn HeartBeat{Event: values[\"event\"].(string),\n\t\t\tIp: values[\"ip\"].(string),\n\t\t\tMachineId: machineId}\n\n\tcase \"fs.removed\", \"fs.created\":\n\t\treturn FsSystem{Event: values[\"event\"].(string),\n\t\t\tVolume: values[\"volume\"].(string),\n\t\t\tType: values[\"type\"].(string),\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\n\tcase \"disk.unplugged\":\n\t\treturn DiskUnplugged{Event: values[\"event\"].(string),\n\t\t\tUuid: values[\"uuid\"].(string),\n\t\t\tLocation: values[\"location\"].(string),\n\t\t\tDevName: values[\"dev_name\"].(string),\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\n\tcase \"disk.plugged\", \"raid.created\", \"volume.created\", \"volume.removed\", \"raid.degraded\", \"raid.failed\", \"volume.failed\", \"volume.normal\", \"raid.normal\":\n\t\treturn DiskPlugged{Event: values[\"event\"].(string),\n\t\t\tUuid: values[\"uuid\"].(string),\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\n\tcase \"raid.removed\":\n\t\tdisks := values[\"raid_disks\"].([]interface{})\n\t\tvar ones []string\n\t\tfor _, val := range disks {\n\t\t\tdisk := val.(string)\n\t\t\tones = append(ones, disk)\n\t\t}\n\n\t\treturn RaidRemove{Event: values[\"event\"].(string),\n\t\t\tUuid: values[\"uuid\"].(string),\n\t\t\tRaidDisks: ones,\n\t\t\tMachineId: machineId,\n\t\t\tIp: values[\"ip\"].(string)}\n\t}\n\treturn nil\n}", "func (srhrce StatefulReplicaHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (nhrce NodeHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (e event) Data() eh.EventData {\n\treturn e.dbEvent.data\n}", "func (r *Rest) PostHwEvent(url *types.URI, e hwevent.Event) error {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\tlog.Errorf(\"error marshalling event %v\", e)\n\t\treturn err\n\t}\n\tif status := r.Post(url, b); status == http.StatusBadRequest {\n\t\treturn fmt.Errorf(\"post returned status %d\", status)\n\t}\n\treturn nil\n}", "func (ne NodeEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (srhrce StatelessReplicaHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (fwdclient *Client) SubmitEvent(evt EventRequest) error {\n\tlog.Debugf(\"%s: url=%s\", fwdclient.AppName, fwdclient.ActionUrls.Raw)\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(evt)\n\treq, err := http.NewRequest(\"POST\", fwdclient.ActionUrls.Raw, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Splunk %s\", fwdclient.Token))\n\tresp, err := fwdclient.httpclient.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: Authorization Token is inorrect. Error: %s\", fwdclient.AppName, err)\n\t}\n\tdefer resp.Body.Close()\n\tlog.Debugf(\"%s: status=%d %s\", fwdclient.AppName, resp.StatusCode, http.StatusText(resp.StatusCode))\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: failed: response : %s\", fwdclient.AppName, err)\n\t}\n\teventResponse := new(EventResponse)\n\tif err := json.Unmarshal(respBody, eventResponse); err != nil {\n\t\treturn fmt.Errorf(\"%s: failed: Response is not JSON formate: %s\", fwdclient.AppName, respBody)\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"%s: failed: %d %s (%s)\", fwdclient.AppName, resp.StatusCode, http.StatusText(resp.StatusCode), eventResponse.Text)\n\t}\n\tlog.Debugf(\"%s: code=%d, text=%s\", fwdclient.AppName, eventResponse.Code, eventResponse.Text)\n\treturn nil\n}", "func (r *Recorder) Eventf(\n\tobject corev1.ObjectReference,\n\tmetadata map[string]string,\n\tseverity, reason string,\n\tmessageFmt string, args ...interface{}) error {\n\tif r.Client == nil {\n\t\treturn fmt.Errorf(\"retryable HTTP client has not been initialized\")\n\t}\n\n\tmessage := fmt.Sprintf(messageFmt, args...)\n\n\tif object.Kind == \"\" {\n\t\treturn fmt.Errorf(\"failed to get object kind\")\n\t}\n\n\tif object.Name == \"\" {\n\t\treturn fmt.Errorf(\"failed to get object name\")\n\t}\n\n\tif object.Namespace == \"\" {\n\t\treturn fmt.Errorf(\"failed to get object namespace\")\n\t}\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tevent := Event{\n\t\tInvolvedObject: object,\n\t\tSeverity: severity,\n\t\tTimestamp: metav1.Now(),\n\t\tMessage: message,\n\t\tReason: reason,\n\t\tMetadata: metadata,\n\t\tReportingController: r.ReportingController,\n\t\tReportingInstance: hostname,\n\t}\n\n\tbody, err := json.Marshal(event)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal object into json, error: %w\", err)\n\t}\n\n\tif _, err := r.Client.Post(r.Webhook, \"application/json\", body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (dshrce DeployedServiceHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (cmsfse ChaosMoveSecondaryFaultScheduledEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (t *SimpleChaincode) create_event(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar tEvent TransactionEvent\n\t\n\ttranID \t\t\t:= \"\\\"TranID\\\":\\\"\"+args[0]+\"\\\", \"\n\tsenderName \t\t:= \"\\\"SenderName\\\":\\\"\"+args[1]+\"\\\", \"\n\tsenderCountry := \"\\\"SenderCountry\\\":\\\"\"+args[2]+\"\\\", \"\n\treceiverName \t:= \"\\\"ReceiverName\\\":\\\"\"+args[3]+\"\\\", \"\n\treceiverCountry := \"\\\"ReceiverCountry\\\":\\\"\"+args[4]+\"\\\", \"\n\tamount \t\t\t:= \"\\\"Amount\\\":\\\"\"+args[5]+\"\\\", \"\n\n // Concatenates the variables to create the total JSON object\n\tevent_json := \"{\"+tranID+senderName+senderCountry+receiverName+receiverCountry+amount+\"}\" \t\t\n\t// Convert the JSON defined above into a TransactionEvent object for go\n\terr := json.Unmarshal([]byte(event_json), &tEvent)\t\t\t\t\t\t\t\t\t\t\n\tif err != nil { \n\t\treturn nil, errors.New(\"Invalid JSON object\") \n\t}\n\n\tbytes, err := json.Marshal(tEvent)\n\tif err != nil { \n\t\treturn nil, errors.New(\"Error converting transaction event\") \n\t}\n\n\t// Save new tran event record\n\terr = stub.PutState(tEvent.TranID, bytes)\n\tif err != nil { \n\t\tfmt.Printf(\"create_event: Error storing transaction event: %s\", err); \n\t\treturn nil, errors.New(\"Error storing transaction event\") \n\t}\n\n\t// Update tranIDs with newly created ID and store it in chain.\n\tbytes, err = stub.GetState(\"tranIDs\")\n\tif err != nil { \n\t\treturn nil, errors.New(\"Unable to get tranIDs\") \n\t}\n\n\tvar tranHld TRAN_Holder\n\terr = json.Unmarshal(bytes, &tranHld)\n\tif err != nil {\t\n\t\treturn nil, errors.New(\"Corrupt TRAN_Holder record\") \n\t}\n\n\ttranHld.TranIDs = append(tranHld.TranIDs, args[0])\n\tbytes, err = json.Marshal(tranHld)\n\n\terr = stub.PutState(\"tranIDs\", bytes)\n\tif err != nil { \n\t\tfmt.Printf(\"create_event: Error storing TranIDs: %s\", err); \n\t\treturn nil, errors.New(\"Error storing TranIDs\") \n\t}\n\n\treturn nil, nil \n}", "func (nae NodeAddedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (phrce PartitionHealthReportCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func createEventJson(t string) string {\n\tuserJson := `\n\t{\n\t\"created\": 1326853478,\n\t\"livemode\": false,\n\t\"id\": \"evt_00000000000000\",\n\t\"type\": \"` + t + `\",\n\t\"object\": \"event\",\n\t\"request\": null,\n\t\"pending_webhooks\": 1,\n\t\"api_version\": \"2017-08-15\",\n\t\"data\": {\n\t\"object\": {\n\t\"id\": \"in_00000000000000\",\n\t\"object\": \"invoice\",\n\t\"amount_due\": 0,\n\t\"application_fee\": null,\n\t\"attempt_count\": 0,\n\t\"attempted\": false,\n\t\"billing\": \"charge_automatically\",\n\t\"charge\": null,\n\t\"closed\": false,\n\t\"currency\": \"eur\",\n\t\"customer\": \"cus_00000000000000\",\n\t\"date\": 1510657958,\n\t\"description\": null,\n\t\"discount\": null,\n\t\"ending_balance\": null,\n\t\"forgiven\": false,\n\t\"lines\": {\n\t\"data\": [\n\t{\n\t\"id\": \"sub_BlZUOK0My1Ht6S\",\n\t\"object\": \"line_item\",\n\t\"amount\": 2000,\n\t\"currency\": \"eur\",\n\t\"description\": null,\n\t\"discountable\": true,\n\t\"livemode\": true,\n\t\"metadata\": {\n\t},\n\t\"period\": {\n\t\"start\": 1513249959,\n\t\"end\": 1515928359\n\t},\n\t\"plan\": {\n\t\"id\": \"gold\",\n\t\"object\": \"plan\",\n\t\"amount\": 2000,\n\t\"created\": 1510657959,\n\t\"currency\": \"eur\",\n\t\"interval\": \"month\",\n\t\"interval_count\": 1,\n\t\"livemode\": false,\n\t\"metadata\": {\n\t},\n\t\"name\": \"silver-monthly\",\n\t\"statement_descriptor\": null,\n\t\"trial_period_days\": null\n\t},\n\t\"proration\": false,\n\t\"quantity\": 1,\n\t\"subscription\": null,\n\t\"subscription_item\": \"si_BlZUGEoPCsxCVq\",\n\t\"type\": \"subscription\"\n\t}\n\t],\n\t\"has_more\": false,\n\t\"object\": \"list\",\n\t\"url\": \"/v1/invoices/in_1BO2LKFn7GFBH7C2VSivRSCd/lines\"\n\t},\n\t\"livemode\": false,\n\t\"metadata\": {\n\t},\n\t\"next_payment_attempt\": 1510661558,\n\t\"number\": \"dd974423d7-0001\",\n\t\"paid\": true,\n\t\"period_end\": 1510657958,\n\t\"period_start\": 1510657958,\n\t\"receipt_number\": null,\n\t\"starting_balance\": 0,\n\t\"statement_descriptor\": null,\n\t\"subscription\": null,\n\t\"subtotal\": 0,\n\t\"tax\": null,\n\t\"tax_percent\": null,\n\t\"total\": 0,\n\t\"webhooks_delivered_at\": null\n\t\t\t}\n\t\t}\n\t}`\n\n\treturn userJson\n}", "func (crrfse ChaosRemoveReplicaFaultScheduledEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func transformEvent(event *APIEvents) {\n\t// if event version is <= 1.21 there will be no Action and no Type\n\tif event.Action == \"\" && event.Type == \"\" {\n\t\tevent.Action = event.Status\n\t\tevent.Actor.ID = event.ID\n\t\tevent.Actor.Attributes = map[string]string{}\n\t\tswitch event.Status {\n\t\tcase \"delete\", \"import\", \"pull\", \"push\", \"tag\", \"untag\":\n\t\t\tevent.Type = \"image\"\n\t\tdefault:\n\t\t\tevent.Type = \"container\"\n\t\t\tif event.From != \"\" {\n\t\t\t\tevent.Actor.Attributes[\"image\"] = event.From\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif event.Status == \"\" {\n\t\t\tif event.Type == \"image\" || event.Type == \"container\" {\n\t\t\t\tevent.Status = event.Action\n\t\t\t} else {\n\t\t\t\t// Because just the Status has been overloaded with different Types\n\t\t\t\t// if an event is not for an image or a container, we prepend the type\n\t\t\t\t// to avoid problems for people relying on actions being only for\n\t\t\t\t// images and containers\n\t\t\t\tevent.Status = event.Type + \":\" + event.Action\n\t\t\t}\n\t\t}\n\t\tif event.ID == \"\" {\n\t\t\tevent.ID = event.Actor.ID\n\t\t}\n\t\tif event.From == \"\" {\n\t\t\tevent.From = event.Actor.Attributes[\"image\"]\n\t\t}\n\t}\n}", "func (w *BaseWebsocketClient) OnWsMessage(payload []byte, isBinary bool) {}", "func (nue NodeUpEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (sce ServiceCreatedEvent) AsServiceCreatedEvent() (*ServiceCreatedEvent, bool) {\n\treturn &sce, true\n}", "func (n *NetImpl) eventHandler(handler interface{}, params ...interface{}) {\n\tcallback := handler.(func(_ *peering.RecvEvent))\n\trecvEvent := params[0].(*peering.RecvEvent)\n\tcallback(recvEvent)\n}", "func eventToExportEvent(e *v1.Event) *observerpb.ExportEvent {\n\tswitch ev := e.Event.(type) {\n\tcase *flowpb.Flow:\n\t\treturn &observerpb.ExportEvent{\n\t\t\tTime: ev.GetTime(),\n\t\t\tNodeName: ev.GetNodeName(),\n\t\t\tResponseTypes: &observerpb.ExportEvent_Flow{\n\t\t\t\tFlow: ev,\n\t\t\t},\n\t\t}\n\tcase *flowpb.LostEvent:\n\t\treturn &observerpb.ExportEvent{\n\t\t\tTime: e.Timestamp,\n\t\t\tNodeName: nodeTypes.GetName(),\n\t\t\tResponseTypes: &observerpb.ExportEvent_LostEvents{\n\t\t\t\tLostEvents: ev,\n\t\t\t},\n\t\t}\n\tcase *flowpb.AgentEvent:\n\t\treturn &observerpb.ExportEvent{\n\t\t\tTime: e.Timestamp,\n\t\t\tNodeName: nodeTypes.GetName(),\n\t\t\tResponseTypes: &observerpb.ExportEvent_AgentEvent{\n\t\t\t\tAgentEvent: ev,\n\t\t\t},\n\t\t}\n\tcase *flowpb.DebugEvent:\n\t\treturn &observerpb.ExportEvent{\n\t\t\tTime: e.Timestamp,\n\t\t\tNodeName: nodeTypes.GetName(),\n\t\t\tResponseTypes: &observerpb.ExportEvent_DebugEvent{\n\t\t\t\tDebugEvent: ev,\n\t\t\t},\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n}", "func FromEventObjectStorage(_ []byte, data []byte) (result objectstorage.StorableObject, err error) {\n\treturn parseEvent(marshalutil.New(data))\n}", "func (eh *EventHandler) PostHandler(c *gin.Context) {\n\teventsArray, err := eh.parser.ParseEventsBody(c)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Error parsing events body: %v\", err)\n\t\tc.JSON(http.StatusBadRequest, middleware.ErrResponse(msg, nil))\n\t\treturn\n\t}\n\n\tiface, ok := c.Get(middleware.TokenName)\n\tif !ok {\n\t\tlogging.SystemError(\"Token wasn't found in the context\")\n\t\treturn\n\t}\n\ttoken := iface.(string)\n\n\treqContext := getRequestContext(c)\n\n\t//put all events to write-ahead-log if idle\n\tif appstatus.Instance.Idle.Load() {\n\t\teh.writeAheadLogService.Consume(eventsArray, reqContext, token, eh.processor.Type())\n\t\tc.JSON(http.StatusOK, middleware.OKResponse())\n\t\treturn\n\t}\n\n\terr = eh.multiplexingService.AcceptRequest(eh.processor, reqContext, token, eventsArray)\n\tif err != nil {\n\t\tcode := http.StatusBadRequest\n\t\tif err == multiplexing.ErrNoDestinations {\n\t\t\tcode = http.StatusUnprocessableEntity\n\t\t\terr = fmt.Errorf(noDestinationsErrTemplate, token)\n\t\t}\n\n\t\treqBody, _ := json.Marshal(eventsArray)\n\t\tlogging.Warnf(\"%v. Event: %s\", err, string(reqBody))\n\t\tc.JSON(code, middleware.ErrResponse(err.Error(), nil))\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, EventResponse{Status: \"ok\", DeleteCookie: !reqContext.CookiesLawCompliant})\n}", "func (srhree StatelessReplicaHealthReportExpiredEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (audce ApplicationUpgradeDomainCompleteEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}", "func (ace ApplicationCreatedEvent) AsServiceEvent() (*ServiceEvent, bool) {\n\treturn nil, false\n}" ]
[ "0.6438354", "0.60353184", "0.6000109", "0.59321505", "0.5768451", "0.5756071", "0.57459855", "0.5693179", "0.56273997", "0.5607155", "0.55602217", "0.5532839", "0.55267197", "0.5525084", "0.55238265", "0.5508955", "0.55087966", "0.5476726", "0.54726946", "0.5445884", "0.5440322", "0.543841", "0.5435813", "0.5411799", "0.5398332", "0.53928304", "0.53899723", "0.53896713", "0.5379609", "0.5349301", "0.53360736", "0.53328806", "0.533266", "0.53123", "0.5305742", "0.5294629", "0.52741396", "0.52717847", "0.52491105", "0.5240598", "0.52323097", "0.5231941", "0.52291906", "0.52190024", "0.5202233", "0.51995605", "0.51892734", "0.5179087", "0.51786864", "0.5173471", "0.51636887", "0.5159741", "0.5158682", "0.5158362", "0.5153299", "0.5143341", "0.5135967", "0.5127981", "0.5125675", "0.51152813", "0.5113076", "0.5111757", "0.5108454", "0.51074094", "0.5097415", "0.5096798", "0.50930816", "0.5091428", "0.50839853", "0.50808126", "0.50762105", "0.5075662", "0.5064856", "0.50584865", "0.5058142", "0.5052331", "0.5052141", "0.5047749", "0.5047058", "0.5045614", "0.5042902", "0.5041764", "0.5039452", "0.5035774", "0.5030962", "0.50273275", "0.50262666", "0.5025196", "0.5024837", "0.50205576", "0.50144815", "0.5013234", "0.5008395", "0.5006212", "0.5005693", "0.49987504", "0.49922675", "0.49912995", "0.49889308", "0.49807018" ]
0.74734116
0
Hash function to take key block data and return a SHA256 hash as a string
func calculateHash(block Block) string { // Time and vehicle identifier (v5c) are the key block items to generate the hash record := string(string(block.Index) + block.Timestamp + block.Event.PerformedOnVehicle.V5c + block.PrevHash) h := sha256.New() h.Write([]byte(record)) hashed := h.Sum(nil) return hex.EncodeToString(hashed) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func calculateHash (block Block) string{\n h := sha256.New()\n unique := block.Data + block.PrevHash + block.TimeStamp + strconv.Itoa(block.Nonce)\n h.Write([]byte(unique))\n \n return hex.EncodeToString(h.Sum(nil))\n}", "func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}", "func calculateHash(block Block) string {\n\trecord := strconv.Itoa(block.Index) + block.Timestamp + strconv.Itoa(block.Key) + block.PrevHash\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}", "func KeyHash(s string) string {\n\tif len(s) > 100 {\n\t\ts = s[:100]\n\t}\n\td := sha256.Sum256([]byte(s))\n\treturn hex.EncodeToString(d[:])[:12]\n}", "func HashBlock(block *Block) string {\n if block == nil {\n return \"0000000000000000000000000000000000000000000000000000000000000000\"\n }\n\n // This function converts the block to bytes by writing the fields into a Buffer,\n // then sending the Buffer contents to an sha256 object. We do it this way so it\n // is easy to examine the bytes by printing the Buffer contents.\n\n buf := new(bytes.Buffer)\n\n // Write the PrevHash field\n binPrevBlockHash, err := hex.DecodeString(block.PrevHash)\n if err != nil { panic(\"Error decoding block.PrevHash\") }\n buf.Write(binPrevBlockHash)\n\n // Write the Height field\n err = binary.Write(buf, binary.LittleEndian, block.Height)\n if err != nil { panic(\"Error writing block.Height\") }\n\n // Done writing fields, get the Buffer contents\n blockBytes := buf.Bytes()\n\n // Uncomment one of these statements to print out the bytes\n // fmt.Printf(\"%s\\n\", hex.Dump(blockBytes)) // Pretty hex dump format\n // fmt.Printf(\"%s\\n\", hex.EncodeToString(blockBytes)) // Mashed-together characters format\n\n // Compute the hash of blockBytes using the sha256 cryptographic hash algorithm\n hasher := sha256.New()\n hasher.Write(blockBytes)\n hash := hex.EncodeToString(hasher.Sum(nil))\n\n // Uncomment this statement to print out the hash\n // fmt.Printf(\"The hash of these bytes is %s\\n\", hash)\n\n return hash\n}", "func blockHash(block Block) [32]byte {\n\tblockmarshal, _ := json.Marshal(block)\n\tsha := sha256.Sum256(blockmarshal)\n\treturn sha\n}", "func (s *DHT) hashKey(data []byte) []byte {\n\tsha := sha3.Sum256(data)\n\treturn sha[:]\n}", "func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}", "func Sha256Hash(password string) string {\n h := sha256.Sum256([]byte(password))\n return \"{SHA256}\" + base64.StdEncoding.EncodeToString(h[:])\n}", "func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}", "func hashKey(b []byte) string {\n\th := sha1.New() // #nosec G401 Used only to generate random value to be used to generate hash string\n\t_, err := h.Write(b)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to hash key with error:\", err)\n\t}\n\n\treturn string(h.Sum(nil))\n}", "func Hash(v []byte) string {\n\th := sha256.Sum256(v)\n\treturn hex.EncodeToString(h[:])\n}", "func (hasher *SHA256) HashKey() string {\n\treturn \"\"\n}", "func Hash(data ...[]byte) []byte {\n\treturn crypto.Keccak256(data...)\n}", "func calcHash(data string) string {\n\th := sha256.New()\n\th.Write([]byte(data))\n\thash := fmt.Sprintf(\"%x\", h.Sum(nil))\n\treturn hash\n}", "func calculateBlockHash(block Block) string {\n\trecord := string(rune(block.Index)) + block.Timestamp + string(rune(block.BPM)) + block.PrevHash\n\treturn calculateHash(record)\n}", "func Hash(data []byte) []byte {\n\treturn hash.SHA256(data)\n}", "func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}", "func Hashbin(tox string) []byte {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n return bs \n}", "func calculateHash(block Block) []byte {\n\tbVersion := util.Uinttobyte(block.Version)\n\tbNonce := util.Uinttobyte(block.Nonce)\n\tbDifficulty := util.Uinttobyte(block.Difficulty)\n\n\trecord := []byte{}\n\trecord = append(record, bVersion[:]...)\n\trecord = append(record, block.PrevHash[:]...)\n\trecord = append(record, bNonce[:]...)\n\trecord = append(record, []byte(block.Timestamp)[:]...)\n\trecord = append(record, bDifficulty[:]...)\n\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\t//fmt.Println(hex.EncodeToString(hashed))\n\treturn hashed\n}", "func calculateBlockHash(Term int, Index int, idx int, Timestamp string,BPM string, prevHash string, validator string) string {\nrecord := string(Index) + Timestamp + string(BPM) + prevHash + string(idx) + string(Term) + validator\nreturn calculateHash(record)\n}", "func TestHashString(t *testing.T) {\n\t// Block 100000 hash.\n\twantStr := \"000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506\"\n\thash := Hash([HashSize]byte{ // Make go vet happy.\n\t\t0x06, 0xe5, 0x33, 0xfd, 0x1a, 0xda, 0x86, 0x39,\n\t\t0x1f, 0x3f, 0x6c, 0x34, 0x32, 0x04, 0xb0, 0xd2,\n\t\t0x78, 0xd4, 0xaa, 0xec, 0x1c, 0x0b, 0x20, 0xaa,\n\t\t0x27, 0xba, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t})\n\n\thashStr := hash.String()\n\tassert.Equal(t, wantStr, hashStr)\n}", "func CalcHash(data string) string {\r\n\thashed := sha256.Sum256([]byte(data))\r\n\treturn hex.EncodeToString(hashed[:])\r\n}", "func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}", "func GenerateSHA256Hash() string {\n\tkey := getSecretPhrase()\n\thasher := sha256.New()\n\thasher.Write([]byte(key))\n\n\tactual, err := strkey.Encode(strkey.VersionByteHashX, hasher.Sum(nil))\n\tif err != nil {\n\t\tpanic(err);\n\t\t//LOGGER.Fatal(err)\n\t\treturn \"\"\n\t}\n\treturn actual\n}", "func SHA256Hash(data []byte) []byte {\n\tsum := sha256.Sum256(data)\n\treturn sum[:]\n}", "func encodeKeyHash(verPublicKeyHash []byte, checkSum []byte) string {\n\n\ts := \"START encodeKeyHash() - Encodes verPublicKeyHash & checkSum\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\t// 7 - CONCAT\n\taddressHex := append(verPublicKeyHash, checkSum...)\n\ts = \"7 - CONCAT \" + hex.EncodeToString(addressHex)\n\tlog.Info(\"WALLET: GUTS \" + s)\n\n\t// 8 - BASE58 ENCODING\n\tjeffCoinAddressHex := base58.Encode(addressHex)\n\ts = \"8 - BASE58 ENCODING \" + jeffCoinAddressHex\n\tlog.Info(\"WALLET: GUTS \" + s)\n\n\ts = \"END encodeKeyHash() - Encodes verPublicKeyHash & checkSum\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn jeffCoinAddressHex\n\n}", "func Hash(length int, key string) int64 {\n\tif key == \"\" {\n\t\treturn 0\n\t}\n\thc := hashCode(key)\n\treturn (hc ^ (hc >> 16)) % int64(length)\n}", "func hashKey(b []byte) string {\n\th := sha1.New()\n\t_, err := h.Write(b)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to hash key with error:\", err)\n\t}\n\n\treturn string(h.Sum(nil))\n}", "func TestHash(t *testing.T) {\n\tdata := \"bce-auth-v1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/2015-04-27T08:23:49Z/1800\"\n\tkey := \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n\tresult := \"1d5ce5f464064cbee060330d973218821825ac6952368a482a592e6615aef479\"\n\ttestResult := hash(data, key)\n\tif result == testResult {\n\t\tt.Log(\"hash test success\")\n\t} else {\n\t\tt.Error(\"hash test fail\")\n\t}\n}", "func sliceKeyHash(k []byte) string {\n\tif k == nil {\n\t\treturn \"\"\n\t}\n\n\th := sha256.New()\n\t_, _ = h.Write(k)\n\treturn hex.EncodeToString(h.Sum(nil))[:6]\n}", "func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func newSHA256() hash.Hash { return sha256.New() }", "func calculateHash(index int, previousHash string, timestamp int64, data transaction.Transaction) string {\n\tvar foo = strconv.Itoa(index) + string(previousHash) + strconv.Itoa(int(timestamp)) + hex.EncodeToString(data.Id)\n\tinput :=strings.NewReader(foo)\n\tvar newHash = sha256.New()\n\tif _, err := io.Copy(newHash, input); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn hex.EncodeToString(newHash.Sum(nil))\n}", "func op_BLOCKHASH(pc *uint64, in *interpreter, ctx *callCtx) uint64 {\n\tnum := ctx.stack.Peek()\n\tnum64, overflow := num.Uint64WithOverflow()\n\tif overflow {\n\t\tnum.Clear()\n\t}\n\tvar upper, lower uint64\n\tupper = in.evm.block.NumberU64()\n\tif upper < 257 {\n\t\tlower = 0\n\t} else {\n\t\tlower = upper - 256\n\t}\n\tif num64 >= lower && num64 < upper {\n\t\tnum.SetBytes(in.evm.block.Hash().Bytes())\n\t} else {\n\t\tnum.Clear()\n\t}\n\treturn 0\n}", "func SHA256(raw []byte) Hash {\n\treturn gosha256.Sum256(raw)\n}", "func blockHashKey(number uint64) []byte {\n\treturn append(append(blockPrefix, encodeBlockNumber(number)...), blockHashSuffix...)\n}", "func CalculateHash(pBlock Block) string {\n\tbHeader := strconv.Itoa(pBlock.Nonce) + pBlock.Timestamp.String() + pBlock.HashPreviousBlock\n\tHash := sha256.New()\n\tHash.Write([]byte(bHeader))\n\treturn hex.EncodeToString(Hash.Sum(nil))\n}", "func calculateBlockHash(block Block) string {\n\trecord := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash\n\treturn calculateHash(record)\n}", "func calculateBlockHash(block Block) string {\n\trecord := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash\n\treturn calculateHash(record)\n}", "func Hash(data []byte) []byte {\n\th := sha256.Sum256(data)\n\treturn types.ByteSlice(h[:])\n}", "func hash(f []byte) (string, error) {\n\tsha := sha256.New()\n\t_, err := sha.Write(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha.Sum(nil)), nil\n}", "func GetHash(b string) (hash string) {\n\t// Hash input b and capture/format its output as a string literal\n\thash = fmt.Sprintf(\"%X\", sha256.Sum256([]byte(b)[:]))\n\treturn\n}", "func Hash(key string) uint32 {\n\treturn uint32(aeshashstr(noescape(unsafe.Pointer(&key)), 0))\n}", "func Hash(src string, secret string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(src))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func (p BnetAuthCheckPacket) KeyHash(index int) string {\n\tconst keyOffset = 24\n\tconst keyLen = 4 * 9\n\toffset := keyOffset + index*keyLen + 8\n\thashBytes := p[offset : offset+4]\n\treturn hex.EncodeToString(hashBytes)\n}", "func Sha256Hash(data []byte) [32]byte {\n\tsum := sha256.Sum256(data)\n\treturn sum\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func Hash(input []byte) (out []byte) {\n\thash := sha256.New()\n\thash.Write(input)\n\treturn hash.Sum(nil)\n}", "func SHA256(text string) string {\n\talgorithm := sha256.New()\n\treturn stringHasher(algorithm, text)\n}", "func (b *Block) CalculateHash() (BlockID, error) {\n var err error\n hash := sha256.New()\n /*err := binary.Write(hash, binary.LittleEndian, int32(b.Index))\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }*/\n for _, val := range []uint32{b.Version, b.Bits} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n for _, val := range []uint64{b.Nonce, b.Timestamp} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n\n hash.Write(b.PrevBlock)\n hash.Write([]byte(b.PublicKey))\n hash.Write(b.Data)\n buf := hash.Sum(nil)\n return buf, nil\n}", "func (b BlockChain) Hash() {\n\n}", "func (bc *Blockchain) HashBlock(block Block) string {\n var hash = sha256.New()\n hash.Write([]byte(strconv.Itoa(block.Index) +\n time.Unix(block.Timestamp, 0).Format(time.UnixDate) +\n strconv.Itoa(block.Proof) +\n block.PreviousHash +\n block.Difficulty))\n hashed := hash.Sum(nil)\n return hex.EncodeToString(hashed)\n}", "func Hash(data []byte) [blake2b.Size]byte {\n\treturn blake2b.Sum512(data)\n}", "func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}", "func computeHash(w http.ResponseWriter, req *http.Request) {\n\tvalues := req.URL.Query()\n\tdata := values.Get(\"data\")\n\tif data == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - data param not present\"))\n\t\treturn\n\t}\n\tsalt := values.Get(\"salt\")\n\tif salt == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - salt param not present\"))\n\t\treturn\n\t}\n\th := sha256.Sum256([]byte(data+salt))\n\tencodedStr := hex.EncodeToString(h[:])\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(encodedStr))\n}", "func (bc BucketConfig) hash() string {\n\tsource := strings.ToLower(bc.Name + \"/\" + bc.Endpoint)\n\thash := sha1.Sum([]byte(source))\n\treturn strings.ToLower(hex.EncodeToString(hash[0:6]))\n}", "func Hash(s string) string {\n\tfmt.Println(\"Hashing string:\", s)\n\thash := sha256.Sum256([]byte(s))\n\tniceHash := fmt.Sprintf(\"%x\", hash)\n\tfmt.Println(\"Created hash:\", hash)\n\treturn niceHash\n}", "func GetSHA256Hash(text string) string {\n\thasher := sha256.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func hash(key uint64) uint64 {\r\n\tkey ^= key >> 33\r\n\tkey *= 0xff51afd7ed558ccd\r\n\tkey ^= key >> 33\r\n\tkey *= 0xc4ceb9fe1a85ec53\r\n\tkey ^= key >> 33\r\n\treturn key\r\n}", "func ByteHash(data ...[]byte) []byte {\n\n\thw := sha3.NewKeccak256()\n\tfor _, d := range data {\n\t\thw.Write(d)\n\t}\n\thash := hw.Sum(nil)\n\treturn hash\n}", "func (bc *Blockchain) Hash() {\n\n}", "func hash(path string) string {\n\th, err := files.Sha256(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn h[:10]\n}", "func ComputeHash(body []byte) string {\n\th := md5.New()\n\th.Write(body)\n\th.Write(kSecret)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func Keccak256Hash(data []byte) []byte {\n\tb := sha3.Sum256(data)\n\treturn b[:]\n}", "func TestHash(t *testing.T) {\n\t// Hash of block 234439.\n\tblockHashStr := \"14a0810ac680a3eb3f82edc878cea25ec41d6b790744e5daeef\"\n\tblockHash, err := NewHashFromStr(blockHashStr)\n\tassert.NoError(t, err)\n\n\t// Hash of block 234440 as byte slice.\n\tbuf := []byte{\n\t\t0x79, 0xa6, 0x1a, 0xdb, 0xc6, 0xe5, 0xa2, 0xe1,\n\t\t0x39, 0xd2, 0x71, 0x3a, 0x54, 0x6e, 0xc7, 0xc8,\n\t\t0x75, 0x63, 0x2e, 0x75, 0xf1, 0xdf, 0x9c, 0x3f,\n\t\t0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t}\n\n\thash, err := NewHash(buf)\n\tassert.NoError(t, err)\n\n\t// Ensure proper size.\n\tassert.Equal(t, HashSize, len(hash))\n\n\t// Ensure contents match.\n\tassert.Equal(t, buf[:], hash[:])\n\n\t// Ensure contents of hash of block 234440 don't match 234439.\n\tassert.False(t, hash.IsEqual(blockHash))\n\n\t// Set hash from byte slice and ensure contents match.\n\terr = hash.SetBytes(blockHash.CloneBytes())\n\tassert.NoError(t, err)\n\tassert.True(t, hash.IsEqual(blockHash))\n\n\t// Ensure nil hashes are handled properly.\n\tassert.True(t, (*Hash)(nil).IsEqual(nil))\n\n\tassert.False(t, hash.IsEqual(nil))\n\n\t// Invalid size for SetBytes.\n\terr = hash.SetBytes([]byte{0x00})\n\tassert.NotNil(t, err)\n\n\t// Invalid size for NewHash.\n\tinvalidHash := make([]byte, HashSize+1)\n\t_, err = NewHash(invalidHash)\n\tassert.NotNil(t, err)\n\n\tif err == nil {\n\t\tt.Errorf(\"NewHash: failed to received expected err - got: nil\")\n\t}\n}", "func EncryptSHA256(text string) string {\n h := sha256.New()\n h.Write([]byte(text))\n s := base64.URLEncoding.EncodeToString(h.Sum(nil))\n return (s)\n}", "func hash(path string) string {\n\th, err := files.Sha256(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn h[:10]\n}", "func blockHash(x uint64) uint32 {\n\tconst prime6bytes = 227718039650203\n\tx &= 1<<40 - 1\n\treturn uint32((x * prime6bytes) >> (64 - hashLog))\n}", "func StandardHash(b []byte) []byte {\n\t// I'm not sure if the blspy hash256 does anything special. I'm going to\n\t// have it create a regular SHA 256 hash.\n\t//\n\t// return bytes32(blspy.Util.hash256(bytes(b)))\n\n\thasher := sha256.New()\n\thasher.Write(b)\n\n\treturn hasher.Sum(nil)\n}", "func Sha256Hash(file io.Reader) (string, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tif _, err := io.Copy(buf, file); err != nil {\n\t\tlog.Println(\"Failed to copy file to buffer in hashing function...\")\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(buf.Bytes())\n\n\tsha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))\n\n\treturn sha, nil\n}", "func RawHash(data interface{}) []byte {\n\tvar databuf []byte\n\tswitch dataImpl := data.(type) {\n\tcase []byte:\n\t\tdatabuf = dataImpl\n\tcase HashBytes:\n\t\tdatabuf = dataImpl[:]\n\tcase string:\n\t\tdatabuf = []byte(dataImpl)\n\tdefault:\n\t\tpanic(\"unknown type\")\n\t}\n\thash := sha3.New256()\n\thash.Write(databuf)\n\tvar buf []byte\n\treturn hash.Sum(buf)\n}", "func SHA256(s string) string {\n\treturn stringHasher(sha256.New(), s)\n}", "func Hash256(pass string, salt string) string {\n\tcombined_bytes := []byte(pass + salt)\n\thash_bytes := hasher256.Sum(combined_bytes)\n\treturn hex.EncodeToString(hash_bytes)\n}", "func Hash(data interface{}) string {\n\treturn hex.EncodeToString(RawHash(data))\n}", "func keyHash(k crypto.Key) ([]byte, error) {\n\tkb, err := k.Bytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, _ := mh.Sum(kb, mh.SHA2_256, -1)\n\treturn []byte(h), nil\n}", "func hash(key string) int{\n\tvar num = 0\n\t// get the lenght of the key\n\tvar length = len(key)\n\n\t// add the ascii character value to creat a sum \n\tfor i := 0; i < length; i++{\n\n\t\tnum += int(key[i])\n\t}\n\t\n\t// square in the middle hash method\n\tvar avg = num * int((math.Pow(5.0, 0.5) - 1)) / 2\n\tvar numeric = avg - int(math.Floor(float64(avg)))\n\n\n\t// hash value to place into the table slice between -1 and CAPACITY - 1\n\treturn int(math.Floor(float64(numeric * CAPACITY)))\n}", "func (block *Block) Hash() string {\n\tvar hashStr string\n\n\thashStr = string(block.Header.Height) + string(block.Header.Timestamp) + string(block.Header.ParentHash) +\n\t\tstring(block.Value.Root) + string(block.Header.Size) + block.Header.Nonce\n\n\tsum := sha3.Sum256([]byte(hashStr))\n\treturn \"HashStart_\" + hex.EncodeToString(sum[:]) + \"_HashEnd\"\n}", "func Keccak256Hash(data ...[]byte) (h common.Hash) {\n\td := sha3.NewLegacyKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}", "func (blk Block) CalcHash() []byte {\n\t// TODO\n\n\tprevHashStr := hex.EncodeToString(blk.PrevHash)\n\tgen := blk.Generation\n\tdif := blk.Difficulty\n\tdata := blk.Data\n\tprf := blk.Proof\n\n\thashStr := fmt.Sprintf(\"%s:%d:%d:%s:%d\", prevHashStr, gen, dif, data, prf)\n\n\thash := sha256.New()\n\n\thash.Write([]byte(hashStr))\n\n\treturn hash.Sum(nil)\n}", "func hashBlock(s []byte) uint32 {\n\tvar b [4]byte\n\tswitch len(s) {\n\tcase 3:\n\t\tb[2] = s[2]\n\t\tb[1] = s[1]\n\t\tb[0] = s[0]\n\tdefault:\n\t\tb[0] = 0 // for set breakpoint\n\t}\n\ti := binary.LittleEndian.Uint32(b[:])\n\treturn i\n}", "func makeBlockHash(block Block) string {\n\thash := sha512.New()\n\thash.Write([]byte(strconv.FormatInt(block.Index, 10) + block.Timestamp.String() + block.HashPoW + block.textNoncePoW + block.PrevHashHeader + block.payload))\n\thashHeader := hex.EncodeToString(hash.Sum(nil))\n\treturn hashHeader\n}", "func Key(hash *chainhash.Hash) [gcs.KeySize]byte {\n\tvar key [gcs.KeySize]byte\n\tcopy(key[:], hash[:])\n\treturn key\n}", "func Keccak256Hash(data ...[]byte) (h common.Hash) {\n\td := sha3.NewKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}", "func Keccak256Hash(data ...[]byte) (h common.Hash) {\n\td := sha3.NewKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}", "func Sha256d(input []byte) Hash {\n sha := sha256.New()\n sha.Write(input)\n intermediate := sha.Sum(nil)\n sha.Reset()\n sha.Write(intermediate)\n hash, err := HashFromBytes(sha.Sum(nil), LittleEndian)\n if err != nil {\n panic(\"impossible flow, this is a bug: \" + err.Error())\n }\n return hash\n}", "func CalculateHash(args []string) string {\n\tvar str = \"\"\n\tfor _,v := range args {\n\t\tstr += v\n\t}\n\thasher := sha256.New()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func (authSvc *AuthService) computeHash(s string) hash.Hash {\n\t\n\tvar hash hash.Hash = sha256.New()\n\tvar bytes []byte = []byte(s)\n\thash.Write(authSvc.secretSalt)\n\thash.Write(bytes)\n\treturn hash\n}", "func getSHA256Sum(data []byte) []byte {\n\thash := sha256.New()\n\thash.Write(data)\n\treturn hash.Sum(nil)\n}", "func Keccak256Hash(data ...[]byte) (h Hash) {\n\td := sha3.NewKeccak256()\n\tfor _, b := range data {\n\t\td.Write(b)\n\t}\n\td.Sum(h[:0])\n\treturn h\n}", "func Hash(b []byte, seed uint64) uint64", "func Hash(key []byte) uint64 {\n\treturn murmur3.Sum64(key)\n}", "func (b *Block) createHash() string {\n\td := fmt.Sprintf(\"%v%v%v%v\", b.Index, b.PrevHash, b.Date, b.Data)\n\th := sha256.New()\n\th.Write([]byte(d))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func Hash(mdfcge []byte) [32]byte {\n\treturn sha256.Sum256(mdfcge)\n}", "func hashBytes(input ...interface{}) []byte {\n\tvar combine []string\n\tfor _, v := range input {\n\t\tif x, ok := v.([]byte); ok {\n\t\t\tv = string(x)\n\t\t}\n\t\tcombine = append(combine, fmt.Sprintf(\"%v\", v))\n\t}\n\tsum := sha256.Sum256([]byte(strings.Join(combine[0:], NONE)))\n\tvar output []byte\n\toutput = append(output[0:], sum[0:]...)\n\treturn output\n}", "func ComputeSHA256(data []byte) (hash []byte) {\r\n\treturn util.ComputeSHA256(data)\r\n}" ]
[ "0.74991125", "0.72448534", "0.71867824", "0.7152402", "0.70672005", "0.7050035", "0.7008327", "0.694254", "0.6933465", "0.6855276", "0.6829969", "0.6821539", "0.68141586", "0.6776146", "0.67583466", "0.67563283", "0.67516357", "0.6748018", "0.67467165", "0.67405146", "0.6731204", "0.6723564", "0.672043", "0.67037517", "0.66871405", "0.66792756", "0.66682196", "0.66626537", "0.66560245", "0.66283697", "0.6618042", "0.66138667", "0.66080666", "0.65977305", "0.6588555", "0.65664935", "0.6565195", "0.65651935", "0.65566605", "0.65540123", "0.6549753", "0.6549753", "0.654859", "0.65449077", "0.6536966", "0.6514848", "0.6514611", "0.65115565", "0.65101576", "0.6493755", "0.6493755", "0.6493755", "0.6480543", "0.6472524", "0.6469549", "0.6469077", "0.64688754", "0.64665824", "0.6465642", "0.6462879", "0.6460036", "0.6459254", "0.6456201", "0.6447223", "0.6432388", "0.64245737", "0.6424037", "0.6401672", "0.63993365", "0.63934577", "0.63913596", "0.6389792", "0.63789254", "0.63685894", "0.63683444", "0.63649553", "0.63633966", "0.63616335", "0.63469976", "0.63459504", "0.6341467", "0.63354254", "0.63263893", "0.6326348", "0.6320066", "0.63169444", "0.631517", "0.6314913", "0.6314913", "0.6313418", "0.631121", "0.6305314", "0.6304716", "0.63013846", "0.6298394", "0.6286596", "0.6279446", "0.6276335", "0.62733203", "0.6267532" ]
0.72586614
1
generateGenesisBlock will create the first block
func generateGenesisBlock() Block { var genesisBlock Block var genesisRecord ServiceEvent var genesisRecordEventDescription EventDescription var genesisRecordEventDescriptionType EventType var genesisRecordVehicle Vehicle var genesisRecordGarage Garage // Seed values for Garage, Vehicle, EventType and EventDescription genesisRecordGarage.GarageId = 0 genesisRecordGarage.Location = "genesis location" genesisRecordGarage.Name = "genesis inc." genesisRecordGarage.Owner = "genesis and co." genesisRecordGarage.Type = "main dealer" genesisRecordVehicle.V5c = "63ne515" genesisRecordVehicle.VehicleColour = append(genesisRecordVehicle.VehicleColour, "starting colour") genesisRecordVehicle.VehicleMake = "genesis make" genesisRecordVehicle.VehicleModel = "genesis model" genesisRecordVehicle.VehicleRegistration = append(genesisRecordVehicle.VehicleRegistration, "GEN 351 S") genesisRecordEventDescriptionType.EventId = 0 genesisRecordEventDescriptionType.EventDescription = "genesis event" genesisRecordEventDescription.EventItem = append(genesisRecordEventDescription.EventItem, genesisRecordEventDescriptionType) genesisRecordEventDescription.VehicleMilage = 10000000 // Pull all the objects into ServiceEvent genesisRecord.EventAuthorisor = "Created by serviceChain as the Genesis Block" genesisRecord.EventDetails = genesisRecordEventDescription genesisRecord.Identifier = 1 genesisRecord.PerformedBy = genesisRecordGarage genesisRecord.PerformedOnVehicle = genesisRecordVehicle // Set the values for the Block genesisBlock.Index = 1 genesisBlock.Hash = "0" genesisBlock.PrevHash = "0" genesisBlock.Timestamp = time.Now().String() genesisBlock.Event = genesisRecord blockString, err := json.MarshalIndent(genesisBlock, "", "\t") if err != nil { log.Println("INFO: serviceChain.createGenesisBlock(): Problem creating the JSON output of the genesis block. Continuing...") } log.Println("INFO: serviceChain.generateGenesisBlock(): Created block with contents: " + string(blockString)) return genesisBlock }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *Block) CreateGenesisBlock() {\n\n header := Header{0, int64(time.Now().Unix()), \"GenesisBlock\", \"\", 0, \"\"}\n b.Mpt = p1.GetMPTrie()\n b.Header = header\n}", "func CreateGenesisBlock(creator *wallet.Wallet) (bl Block, tx Transaction) {\n\tbl.Header.PrevBlockHash = [constants.HASHSIZE]byte{0}\n\tbl.Header.Tstamp = uint64(time.Now().Unix())\n\tbl.Header.Target = 230\n\tbl.Header.Noncetry = 0\n\tbl.blockchainlength = 0\n\n\ttx.Meta.TimePrepared = int64(100) //time.Now().Unix()\n\ttx.Meta.Pubkey = creator.Keys[0].PublicKey\n\ttx.Meta.Address = creator.Address[0]\n\ttx.Inputs = make([]Input, 1)\n\ttx.Outputs = make([]Output, 1)\n\ttx.Inputs[0].OutIdx = 0\n\tcopy(tx.Inputs[0].PrevTransHash[:], []byte(\"Tutturu!\"))\n\ttx.Outputs[0].Amount = 100\n\ttx.Outputs[0].Addr = creator.Address[0]\n\ttx.Outputs[0].Signature = tx.Outputs[0].GenSignature(creator.Keys[0])\n\ttx.SetHash()\n\n\tbl.Txs = make([][constants.HASHSIZE]byte, 1)\n\tbl.Txs[0] = tx.Hash\n\ttotalTxSize := 0\n\tfor _, tx := range bl.Txs {\n\t\ttxSize := len(tx)\n\t\ttotalTxSize += txSize\n\t}\n\n\ttotalTxSize += bl.HeaderSize()\n\tfulltxs := [][constants.HASHSIZE]byte{tx.Hash}\n\tbl.Header.TransHash = Merkleify(fulltxs)\n\tbl.blocksize = uint64(totalTxSize)\n\tbl.transCnt = uint32(len(bl.Txs))\n\tbl.SetHash(mine(creator, bl))\n\tcreator.ClaimedTxs = append(creator.ClaimedTxs, tx.Hash)\n\n\treturn\n}", "func makeGenesisBlock() Block {\n\ttext := \"Welcome to this Go-Blockchain!\"\n\tblock := Block{}\n\n\t//Find suitable hash\n\tblock.HashPoW, block.textNoncePoW = \"0\", \"0\"\n\n\t//Define Header elements\n\tblock.Index = 0\n\tblock.Timestamp = time.Now()\n\tblock.PrevHashHeader = \"0\"\n\n\t//make hash of Header elements\n\tblock.blockHash = makeBlockHash(block)\n\n\t//Define Data\n\tblock.payload = text\n\treturn block\n}", "func GenesisBlock() Block {\n\tnewBlock := Block{\n\t\ttimestamp: time.Date(1, 1, 1, 1, 1, 1, 1, time.Local),\n\t\tdata: Data(\"genesis\"),\n\t}\n\tnewBlock.hash()\n\n\treturn newBlock\n}", "func CreateGenesisBlock() *Block {\n\ttimeStamp := generateTimeStamp()\n\tdata := \"GENESIS BLOCK\"\n\thash := \"3e7f6189598ac7cdd024f5d07b1fb1fd18e1ce68a3986d44b36b97c2ecded8e0\"\n\n\treturn &Block{\n\t\tID: generateUUID(),\n\t\tIndex: 0,\n\t\tTimestamp: timeStamp,\n\t\tData: data,\n\t\tHash: hash,\n\t\tPreviousHash: \"\",\n\t}\n}", "func (g *Genesis) GenesisBlock(ledger *storages.LedgerStoreImp) error {\n\tass, txs := g.genFirst()\n\t//todo hello world msg\n\tblock := &types.Block{\n\t\tHeader: &types.Header{\n\t\t\tHeight: 1,\n\t\t\tVersion: 0x01,\n\t\t\tPrevBlockHash: common.Hash{},\n\t\t\tLeagueRoot: common.Hash{},\n\t\t\tReceiptsRoot: common.Hash{},\n\t\t\tStateRoot: ass.GetHashRoot(),\n\t\t\tTxRoot: txs.GetHashRoot(),\n\t\t\tTimestamp: g.Config.Timestamp,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tblkInfo := &VbftBlockInfo{}\n\tblkInfo.VrfValue = []byte(\"1c9810aa9822e511d5804a9c4db9dd08497c31087b0daafa34d768a3253441fa20515e2f30f81741102af0ca3cefc4818fef16adb825fbaa8cad78647f3afb590e\")\n\tblkInfo.VrfProof = []byte(\"c57741f934042cb8d8b087b44b161db56fc3ffd4ffb675d36cd09f83935be853d8729f3f5298d12d6fd28d45dde515a4b9d7f67682d182ba5118abf451ff1988\")\n\tblock.Header.ConsensusPayload, _ = json.Marshal(blkInfo)\n\tblockInfo := &storages.BlockInfo{\n\t\tBlock: block,\n\t\tAccountStates: ass,\n\t\tGasDestroy: big.NewInt(0),\n\t}\n\terr := ledger.SaveAll(blockInfo)\n\treturn err\n}", "func NewGenesisBlock() *Block {\n\tidea := &Idea{Text: \"Create IdeaBlox\", Author: \"aakarim\"}\n\tout, err := proto.Marshal(idea)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn NewBlock(out, []byte{})\n}", "func NewGenesisBlock() *Block {\n\treturn NewBlock(\"William Keylon\", []byte{})\n}", "func NewGenesisBlock() *Block {\n\treturn NewBlock(\"Genesis\", []byte{})\n}", "func TestGenesisBlock(t *testing.T) {\n\tdoReal(t, \"Live\", block.LiveGenesisDigest, block.LiveGenesisBlock)\n\tdoReal(t, \"Test\", block.TestGenesisDigest, block.TestGenesisBlock)\n}", "func (g *testGenerator) createPremineBlock(blockName string, additionalAmount dcrutil.Amount) *wire.MsgBlock {\n\tcoinbaseTx := wire.NewMsgTx()\n\tcoinbaseTx.AddTxIn(&wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: 0, // Updated below.\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\t// Add each required output and tally the total payouts for the coinbase\n\t// in order to set the input value appropriately.\n\tvar totalSubsidy dcrutil.Amount\n\tfor _, payout := range g.params.BlockOneLedger {\n\t\tpayoutAddr, err := dcrutil.DecodeAddress(payout.Address, g.params)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tpkScript, err := txscript.PayToAddrScript(payoutAddr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcoinbaseTx.AddTxOut(&wire.TxOut{\n\t\t\tValue: payout.Amount + int64(additionalAmount),\n\t\t\tVersion: 0,\n\t\t\tPkScript: pkScript,\n\t\t})\n\n\t\ttotalSubsidy += dcrutil.Amount(payout.Amount)\n\t}\n\tcoinbaseTx.TxIn[0].ValueIn = int64(totalSubsidy)\n\n\t// Generate the block with the specially created regular transactions.\n\treturn g.nextBlock(blockName, nil, nil, func(b *wire.MsgBlock) {\n\t\tb.Transactions = []*wire.MsgTx{coinbaseTx}\n\t})\n}", "func (_EthCrossChain *EthCrossChainTransactor) InitGenesisBlock(opts *bind.TransactOpts, _rawHeader []byte, _pubKeyList []byte) (*types.Transaction, error) {\n\treturn _EthCrossChain.contract.Transact(opts, \"InitGenesisBlock\", _rawHeader, _pubKeyList)\n}", "func (c *Client) CreateGenesisBlock(r *onet.Roster, msg *CreateGenesisBlock) (*CreateGenesisBlockResponse, error) {\n\treply := &CreateGenesisBlockResponse{}\n\tif err := c.SendProtobuf(r.List[0], msg, reply); err != nil {\n\t\treturn nil, err\n\t}\n\treturn reply, nil\n}", "func generateBlock(previousBlock Block, BPM int, address string) (Block, error) {\n\n\tnewBlock := Block{\n\t\tIndex: previousBlock.Index + 1,\n\t\tTimestamp: time.Now().String(),\n\t\tBPM: BPM,\n\t\tPrevHash: previousBlock.Hash,\n\t}\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func CreateGenesisBlock(coinbase *Transaction) *Block {\n\treturn CreateBlock([]*Transaction{coinbase}, []byte{})\n}", "func genOneBlock(blockCnt int32, addr int, localBlkCnt int32, sleepTime int) (Block, bool) {\n\tlastBlock := Blockchain[blockCnt-1]\n\tprevHash := lastBlock.thisHash\n\tblockTemplate := Block{nil, prevHash, addr, 0, initNbitInt, 0, initNbitInt, 1}\n\tnonce, thisHash, premature, realNbit, alpha := solvePoW(blockTemplate, localBlkCnt, sleepTime)\n\tif premature {\n\t\t// solving PoW is interrupted by hearing of new blocks, return immediately\n\t\treturn blockTemplate, true\n\t}\n\t// populate the block template with the right nonce and this hash\n\tblockTemplate.thisHash = thisHash\n\tblockTemplate.nonce = nonce\n\tblockTemplate.HPAM_nbit = realNbit\n\tblockTemplate.alpha = alpha\n\treturn blockTemplate, false\n}", "func CreateGenesisBlock(genesisLastHash string, genesisHash string, genesisDifficulty uint32, genesisNonce uint32) (*Block, error) {\n\tdata := []Transaction{}\n\n\treturn yieldBlock(time.Now().UnixNano(), &genesisLastHash, &genesisHash, data, genesisNonce, genesisDifficulty), nil\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Validator = address\n\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Data = makeSignature(newBlock.Hash)\n\n\treturn newBlock, nil\n}", "func GenesisBlock() *msg.Packet {\n\tpacket := &msg.Packet{}\n\tpacket.Addr = []byte{}\n\tpacket.CurrentBlockNumber = 1\n\tpacket.PacketType = msg.Packet_BLOCK\n\tpacket.Prev = []byte{}\n\tpacket.Sign = []byte(\"This is the genesis\")\n\tblock := &msg.Block{}\n\tblock.Reqs = []*msg.Packet{}\n\tblock.Sanities = []*msg.SanityCheck{}\n\tblock.PacketHashs = []*msg.HashArray{}\n\tblock.Coinbase = &msg.Tx{}\n\tpacket.Data = &msg.Packet_BlockData{block}\n\tPoW.SetPoW(context.Background(), packet, 1)\n\tpacket.Diff = Consts.PoWLimit\n\tPacket.SetHash(packet)\n\treturn packet\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func NewGenesisBlock() *Block {\n\treturn NewBlock(\"Genesis Block\", []byte{})\n}", "func NewGenesisBlock() *Block {\n\treturn NewBlock(\"Genesis Block\", []byte{})\n}", "func NewGenesisBlock() *Block {\n\treturn NewBlock(\"Genesis Block\", []byte{})\n}", "func (mc *Chain) SetupGenesisBlock(hash string, magicBlock *block.MagicBlock, initStates *state.InitStates) *block.Block {\n\tgr, gb := mc.GenerateGenesisBlock(hash, magicBlock, initStates)\n\trr, ok := gr.(*round.Round)\n\tif !ok {\n\t\tpanic(\"Genesis round cannot convert to *round.Round\")\n\t}\n\tmgr := mc.CreateRound(rr)\n\tmc.AddRound(mgr)\n\tmc.AddGenesisBlock(gb)\n\tfor _, sharder := range gb.Sharders.Nodes {\n\t\tsharder.SetStatus(node.NodeStatusInactive)\n\t}\n\treturn gb\n}", "func NewGenesisBlock(contextName string) (*Block, error) {\n\tt := &SPOTuple{Subject: \"Genesis\",\n\t\tPredicate: \"Genesis\",\n\t\tPredicateFlat: \"Genesis\",\n\t\tObject: \"Genesis\",\n\t\tContext: contextName,\n\t\tVersion: 0,\n\t}\n\tblk, err := NewBlock(t, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn blk, nil\n}", "func NewGenesisBlock() Block {\n\tvar genesisBlock Block\n\n\tgenesisBlock.Index = 0\n\tgenesisBlock.Timestamp = time.Now().String()\n\tgenesisBlock.Data = \"Genesis Block\"\n\tgenesisBlock.PrevHash = \"\"\n\tgenesisBlock.Difficulty = GetDifficulty()\n\tgenesisBlock.Nonce = \"\"\n\tgenesisBlock.Hash = calculateBlockHash(genesisBlock)\n\n\treturn genesisBlock\n}", "func genesis(blockchain *BlockChain, block block1.Block, blockHeight int32) bool {\n\n\tblockchain.Chain[blockHeight] = append(blockchain.Chain[blockHeight], block)\n\tblockchain.Length++\n\treturn true\n}", "func GenerateNextBlock(data string, nonce int32) block {\n\tpreviousBlock := getLatestBlock()\n\n\tnextIndex := previousBlock.Index + 1\n\tnextTimestamp := time.Now().UnixNano()\n\tnextHash := calculateHash(nextIndex, previousBlock.Hash, nextTimestamp, data, 0, nonce)\n\n\treturn block{\n\t\tIndex: nextIndex,\n\t\tHash: nextHash,\n\t\tPreviousHash: previousBlock.Hash,\n\t\tTimestamp: nextTimestamp,\n\t\tData: data,\n\t}\n}", "func generateBlock(block *Block) (bool, string) {\n\tb := *block\n\tdata := []byte(fmt.Sprintf(\"%v\", b.HashBlock))\n\tsum := sha256.Sum256(data)\n\thash := sum[:] // Converts from [32]byte to []byte\n\t// TODO: make sure to turn in with call to isLeadingNumZeroCharacters,\n\t// not with call to isLeadingNumZeroes (which is used for finer control of block generation)\n\tif isLeadingNumZeroes(hash) {\n\t// if isLeadingNumZeroCharacters(hash) {\n\t\thashString := string(hash)\n\t\tb.Hash = hashString\n\t\taddToBlockChain(b)\n\t\tbroadcastBlock(b)\n\t\tfmt.Println(\"Done generating new block\")\n\t\treturn true, hashString\n\t} else {\n\t\tb.HashBlock.Nonce = b.HashBlock.Nonce + 1\n\t\t*block = b\n\t\treturn false, \"\"\n\t}\n}", "func CreateGenesisState() (s *State, diffs []OutputDiff) {\n\t// Create a new state and initialize the maps.\n\ts = &State{\n\t\tblockRoot: new(BlockNode),\n\t\tbadBlocks: make(map[BlockID]struct{}),\n\t\tblockMap: make(map[BlockID]*BlockNode),\n\t\tmissingParents: make(map[BlockID]map[BlockID]Block),\n\t\tcurrentPath: make(map[BlockHeight]BlockID),\n\t\topenContracts: make(map[ContractID]*OpenContract),\n\t\tunspentOutputs: make(map[OutputID]Output),\n\t\tspentOutputs: make(map[OutputID]Output),\n\t\ttransactionPoolOutputs: make(map[OutputID]*Transaction),\n\t\ttransactionPoolProofs: make(map[ContractID]*Transaction),\n\t\ttransactionList: make(map[OutputID]*Transaction),\n\t}\n\n\t// Create the genesis block and add it as the BlockRoot.\n\tgenesisBlock := Block{\n\t\tTimestamp: GenesisTimestamp,\n\t\tMinerAddress: GenesisAddress,\n\t}\n\ts.blockRoot.Block = genesisBlock\n\ts.blockRoot.Height = 0\n\tfor i := range s.blockRoot.RecentTimestamps {\n\t\ts.blockRoot.RecentTimestamps[i] = GenesisTimestamp\n\t}\n\ts.blockRoot.Target = RootTarget\n\ts.blockRoot.Depth = RootDepth\n\ts.blockMap[genesisBlock.ID()] = s.blockRoot\n\n\t// Fill out the consensus informaiton for the genesis block.\n\ts.currentBlockID = genesisBlock.ID()\n\ts.currentPath[BlockHeight(0)] = genesisBlock.ID()\n\n\t// Create the genesis subsidy output.\n\tgenesisSubsidyOutput := Output{\n\t\tValue: CalculateCoinbase(0),\n\t\tSpendHash: GenesisAddress,\n\t}\n\ts.unspentOutputs[genesisBlock.SubsidyID()] = genesisSubsidyOutput\n\n\t// Create the output diff for genesis subsidy.\n\tdiff := OutputDiff{\n\t\tNew: true,\n\t\tID: genesisBlock.SubsidyID(),\n\t\tOutput: genesisSubsidyOutput,\n\t}\n\tdiffs = append(diffs, diff)\n\n\treturn\n}", "func (powb *ProofOfWorkBlock) GenesisBlock(minter *Node) *ProofOfWorkBlock {\n\tvar totalMiningPower int64 = 0\n\t//计算所有区块的算力总和\n\t//for (Node node : getSimulatedNodes()) {\n\t//\ttotalMiningPower += node.getMiningPower();\n\t//}\n\tSimulator.GetSimulatedNodes().Each(func(index int, v interface{}) {\n\t\ttotalMiningPower += v.(*Node).GetMiningPower()\n\t})\n\n\t//难度 = 总算力*区块间隔时间\n\t// 相当于难度没有调整:\n\t// 调整策略,取前几个区块的出块时间,与预计的总出块时间\n\t// 难度(非难度值) = (预计的总出块时间/前几个区块的出块时间)*当前难度\n\t// 比特币总每次调整不超过4倍\n\tGenesisNextDifficulty = GenesisNextDifficulty.Mul(big.NewInt(totalMiningPower), big.NewInt(Simulator.GetTargetInterval()))\n\n\treturn NewProofOfWorkBlock(nil, minter, 0, big.NewInt(0))\n}", "func main() {\n\tvar chainHead *Block\n\tgenesis := BlockData{Transactions: []string{\"S2E\", \"S2Z\"}}\n\t//fmt.Printf(\"helllooo\")\n\t//fmt.Println(genesis)\n\tchainHead = InsertBlock(genesis, chainHead)\n\t//var x string=CalculateHash(chainHead)\n\t//fmt.Printf(\"%x\\n\", x)\n\n\tsecondBlock := BlockData{Transactions: []string{\"E2Alice\", \"E2Bob\", \"S2John\"}}\n\tchainHead = InsertBlock(secondBlock, chainHead)\n\n\tListBlocks(chainHead)\n\n\t//ChangeBlock(\"S2E\", \"S2Trudy\", chainHead)\n\n\tListBlocks(chainHead)\n\n\tVerifyChain(chainHead)\n\n}", "func generateCommitBlock(txid int, requiredKeyValues map[Key]Value) string {\n\tfmt.Println(\"Generating a Commit Block...\")\n\tmutex.Lock()\n\tputSet := transactions[txid].PutSet\n\tmutex.Unlock()\n\tblock := Block{PutSet: putSet, HashBlock: HashBlock{TxID: txid, NodeID: myNodeID, Nonce: 0}}\n\tfor {\n\t\tif isGenerateCommits {\n\t\t\tisWorkingOnCommit = true\n\t\t\t// this commit block was just added by AddBlock()\n\t\t\tisInChain, hash := isBlockInChain(txid)\n\t\t\tif isInChain {\n\t\t\t\tisWorkingOnCommit = false\n\t\t\t\treturn hash\n\t\t\t} else if !isCommitPossible(requiredKeyValues) {\n\t\t\t\tisWorkingOnCommit = false\n\t\t\t\treturn \"\"\n\t\t\t} else {\n\t\t\t\tblock = setCorrectParentHashAndDepth(block)\n\t\t\t\tfor isGenerateCommits {\n\t\t\t\t\tsuccess, blockHash := generateBlock(&block)\n\t\t\t\t\tisWorkingOnCommit = false\n\t\t\t\t\tif success {\n\t\t\t\t\t\treturn blockHash\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// isGenerateCommits was set to false by AddBlock()\n\t\ttime.Sleep(time.Millisecond)\n\t}\n}", "func (c *Chain) GenerateBlock(when int, who string, privkey *ecdsa.PrivateKey) (*core.Block, error) {\n\tif when <= c.Gpo().Time || when != c.Gpo().Time+config.BlockInterval {\n\t\treturn nil, fmt.Errorf(\"incorrect time\")\n\t}\n\n\twitness, err := c.sdb.GetAccountByName(who)\n\tif err != nil || witness.PublicKey != utils.EncodePubKeyInPem(&privkey.PublicKey) {\n\t\treturn nil, fmt.Errorf(\"incorret witness or key\")\n\t}\n\n\tb := core.Block{\n\t\t// ID will be set later\n\t\tNum: c.Gpo().BlockNum,\n\t\tPrevBlockId: c.Gpo().BlockId,\n\t\tCreatedOn: when,\n\t\tWitness: who,\n\t}\n\n\t// move pending txs to block\n\tc.movePendingTransactionsToBlock(&b)\n\t//c.MoveTxToBlock(&b)\n\n\t// set b.ID\n\t// set b.MerkleRoot\n\treturn &b, nil\n}", "func (s *BlockchainService) generateBlock(oldBlock *Block, payload int) Block {\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Payload = payload\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(&newBlock)\n\n\treturn newBlock\n}", "func (c *Chain) GenerateNextBlock() (*core.Block, error) {\n\tslottime := getNextBlockTime(c.Gpo())\n\tname := getNextWitness(c.Gpo(), c.Wso())\n\treturn c.GenerateBlock(slottime, name, getCurrentWitnessPrivateKey())\n}", "func InitChain(address string) *BlockChain {\n\n\tvar lastHash []byte\n\n\tif DBExist() {\n\t\tfmt.Println(\"Blockchain Already Exist\")\n\t\truntime.Goexit()\n\t}\n\n\topts := badger.DefaultOptions\n\topts.Dir = dbpath\n\topts.ValueDir = dbpath\n\n\tdb, err := badger.Open(opts)\n\tHandle(err)\n\n\terr = db.Update(func(txn *badger.Txn) error {\n\t\t// create transaction with address and genesis data\n\t\tcbtx := CoinbaseTx(address, genesisData)\n\n\t\t// create first block with genesis transaction\n\t\tgenesis := Genesis(cbtx)\n\n\t\tfmt.Println(\"Genesis Block Created \")\n\n\t\terr := txn.Set([]byte(\"lasthash\"), genesis.Hash)\n\t\tHandle(err)\n\n\t\terr = txn.Set(genesis.Hash, genesis.Serialize())\n\n\t\tlastHash = genesis.Hash\n\n\t\treturn err\n\t})\n\n\t// // Checking and also updating database with blockchain\n\t// err = db.Update(func(txn *badger.Txn) error {\n\t// \t// check if there is a blockchain via lasthash key\n\t// \t// if not\n\t// \tif _, err := txn.Get([]byte(\"lasthash\")); err == badger.ErrKeyNotFound {\n\t// \t\tfmt.Println(\"No Blockchain Exist. Creating One ...\")\n\t// \t\t// create genesis block\n\t// \t\tgenesis := Genesis()\n\n\t// \t\t// save hash to database with lasthash key --> to disk\n\t// \t\t// the purpose of this is later when we want to get blocks from block chain we can get from deserialized this block\n\t// \t\terr := txn.Set(genesis.Hash, genesis.Serialize())\n\t// \t\tHandle(err)\n\n\t// \t\t// save serialize block to database with it's hash key --> to disk\n\t// \t\terr = txn.Set([]byte(\"lasthash\"), genesis.Hash)\n\n\t// \t\t// set lasthash with genesis hash so we get lasthash in memory --> in memory\n\t// \t\tlastHash = genesis.Hash\n\n\t// \t\treturn err\n\n\t// \t} else {\n\t// \t\t// else if there is a block chain\n\t// \t\t// get lasthash value\n\t// \t\titem, err := txn.Get([]byte(\"lasthash\"))\n\t// \t\tHandle(err)\n\n\t// \t\t// set lasthash to lasthash in memory --> in memory\n\t// \t\tlastHash, err = item.Value()\n\n\t// \t\treturn err\n\t// \t}\n\t// })\n\n\tHandle(err)\n\n\tblockchain := BlockChain{lastHash, db}\n\n\treturn &blockchain\n\n}", "func generateNewBlock(oldBlock Block, dataPayload string) (Block, error) {\n\n\tvar newBlock Block\n\ttimeNow := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = timeNow.String()\n\n\tnewEvent, err := dataPayloadtoServiceEvent(dataPayload)\n\n\tif err != nil {\n\t\tlog.Println(\"ERROR: Unable to convert data payload into ServiceEvent for new block generation.\")\n\t}\n\n\tnewBlock.Event = newEvent\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\treturn newBlock, nil\n}", "func (_EthCrossChain *EthCrossChainSession) InitGenesisBlock(_rawHeader []byte, _pubKeyList []byte) (*types.Transaction, error) {\n\treturn _EthCrossChain.Contract.InitGenesisBlock(&_EthCrossChain.TransactOpts, _rawHeader, _pubKeyList)\n}", "func GenesisBlock() *types.Block {\n\treturn types.NewExistingBlock(types.GetEffectiveGenesis(), []byte(\"genesis\"), nil)\n}", "func CreateGenesisBlockWithGeneisBlock() *BlockChain {\n\tblock := CreateGenesisBlock([]byte(\"init blockchain\"))\n\treturn &BlockChain{Blocks: []*Block{block}}\n}", "func (bc *Blockchain) createBlock() {\n\tnonce := bc.proofOfWork()\n\tpreviousHash := bc.lastBlock().Hash()\n\tbc.chainNewBlock(nonce, previousHash)\n}", "func (_EthCrossChain *EthCrossChainTransactorSession) InitGenesisBlock(_rawHeader []byte, _pubKeyList []byte) (*types.Transaction, error) {\n\treturn _EthCrossChain.Contract.InitGenesisBlock(&_EthCrossChain.TransactOpts, _rawHeader, _pubKeyList)\n}", "func (m *CPUMiner) generateBlocks(quit chan struct{}) {\n\tticker := time.NewTicker(time.Second * hashUpdateSecs)\n\tdefer ticker.Stop()\n\nout:\n\tfor {\n\t\tselect {\n\t\tcase <-quit:\n\t\t\tbreak out\n\t\tdefault:\n\t\t}\n\n\t\tblock, err := mining.NewBlockTemplate(m.chain, m.txPool, m.accountManager)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Mining: failed on create NewBlockTemplate: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.solveBlock(block, ticker, quit) {\n\t\t\tif isOrphan, err := m.chain.ProcessBlock(block); err == nil {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"module\": logModule,\n\t\t\t\t\t\"height\": block.BlockHeader.Height,\n\t\t\t\t\t\"isOrphan\": isOrphan,\n\t\t\t\t\t\"tx\": len(block.Transactions),\n\t\t\t\t}).Info(\"Miner processed block\")\n\n\t\t\t\t// Broadcast the block and announce chain insertion event\n\t\t\t\tif err = m.eventDispatcher.Post(event.NewMinedBlockEvent{Block: *block}); err != nil {\n\t\t\t\t\tlog.WithFields(log.Fields{\"module\": logModule, \"height\": block.BlockHeader.Height, \"error\": err}).Errorf(\"Miner fail on post block\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.WithFields(log.Fields{\"module\": logModule, \"height\": block.BlockHeader.Height, \"error\": err}).Errorf(\"Miner fail on ProcessBlock\")\n\t\t\t}\n\t\t}\n\t}\n\n\tm.workerWg.Done()\n}", "func Genesis() *Block {\n\treturn CreateBlock(\"Genesis\", []byte{})\n}", "func NewGenesisBlock(tx *Transaction) *Block {\n\treturn NewBlock([]*Transaction{tx}, []byte{})\n}", "func generateNoOpBlock() {\n\tfmt.Println(\"Generating a NoOp Block...\")\n\tfmt.Println(\"Block chain size:\", len(blockChain), \"number transactions:\", len(transactions))\n\t// TODO this printstate() actually seemed to help performance... Maybe could use a tiny sleep here?\n\tprintState()\n\tif len(leafBlocks) > 1 {\n\t\tfmt.Println(\"We have a fork!!!!!!!!!!!!!!\")\n\t}\n\tnoOpBlock := Block{HashBlock: HashBlock{TxID: 0, NodeID: myNodeID, Nonce: 0}}\n\tnoOpBlock = setCorrectParentHashAndDepth(noOpBlock)\n\tfor isGenerateNoOps {\n\t\tsuccess, _ := generateBlock(&noOpBlock)\n\t\tif success {\n\t\t\treturn\n\t\t}\n\t}\n\t// received a call to commit or AddBlock which set isGenerateNoOps = false\n\treturn\n}", "func UpdateGenesisBlock(blk *wire.MsgBlock) {\n\tChainParams.GenesisBlock = blk\n\t// update ChainID\n\tchainID, err := ChainParams.GenesisBlock.Header.GetChainID()\n\tif err != nil {\n\t\tpanic(err) // should not happen\n\t}\n\tChainParams.ChainID = &chainID\n\tgenesisChainID = chainID\n\tgenesisHeader.ChainID = chainID\n\tChainParams.GenesisBlock.Header.ChainID = chainID\n\t//update Block Hash\n\tgenesisHash = genesisHeader.BlockHash()\n\tChainParams.GenesisHash = &genesisHash\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func generateBlock(oldBlock Block, Key int) Block {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Key = Key\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\tf, err := os.OpenFile(\"blocks.txt\",\n\t\tos.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tb, err := json.Marshal(newBlock)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\tif _, err := f.WriteString(string(b)); err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn newBlock\n}", "func generateRandomBlock() types.Block {\n\tblock := types.Block{\n\t\tTimestamp: types.Timestamp(rand.Uint64()),\n\t}\n\treturn block\n}", "func (blockchain *Blockchain) MineNewBlock(originalTxs []*Transaction) *Block {\n\t// Reward of mining a block\n\tcoinBaseTransaction := NewRewardTransacion()\n\ttxs := []*Transaction{coinBaseTransaction}\n\ttxs = append(txs, originalTxs...)\n\t// Verify transactions\n\tfor _, tx := range txs {\n\t\tif !tx.IsCoinBaseTransaction() {\n\t\t\tif blockchain.VerifityTransaction(tx, txs) == false {\n\t\t\t\tlog.Panic(\"Verify transaction failed...\")\n\t\t\t}\n\t\t}\n\t}\n\n\tDBName := fmt.Sprintf(DBName, os.Getenv(\"NODE_ID\"))\n\tdb, err := bolt.Open(DBName, 0600, nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer db.Close()\n\t// Get the latest block\n\tvar block Block\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BlockBucketName))\n\t\tif b != nil {\n\t\t\thash := b.Get([]byte(\"l\"))\n\t\t\tblockBytes := b.Get(hash)\n\t\t\tgobDecode(blockBytes, &block)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\t// Mine a new block\n\tnewBlock := NewBlock(txs, block.Height+1, block.BlockHash)\n\n\treturn newBlock\n}", "func (b Engine) block(difficulty uint8) *core.Block {\n\t//random data\n\tpriv, _ := crypt.GenKeys()\n\tj, _ := job.NewJob(\"func test(){return 1+1}\", \"test\", false, priv)\n\tnodes := []*merkletree.MerkleNode{}\n\tfor i := 0; i < 16; i++ {\n\t\tnode, err := merkletree.NewNode(*j, nil, nil)\n\t\tif err != nil {\n\t\t\tb.logger.Fatal(err)\n\t\t}\n\t\tnodes = append(nodes, node)\n\t}\n\ttree, err := merkletree.NewMerkleTree(nodes)\n\tif err != nil {\n\t\tb.logger.Fatal(err)\n\t}\n\tblock, err := core.NewBlock(*tree, \"47656e65736973\", uint64(rand.Int()), difficulty, \"62656e63686d61726b2d656e67696e65\")\n\tif err != nil {\n\t\tb.logger.Fatal(err)\n\t}\n\treturn block\n}", "func GenesisBlock(address string) *Block {\n\tcoinBase := NewCoinbaseTX(address, \"创世块\")\n\tcoinBases := []*Transaction{coinBase}\n\treturn NewBlock(coinBases, []byte{})\n}", "func (cs *ConsensusState) createProposalBlock() (block *ttypes.QbftBlock) {\n\tvar commit *tmtypes.QbftCommit\n\tif cs.Height == 1 {\n\t\t// We're creating a proposal for the first block.\n\t\t// The commit is empty, but not nil.\n\t\tcommit = &tmtypes.QbftCommit{}\n\t} else if cs.LastCommit.HasTwoThirdsMajority() {\n\t\t// Make the commit from LastCommit\n\t\tcommit = cs.LastCommit.MakeCommonCommit()\n\t} else {\n\t\t// This shouldn't happen.\n\t\tqbftlog.Error(\"enterPropose: Cannot propose anything: No commit for the previous block.\")\n\t\treturn nil\n\t}\n\n\t// Mempool validated transactions\n\tbeg := time.Now()\n\tpblock := cs.client.BuildBlock(cs.Height - 1)\n\tif pblock == nil {\n\t\tqbftlog.Error(\"createProposalBlock BuildBlock fail\")\n\t\treturn nil\n\t}\n\tqbftlog.Info(fmt.Sprintf(\"createProposalBlock BuildBlock. Current: %v/%v/%v\", cs.Height, cs.Round, cs.Step),\n\t\t\"height\", pblock.Height, \"txs-len\", len(pblock.Txs), \"cost\", types.Since(beg))\n\n\tif pblock.Height != cs.Height {\n\t\tqbftlog.Error(\"pblock.Height is not equal to cs.Height\")\n\t\treturn nil\n\t}\n\n\tproposerAddr := cs.privValidator.GetAddress()\n\tblock = cs.state.MakeBlock(cs.Height, int64(cs.Round), pblock, commit, proposerAddr)\n\tbaseTx := cs.createBaseTx(block.QbftBlock)\n\tif baseTx == nil {\n\t\tqbftlog.Error(\"createProposalBlock createBaseTx fail\")\n\t\treturn nil\n\t}\n\tcfg := cs.client.GetQueueClient().GetConfig()\n\n\tblock.Data.Txs[0] = baseTx\n\t//需要首先对交易进行排序然后再计算TxHash\n\tif cfg.IsFork(block.Data.Height, \"ForkRootHash\") {\n\t\tblock.Data.Txs = types.TransactionSort(block.Data.Txs)\n\t}\n\n\tblock.Data.TxHash = merkle.CalcMerkleRoot(cfg, block.Data.Height, block.Data.Txs)\n\tif preExec.Load().(bool) {\n\t\tpblockNew := cs.client.PreExecBlock(block.Data, false)\n\t\tif pblockNew == nil {\n\t\t\tqbftlog.Error(\"createProposalBlock PreExecBlock fail\")\n\t\t\treturn nil\n\t\t}\n\t\tblock.Data = pblockNew\n\t}\n\treturn block\n}", "func (g *BlockGenerator) GenerateBlock() (*types.Block, error) {\n\tbState := g.bState\n\n\ttransactions, err := g.GatherTXs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn := len(transactions)\n\tif n == 0 && g.skipEmpty {\n\t\tlogger.Debug().Msg(\"BF: empty block is skipped\")\n\t\treturn nil, ErrBlockEmpty\n\t}\n\n\ttxs := make([]*types.Tx, n)\n\tfor i, x := range transactions {\n\t\ttxs[i] = x.GetTx()\n\t}\n\n\tblock := types.NewBlock(g.bi, bState.GetRoot(), bState.Receipts(), txs, chain.CoinbaseAccount, bState.Consensus())\n\tif n != 0 && logger.IsDebugEnabled() {\n\t\tlogger.Debug().\n\t\t\tStr(\"txroothash\", types.EncodeB64(block.GetHeader().GetTxsRootHash())).\n\t\t\tInt(\"hashed\", len(txs)).\n\t\t\tInt(\"no_receipts\", len(bState.Receipts().Get())).\n\t\t\tMsg(\"BF: tx root hash\")\n\t}\n\n\treturn block, nil\n}", "func TestGenesis(t *testing.T) {\n\t// Initialize the vm\n\tdbManager := manager.NewMemDB(version.DefaultVersion1_0_0)\n\tmsgChan := make(chan common.Message, 1)\n\tvm := &VM{}\n\tctx := snow.DefaultContextTest()\n\tctx.ChainID = blockchainID\n\n\tif err := vm.Initialize(ctx, dbManager, []byte{0, 0, 0, 0, 0}, nil, nil, msgChan, nil, nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Verify that the db is initialized\n\tif !vm.DBInitialized() {\n\t\tt.Fatal(\"db should be initialized\")\n\t}\n\n\t// Get lastAccepted\n\tlastAccepted, err := vm.LastAccepted()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif lastAccepted == ids.Empty {\n\t\tt.Fatal(\"lastAccepted should not be empty\")\n\t}\n\n\t// Verify that getBlock returns the genesis block, and the genesis block\n\t// is the type we expect\n\tgenesisSnowmanBlock, err := vm.GetBlock(lastAccepted) // genesisBlock as snowman.Block\n\tif err != nil {\n\t\tt.Fatalf(\"couldn't get genesisBlock: %s\", err)\n\t}\n\tgenesisBlock, ok := genesisSnowmanBlock.(*Block) // type assert that genesisBlock is a *Block\n\tif !ok {\n\t\tt.Fatal(\"type of genesisBlock should be *Block\")\n\t}\n\n\t// Verify that the genesis block has the data we expect\n\tif err := assertBlock(genesisBlock, ids.Empty, []byte{0, 0, 0, 0, 0}, true); err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func GenerateBlock(oldBlock model.Block, data string, address string) (model.Block, error) {\n\n\tvar newBlock model.Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = crypto.CalculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func (bs *Bootstrapper) GenesisBlock() *cb.Block {\n\t// TODO(mjs): remove\n\treturn genesis.NewFactoryImpl(bs.channelGroup).Block(\"testchannelid\")\n}", "func mineNewBlock (block *Block) {\n proofPrefix := strings.Repeat(\"0\", difficulty)\n for calculateHash(*block)[:difficulty] != proofPrefix {\n block.Nonce ++\n }\n\n block.Hash = calculateHash(*block)\n}", "func (t *Thereum) nextBlock() (*types.Block, *state.StateDB) {\n\t// make new blocks using the transaction pool\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\tblocks, _ := core.GenerateChain(\n\t\tt.chainConfig,\n\t\tt.blockchain.CurrentBlock(),\n\t\tethash.NewFaker(),\n\t\tt.database,\n\t\t1,\n\t\tfunc(i int, b *core.BlockGen) {\n\t\t\tb.SetCoinbase(t.root.Address)\n\t\t\t// get the next set of highest paying transactions\n\t\t\ttxs := t.txPool.Batch(t.gasLimit)\n\t\t\t// add them to the new block.\n\t\t\tfor _, tx := range txs {\n\t\t\t\tb.AddTx(tx)\n\t\t\t\tfmt.Println(\"finalized: \", tx.Hash().Hex())\n\t\t\t}\n\t\t},\n\t)\n\tstatedb, _ := t.blockchain.State()\n\n\tfreshBlock := blocks[0]\n\n\tfreshState, _ := state.New(freshBlock.Root(), statedb.Database())\n\treturn freshBlock, freshState\n}", "func NewGenesisBlock(genesisAddr cipher.Address, genesisCoins, timestamp uint64) (*Block, error) {\n\ttxn := Transaction{}\n\ttxn.PushOutput(genesisAddr, genesisCoins, genesisCoins)\n\tbody := BlockBody{Transactions: Transactions{txn}}\n\tprevHash := cipher.SHA256{}\n\thead := BlockHeader{\n\t\tTime: timestamp,\n\t\tBodyHash: body.Hash(),\n\t\tPrevHash: prevHash,\n\t\tBkSeq: 0,\n\t\tVersion: 0,\n\t\tFee: 0,\n\t\tUxHash: cipher.SHA256{},\n\t}\n\tb := &Block{\n\t\tHead: head,\n\t\tBody: body,\n\t}\n\n\treturn b, nil\n}", "func NewGenesisBlock(genesisAddr cipher.Address, genesisCoins, timestamp uint64) (*Block, error) {\n\ttxn := Transaction{}\n\tif err := txn.PushOutput(genesisAddr, genesisCoins, genesisCoins); err != nil {\n\t\treturn nil, err\n\t}\n\tbody := BlockBody{Transactions: Transactions{txn}}\n\tprevHash := cipher.SHA256{}\n\tbodyHash := body.Hash()\n\thead := BlockHeader{\n\t\tTime: timestamp,\n\t\tBodyHash: bodyHash,\n\t\tPrevHash: prevHash,\n\t\tBkSeq: 0,\n\t\tVersion: 0,\n\t\tFee: 0,\n\t\tUxHash: cipher.SHA256{},\n\t}\n\tb := &Block{\n\t\tHead: head,\n\t\tBody: body,\n\t}\n\n\treturn b, nil\n}", "func CreateNewBlock(txs []*model.Transaction, prevHash string, reward float64, height int64, pk []byte, l *model.Ledger, difficulty int, ctl chan commands.Command) (*model.Block, commands.Command, []*model.Transaction, error) {\n\torigL := GetLedgerDeepCopy(l)\n\n\terrTxs, err := HandleTransactions(txs, l)\n\tif err != nil {\n\t\treturn nil, commands.NewDefaultCommand(), errTxs, err\n\t}\n\n\t// All transactions are valid if reached here, calculate transaction fee on the original ledger.\n\tfee, err := CalcTxFee(txs, origL)\n\tif err != nil {\n\t\tlog.Fatalln(\"there should never be a case where handle transaction success but fail calcFee\")\n\t}\n\n\tblock := model.Block{\n\t\tPrevHash: prevHash,\n\t\tTxs: txs,\n\t\tCoinbase: CreateCoinbaseTx(reward+fee, pk, height),\n\t}\n\n\tc, err := Mine(&block, difficulty, ctl)\n\treturn &block, c, []*model.Transaction{}, err\n}", "func ProduceBlock(prevBlockHash string, prevBlock *Block) *Block {\n // This function creates a new block.\n //\n // The implementation is fairly straightforward matter of creating a Block instance and filling in the fields.\n //\n // This function's API is slightly weird, it requires the caller to compute `prevBlockHash = HashBlock(prevBlock)`.\n // Why we don't simplify the API by computing `prevBlockHash` ourselves, reducing the number of arguments\n // from two to one? Two reasons:\n //\n // - Immediately, it makes the placement of the `HashBlock()` debugging output less confusing.\n // - Eventually, we will have more data with the same data flow as `prevBlockHash`, so writing code to route this data\n // now will be useful later.\n\n newBlock := new(Block)\n\n if prevBlock == nil {\n newBlock.PrevHash = prevBlockHash\n newBlock.Height = 1\n } else {\n newBlock.PrevHash = prevBlockHash\n newBlock.Height = prevBlock.Height + 1\n }\n\n return newBlock\n}", "func initGenesis(ctx *cli.Context) error {\n\t// Make sure we have a valid genesis JSON\n\tgenesisPath := ctx.Args().First()\n\tif len(genesisPath) == 0 {\n\t\tutils.Fatalf(\"Must supply path to genesis JSON file\")\n\t}\n\tfile, err := os.Open(genesisPath)\n\tif err != nil {\n\t\tutils.Fatalf(\"Failed to read genesis file: %v\", err)\n\t}\n\tdefer file.Close()\n\n\tkeyGenesis := new(core.GenesisKey)\n\tif err := json.NewDecoder(file).Decode(keyGenesis); err != nil {\n\t\tutils.Fatalf(\"init keychain, invalid genesis file: %v\", err)\n\t}\n\n\tfile.Seek(0, 0)\n\tgenesis := new(core.Genesis)\n\tif err := json.NewDecoder(file).Decode(genesis); err != nil {\n\t\tutils.Fatalf(\"init blockchain,invalid genesis file: %v\", err)\n\t}\n\n\t// Open an initialise both full and light databases\n\tstack := makeFullNode(ctx)\n\tfor _, name := range []string{\"chaindata\"} {\n\t\tchaindb, err := stack.OpenDatabase(name, 0, 0)\n\t\tif err != nil {\n\t\t\tutils.Fatalf(\"Failed to open database: %v\", err)\n\t\t}\n\n\t\t_, hash, err := core.SetupGenesisKeyBlock(chaindb, keyGenesis)\n\t\tif err != nil {\n\t\t\tutils.Fatalf(\"Failed to write genesis key block: %v\", err)\n\t\t}\n\n\t\tgenesis.KeyHash = hash\n\t\t_, hash, err = core.SetupGenesisBlock(chaindb, genesis)\n\t\tif err != nil {\n\t\t\tutils.Fatalf(\"Failed to write genesis block: %v\", err)\n\t\t}\n\n\t\tlog.Info(\"Successfully wrote genesis state\", \"database\", name, \"hash\", hash)\n\t}\n\n\treturn nil\n}", "func TestGenesisBlockParser(t *testing.T) {\n\tblockFile, err := os.Open(\"../testdata/mainnet_genesis\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer blockFile.Close()\n\n\tscan := bufio.NewScanner(blockFile)\n\tfor i := 0; scan.Scan(); i++ {\n\t\tblockDataHex := scan.Text()\n\t\tblockData, err := hex.DecodeString(blockDataHex)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tblock := NewBlock()\n\t\tblockData, err = block.ParseFromSlice(blockData)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Some basic sanity checks\n\t\tif block.hdr.Version != 4 {\n\t\t\tt.Error(\"Read wrong version in genesis block.\")\n\t\t\tbreak\n\t\t}\n\n\t\tif block.GetHeight() != i {\n\t\t\tt.Errorf(\"Got wrong height for block %d: %d\", i, block.GetHeight())\n\t\t}\n\t}\n}", "func (s *service) MineNewBlock(lastBlock *Block, data []Transaction) (*Block, error) {\n\t// validations\n\tif lastBlock == nil {\n\t\treturn nil, ErrMissingLastBlock\n\t}\n\n\tdifficulty := lastBlock.Difficulty\n\tvar nonce uint32\n\tvar timestamp int64\n\tvar hash string\n\tfor {\n\t\tnonce++\n\t\ttimestamp = time.Now().UnixNano()\n\t\tdifficulty = adjustBlockDifficulty(*lastBlock, timestamp, s.MineRate)\n\t\thash = hashing.SHA256Hash(timestamp, *lastBlock.Hash, data, nonce, difficulty)\n\t\tif hexStringToBinary(hash)[:difficulty] == strings.Repeat(\"0\", int(difficulty)) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn yieldBlock(timestamp, lastBlock.Hash, &hash, data, nonce, difficulty), nil\n}", "func (AppModule) GenerateGenesisState(simState *module.SimulationState) {\n\t// simulation.RandomizedGenState(simState)\n}", "func (bc *Blockchain) chainNewBlock(nonce int, previousHash [32]byte) *Block {\n\tb := NewBlock(nonce, previousHash, bc.transactionPool)\n\tbc.chain = append(bc.chain, b)\n\tbc.transactionPool = []*Transaction{}\n\treturn b\n}", "func (t *ArtNodeMinerRPC) GetGenesisBlockRPC(args *shared.Args, reply *string) error {\n\tfmt.Println(\"Get GetGenesisBlock RPC\")\n\t*reply = minerNetSettings.GenesisBlockHash\n\treturn nil\n}", "func (honest *Honest) createBlock(iterationCount int, stakeMap map[int]int) (*Block,error) {\n\n\t// Has block already been appended from advertisements by other client?\n\tif(honest.bc.getBlock(iterationCount) != nil){\n\t\treturn nil, blockExistsError\n\t}\n\n\tpulledGradient := make([]float64, honest.ncol)\n\tpulledGradient = honest.bc.getLatestGradient()\n\tupdatedGradient := make([]float64, honest.ncol)\n\tdeltaM := mat.NewDense(1, honest.ncol, make([]float64, honest.ncol))\n\tpulledGradientM := mat.NewDense(1, honest.ncol, pulledGradient)\n\t// avgFactor := 1.0/float64(len(honest.blockUpdates))\n\n\t// Update Aggregation\n\tfor _, update := range honest.blockUpdates {\n\t\ttheirStake := stakeMap[update.SourceID] \n\t\tif update.Accepted {\n\t\t\tdeltaM = mat.NewDense(1, honest.ncol, update.Delta)\n\t\t\tpulledGradientM.Add(pulledGradientM, deltaM)\t\n\t\t\tstakeMap[update.SourceID] = theirStake + STAKE_UNIT\n\t\t} else {\n\t\t\toutLog.Printf(\"Skipping an update\")\n\t\t\tstakeMap[update.SourceID] = theirStake - STAKE_UNIT\n\t\t}\n\t}\n\n\t// pulledGradientM.Scale(avgFactor, pulledGradientM)\n\n\tmat.Row(updatedGradient, 0, pulledGradientM)\n\n\tupdatesGathered := make([]Update, len(honest.blockUpdates))\n\tcopy(updatesGathered, honest.blockUpdates)\n\n\tbData := BlockData{iterationCount, updatedGradient, updatesGathered}\n\thonest.bc.AddBlock(bData, stakeMap) \n\n\tnewBlock := honest.bc.Blocks[len(honest.bc.Blocks)-1]\n\n\treturn newBlock,nil\n\n\n}", "func mockFirstIntermediateBlock(prevBlockHeader *block.Header) (*block.Block, error) {\n\tblk := block.NewBlock()\n\tblk.Header.Seed = make([]byte, 33)\n\tblk.Header.Height = 1\n\t// Something above the genesis timestamp\n\tblk.Header.Timestamp = 1570000000\n\tblk.SetPrevBlock(prevBlockHeader)\n\n\ttx := mockDeterministicCoinbase()\n\tblk.AddTx(tx)\n\troot, err := blk.CalculateRoot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblk.Header.TxRoot = root\n\n\thash, err := blk.CalculateHash()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblk.Header.Hash = hash\n\n\treturn blk, nil\n}", "func (bc *Blockchain) GetGenesisBlock() *Block {\n\t// TODO(student)\n\treturn nil\n}", "func createGenesisVisor(masterKeys, bcFile,\n bsFile string) (*visor.Visor, visor.SignedBlock, error) {\n we := visor.MustLoadWalletEntry(masterKeys)\n c := visor.NewVisorConfig()\n c.MasterKeys = we\n c.IsMaster = true\n c.BlockSigsFile = bsFile\n c.BlockchainFile = bcFile\n c.CoinHourBurnFactor = 0\n v := visor.NewMinimalVisor(c)\n v.Wallet = visor.CreateMasterWallet(c.MasterKeys)\n sb, err := v.CreateFreshGenesisBlock()\n return v, sb, err\n}", "func TestHaveBlock(t *testing.T) {\n\t// Load up blocks such that there is a side chain.\n\t// (genesis block) -> 1 -> 2 -> 3 -> 4 -> 5\n\t// \\-> 3a\n\n\tparivateKeyList := []string{\n\t\t\"0xd0f0461b7b4d26cf370e6c73b58ef7fa26e8e30853a8cee901ed42cf0879cb6e\", //privateKey0\n\t}\n\ttestRoundSize := uint16(10)\n\taccList, netParam, chain, teardownFunc, err := createFakeChainByPrivateKeys(parivateKeyList, testRoundSize)\n\tdefer teardownFunc()\n\n\tvalidators, filters, _ := chain.GetValidatorsByNode(1, chain.bestChain.tip())\n\n\tmainChainBlkNums := 5\n\tforkBlkHeightIdx := 3\n\torphanBlkHeightIdx := 5\n\n\tbestChainHashList := make([]common.Hash, 0)\n\tnode0 := chain.bestChain.NodeByHeight(0)\n\tbestChainHashList = append(bestChainHashList, node0.hash)\n\tvar forkHash common.Hash\n\tvar orphanHash common.Hash\n\tcurSlot := uint16(0)\n\tcurEpoch := uint32(1)\n\t//create block:\n\tfor i := 0; i < mainChainBlkNums; i++ {\n\t\tif i != 0 {\n\t\t\tif i == int(netParam.RoundSize) {\n\t\t\t\tcurSlot = 0\n\t\t\t\tcurEpoch += 1\n\t\t\t\tvalidators, filters, _ = chain.GetValidatorsByNode(curEpoch, chain.bestChain.tip())\n\t\t\t} else {\n\t\t\t\tcurSlot ++\n\t\t\t}\n\t\t}\n\n\t\tvar block *asiutil.Block\n\t\tvar frokBlock *asiutil.Block\n\t\tif i == (orphanBlkHeightIdx - 1) {\n\t\t\tblock, _, err = createAndSignBlock(netParam, accList, validators, filters, chain, uint32(curEpoch),\n\t\t\t\tuint16(curSlot), chain.bestChain.height(), protos.Asset{0, 0}, 0,\n\t\t\t\tvalidators[curSlot], nil, 0, chain.bestChain.tip())\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"create block error %v\", err)\n\t\t\t}\n\t\t\t//create orphanBlock:\n\t\t\torphanBlock := block\n\t\t\torphanBlock.MsgBlock().Header.PrevBlock = common.Hash{0x01,}\n\t\t\torphanHash = *orphanBlock.Hash()\n\t\t} else {\n\t\t\t//create block:\n\t\t\tblock, _, err = createAndSignBlock(netParam, accList, validators, filters, chain, uint32(curEpoch),\n\t\t\t\tuint16(curSlot), chain.bestChain.height(), protos.Asset{0, 0}, 0,\n\t\t\t\tvalidators[curSlot], nil, 0, chain.bestChain.tip())\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"create block error %v\", err)\n\t\t\t}\n\n\t\t\tif i == int(forkBlkHeightIdx - 1) {\n\t\t\t\tfrokBlock, _, err = createAndSignBlock(netParam, accList, validators, filters, chain, uint32(curEpoch),\n\t\t\t\t\tuint16(curSlot), chain.bestChain.height(), protos.Asset{0, 0}, 0,\n\t\t\t\t\tvalidators[curSlot], nil, int32(i+1), chain.bestChain.tip())\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"create block error %v\", err)\n\t\t\t\t}\n\t\t\t\tforkHash = *frokBlock.Hash()\n\t\t\t}\n\t\t}\n\t\t// Insert the block to bestChain:\n\t\t_, isOrphan, err := chain.ProcessBlock(block, nil, nil, nil, common.BFNone)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ProcessBlock err %v\", err)\n\t\t}\n\t\tlog.Infof(\"isOrphan = %v\", isOrphan)\n\t\tif i == int(forkBlkHeightIdx - 1) {\n\t\t\t_, forkIsOrphan, err := chain.ProcessBlock(frokBlock, nil, nil, nil, common.BFNone)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"ProcessBlock err %v\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"frokBlock isOrphan = %v\", forkIsOrphan)\n\t\t}\n\n\t\tif !isOrphan {\n\t\t\tnode := chain.bestChain.nodeByHeight(chain.bestChain.height())\n\t\t\tbestChainHashList = append(bestChainHashList, node.hash)\n\t\t}\n\t}\n\n\tmainblklen := len(bestChainHashList)\n\ttmpHash := bestChainHashList[mainblklen-1]\n\totherHash := append(tmpHash[:1], tmpHash[:common.HashLength-1]...)\n\tvar resultHash common.Hash\n\tcopy(resultHash[:], otherHash)\n\n\ttests := []struct {\n\t\thash common.Hash\n\t\twant bool\n\t}{\n\t\t//blockHash in bestchain: test0\n\t\t{\n\t\t\tbestChainHashList[mainChainBlkNums-2],\n\t\t\ttrue,\n\t\t},\n\t\t//block hash in fork chain: test1\n\t\t{\n\t\t\tforkHash,\n\t\t\ttrue,\n\t\t},\n\t\t//orphan block hash: test2\n\t\t{\n\t\t\torphanHash,\n\t\t\ttrue,\n\t\t},\n\t\t//Random hashes should not be available\n\t\t{\n\t\t\tresultHash,\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\tt.Logf(\"start test %d\", i)\n\t\tresult, err := chain.HaveBlock(&test.hash)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"HaveBlock #%d unexpected error: %v\", i, err)\n\t\t}\n\t\tif result != test.want {\n\t\t\tt.Errorf(\"HaveBlock #%d got %v want %v\", i, result, test.want)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func InitGenesis(ctx sdk.Context, k keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, genState types.GenesisState) {\n\t// this line is used by starport scaffolding # genesis/module/init\n\t// Set all the auction\n\t// for _, elem := range genState.AuctionList {\n\t// \tk.SetAuction(ctx, *elem)\n\t// }\n\n\t// // Set auction count\n\t// k.SetAuctionCount(ctx, int64(len(genState.AuctionList)))\n\tif err := genState.Validate(); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to validate %s genesis state: %s\", types.ModuleName, err))\n\t}\n\n\tk.SetNextAuctionID(ctx, genState.NextAuctionId)\n\n\tk.SetParams(ctx, genState.Params)\n\n\ttotalAuctionCoins := sdk.NewCoins()\n\tauctions, err := types.UnpackGenesisAuctions(genState.Auctions)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, a := range auctions {\n\t\tk.SetAuction(ctx, a)\n\t\t// find the total coins that should be present in the module account\n\t\ttotalAuctionCoins = totalAuctionCoins.Add(a.GetModuleAccountCoins()...)\n\t}\n\n\t// check if the module account exists\n\tmoduleAcc := accountKeeper.GetModuleAccount(ctx, types.ModuleName)\n\tif moduleAcc == nil {\n\t\tpanic(fmt.Sprintf(\"%s module account has not been set\", types.ModuleName))\n\t}\n\t// check module coins match auction coins\n\t// Note: Other sdk modules do not check this, instead just using the existing module account coins, or if zero, setting them.\n\tbalances := bankKeeper.GetAllBalances(ctx, moduleAcc.GetAddress())\n\tif !balances.IsEqual(totalAuctionCoins) {\n\t\tpanic(fmt.Sprintf(\"total auction coins (%s) do not equal (%s) module account (%s) \", balances, types.ModuleName, totalAuctionCoins))\n\t}\n}", "func (m *MockStub) InitWithGenesis(blockBytes []byte) error {\n\treturn nil\n}", "func (m *MockStub) InitWithGenesis(blockBytes []byte) error {\n\treturn nil\n}", "func (AppModuleBasic) GenerateGenesisState(simState *module.SimulationState) {\n\tRandomizedGenState(simState)\n}", "func newBlock(prevHash [32]byte, prevHashWithoutTx [32]byte, commitmentProof [crypto.COMM_PROOF_LENGTH]byte, height uint32) *protocol.Block {\n\tblock := new(protocol.Block)\n\tblock.PrevHash = prevHash\n\tblock.PrevHashWithoutTx = prevHashWithoutTx\n\tblock.CommitmentProof = commitmentProof\n\tblock.Height = height\n\tblock.StateCopy = make(map[[32]byte]*protocol.Account)\n\tblock.Aggregated = false\n\n\treturn block\n}", "func generateGenesisFile(genFile string, validators []crypto.PubKey) error {\n\t// genesis file\n\tif _, err := os.Stat(genFile); err == nil {\n\t\t// if file existed, do nothing and do not throw an error\n\t\treturn nil\n\t} else {\n\t\tgenDoc := types.GenesisDoc{\n\t\t\tChainID: fmt.Sprintf(\"vastchain-test-%v\", utils.RandomStr(6)),\n\t\t\tGenesisTime: time.Now(),\n\t\t\tConsensusParams: types.DefaultConsensusParams(),\n\t\t}\n\n\t\tgenDoc.Validators = []types.GenesisValidator{}\n\t\tfor _, validator := range validators {\n\t\t\tgenDoc.Validators = append(genDoc.Validators, types.GenesisValidator{\n\t\t\t\tAddress: validator.Address(),\n\t\t\t\tPubKey: validator,\n\t\t\t\tPower: 10,\n\t\t\t})\n\t\t}\n\n\t\tif err := genDoc.SaveAs(genFile); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (cm *chainManager) MintNewBlock(timestamp time.Time) (*block.Block, error) {\n\treturn cm.bc.MintNewBlock(timestamp)\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func (br *BlockRepository) RetrieveGenesis() (*types.Block, *rTypes.Error) {\n\trf := &recordFile{}\n\tif br.dbClient.Where(&recordFile{PrevHash: genesisPreviousHash}).Find(rf).RecordNotFound() {\n\t\treturn nil, errors.Errors[errors.BlockNotFound]\n\t}\n\n\treturn &types.Block{\n\t\tIndex: 0,\n\t\tHash: rf.FileHash,\n\t\tConsensusStartNanos: rf.ConsensusStart,\n\t\tConsensusEndNanos: rf.ConsensusEnd,\n\t}, nil\n}", "func Test_MineBlock_MineBlock(t *testing.T) {\n\tvar block = &Block{\n\t\tIndex: 0,\n\t\tHash: \"\",\n\t\tTransactions: []*transactions.Transaction{\n\t\t\t{\n\t\t\t\tID: \"transactionID\",\n\t\t\t\tInputs: []*transactions.TransactionInput{\n\t\t\t\t\t{\n\t\t\t\t\t\tOutputID: \"output-ID\",\n\t\t\t\t\t\tOutputIndex: 1,\n\t\t\t\t\t\tSignature: \"signature\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutputs: []*transactions.TransactionOutput{\n\t\t\t\t\t{\n\t\t\t\t\t\tAddress: \"address\",\n\t\t\t\t\t\tAmount: 25,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMessage: \"my genesis block!!\",\n\t\tPreviousHash: \"\",\n\t\tTimestamp: time.Unix(1465154705, 0),\n\t\tDifficulty: 5,\n\t\tNonce: 0,\n\t}\n\n\t// hash block\n\tblock.MineBlock()\n\n\t// result should be correct hash\n\texpectedHash := \"01cae462faef5b5132df4a29cba801c620813bc7033ad8ae7d4ad8a8806bb7ca\"\n\tif block.Hash != expectedHash {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %s Expected: %s\", block.Hash, expectedHash)\n\t}\n\texpectedNonce := 4\n\tif block.Nonce != expectedNonce {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %d Expected: %d\", block.Nonce, expectedNonce)\n\t}\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func (m *Miner) blockForWork() (types.Block, crypto.Hash, types.Target) {\n\t// Determine the timestamp.\n\tblockTimestamp := types.CurrentTimestamp()\n\tif blockTimestamp < m.earliestTimestamp {\n\t\tblockTimestamp = m.earliestTimestamp\n\t}\n\n\t// Create the miner payouts.\n\tsubsidy := types.CalculateCoinbase(m.height + 1)\n\tfor _, txn := range m.transactions {\n\t\tfor _, fee := range txn.MinerFees {\n\t\t\tsubsidy = subsidy.Add(fee)\n\t\t}\n\t}\n\tblockPayouts := []types.SiacoinOutput{types.SiacoinOutput{Value: subsidy, UnlockHash: m.address}}\n\n\t// Create the list of transacitons, including the randomized transaction.\n\t// The transactions are assembled by calling append(singleElem,\n\t// existingSlic) because doing it the reverse way has some side effects,\n\t// creating a race condition and ultimately changing the block hash for\n\t// other parts of the program. This is related to the fact that slices are\n\t// pointers, and not immutable objects. Use of the builtin `copy` function\n\t// when passing objects like blocks around may fix this problem.\n\trandBytes := make([]byte, 16)\n\trand.Read(randBytes)\n\trandTxn := types.Transaction{\n\t\tArbitraryData: []string{\"NonSia\" + string(randBytes)},\n\t}\n\tblockTransactions := append([]types.Transaction{randTxn}, m.transactions...)\n\n\t// Assemble the block\n\tb := types.Block{\n\t\tParentID: m.parent,\n\t\tTimestamp: blockTimestamp,\n\t\tMinerPayouts: blockPayouts,\n\t\tTransactions: blockTransactions,\n\t}\n\n\treturn b, b.MerkleRoot(), m.target\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func InitDbWithBitCloutGenesisBlock(params *BitCloutParams, handle *badger.DB) error {\n\t// Construct a node for the genesis block. Its height is zero and it has\n\t// no parents. Its difficulty should be set to the initial\n\t// difficulty specified in the parameters and it should be assumed to be\n\t// valid and stored by the end of this function.\n\tgenesisBlock := params.GenesisBlock\n\tdiffTarget := NewBlockHash(params.MinDifficultyTargetHex)\n\tblockHash := NewBlockHash(params.GenesisBlockHashHex)\n\tgenesisNode := NewBlockNode(\n\t\tnil, // Parent\n\t\tblockHash,\n\t\t0, // Height\n\t\tdiffTarget,\n\t\tBytesToBigint(ExpectedWorkForBlockHash(diffTarget)[:]), // CumWork\n\t\tgenesisBlock.Header, // Header\n\t\tStatusHeaderValidated|StatusBlockProcessed|StatusBlockStored|StatusBlockValidated, // Status\n\t)\n\n\t// Set the fields in the db to reflect the current state of our chain.\n\t//\n\t// Set the best hash to the genesis block in the db since its the only node\n\t// we're currently aware of. Set it for both the header chain and the block\n\t// chain.\n\tif err := PutBestHash(blockHash, handle, ChainTypeBitCloutBlock); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting genesis block hash into db for block chain\")\n\t}\n\t// Add the genesis block to the (hash -> block) index.\n\tif err := PutBlock(genesisBlock, handle); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting genesis block into db\")\n\t}\n\t// Add the genesis block to the (height, hash -> node info) index in the db.\n\tif err := PutHeightHashToNodeInfo(genesisNode, handle, false /*bitcoinNodes*/); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting (height, hash -> node) in db\")\n\t}\n\tif err := DbPutNanosPurchased(handle, params.BitCloutNanosPurchasedAtGenesis); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting genesis block hash into db for block chain\")\n\t}\n\tif err := DbPutGlobalParamsEntry(handle, InitialGlobalParamsEntry); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting GlobalParamsEntry into db for block chain\")\n\t}\n\n\t// We apply seed transactions here. This step is useful for setting\n\t// up the blockchain with a particular set of transactions, e.g. when\n\t// hard forking the chain.\n\t//\n\t// TODO: Right now there's an issue where if we hit an errur during this\n\t// step of the initialization, the next time we run the program it will\n\t// think things are initialized because we set the best block hash at the\n\t// top. We should fix this at some point so that an error in this step\n\t// wipes out the best hash.\n\tutxoView, err := NewUtxoView(handle, params, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"InitDbWithBitCloutGenesisBlock: Error initializing UtxoView\")\n\t}\n\n\t// Add the seed balances to the view.\n\tfor index, txOutput := range params.SeedBalances {\n\t\toutputKey := UtxoKey{\n\t\t\tTxID: BlockHash{},\n\t\t\tIndex: uint32(index),\n\t\t}\n\t\tutxoEntry := UtxoEntry{\n\t\t\tAmountNanos: txOutput.AmountNanos,\n\t\t\tPublicKey: txOutput.PublicKey,\n\t\t\tBlockHeight: 0,\n\t\t\t// Just make this a normal transaction so that we don't have to wait for\n\t\t\t// the block reward maturity.\n\t\t\tUtxoType: UtxoTypeOutput,\n\t\t\tUtxoKey: &outputKey,\n\t\t}\n\n\t\t_, err := utxoView._addUtxo(&utxoEntry)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"InitDbWithBitCloutGenesisBlock: Error adding \"+\n\t\t\t\t\"seed balance at index %v ; output: %v: %v\", index, txOutput, err)\n\t\t}\n\t}\n\n\t// Add the seed txns to the view\n\tfor txnIndex, txnHex := range params.SeedTxns {\n\t\ttxnBytes, err := hex.DecodeString(txnHex)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"InitDbWithBitCloutGenesisBlock: Error decoding seed \"+\n\t\t\t\t\t\"txn HEX: %v, txn index: %v, txn hex: %v\",\n\t\t\t\terr, txnIndex, txnHex)\n\t\t}\n\t\ttxn := &MsgBitCloutTxn{}\n\t\tif err := txn.FromBytes(txnBytes); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"InitDbWithBitCloutGenesisBlock: Error decoding seed \"+\n\t\t\t\t\t\"txn BYTES: %v, txn index: %v, txn hex: %v\",\n\t\t\t\terr, txnIndex, txnHex)\n\t\t}\n\t\t// Important: ignoreUtxos makes it so that the inputs/outputs aren't\n\t\t// processed, which is important.\n\t\t// Set txnSizeBytes to 0 here as the minimum network fee is 0 at genesis block, so there is no need to serialize\n\t\t// these transactions to check if they meet the minimum network fee requirement.\n\t\t_, _, _, _, err = utxoView.ConnectTransaction(\n\t\t\ttxn, txn.Hash(), 0, 0 /*blockHeight*/, false /*verifySignatures*/, true /*ignoreUtxos*/)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"InitDbWithBitCloutGenesisBlock: Error connecting transaction: %v, \"+\n\t\t\t\t\t\"txn index: %v, txn hex: %v\",\n\t\t\t\terr, txnIndex, txnHex)\n\t\t}\n\t}\n\t// Flush all the data in the view.\n\terr = utxoView.FlushToDb()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"InitDbWithBitCloutGenesisBlock: Error flushing seed txns to DB: %v\", err)\n\t}\n\n\treturn nil\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func (h *Harness) GenerateAndSubmitBlock(\n\ttxns []*util.Tx, blockVersion uint32,\n\tblockTime time.Time,\n) (*block.Block, error) {\n\treturn h.GenerateAndSubmitBlockWithCustomCoinbaseOutputs(\n\t\ttxns,\n\t\tblockVersion, blockTime, []wire.TxOut{},\n\t)\n}", "func GenerateGenesisTx(shard shard.Index) *wire.MsgTx {\n\tsetTotalAmountOfEachShard()\n\treturn NewMsgTx(wire.TxVersion, shard)\n}", "func addBlockToBlockchain(t *testing.T, bc *Blockchain) (coin.Block, coin.UxOut) {\n\t// Split the genesis block into two transactions\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 1)\n\tux := bc.GetUnspent().Array()[0]\n\tassert.Equal(t, ux.Body.Address, genAddress)\n\tpub := cipher.PubKeyFromSecKey(genSecret)\n\tassert.Equal(t, genAddress, cipher.AddressFromPubKey(pub))\n\tsig := cipher.SignHash(ux.Hash(), genSecret)\n\tassert.Nil(t, cipher.ChkSig(ux.Body.Address, ux.Hash(), sig))\n\n\ttx, sec := makeTransactionForChainWithHoursFee(t, bc, ux, genSecret, 0, 0)\n\tb, err := bc.NewBlockFromTransactions(coin.Transactions{tx}, _incTime)\n\tassert.Nil(t, err)\n\tassertExecuteBlock(t, bc, b, tx)\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 2)\n\n\t// Spend one of them\n\t// The other will have hours now\n\tux = coin.UxOut{}\n\tfor _, u := range bc.GetUnspent().Pool {\n\t\tif u.Body.Address != genAddress {\n\t\t\tux = u\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.NotEqual(t, ux.Body.Address, cipher.Address{})\n\tassert.NotEqual(t, ux.Body.Address, genAddress)\n\tpub = cipher.PubKeyFromSecKey(sec)\n\taddr := cipher.AddressFromPubKey(pub)\n\tassert.Equal(t, ux.Body.Address, addr)\n\ttx, _ = makeTransactionForChainWithHoursFee(t, bc, ux, sec, 0, 0)\n\tb, err = bc.NewBlockFromTransactions(coin.Transactions{tx},\n\t\tbc.Time()+_incTime)\n\tassert.Nil(t, err)\n\tassertExecuteBlock(t, bc, b, tx)\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 2)\n\n\t// Check that the output in the 2nd block is owned by genesis,\n\t// and has coin hours\n\tfor _, u := range bc.GetUnspent().Pool {\n\t\tif u.Body.Address == genAddress {\n\t\t\tux = u\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Equal(t, ux.Body.Address, genAddress)\n\tassert.Equal(t, ux.Head.BkSeq, uint64(1))\n\tassert.True(t, ux.CoinHours(bc.Time()) > 0)\n\n\treturn b, ux\n}", "func makeGenesis(noms types.ValueReadWriter, serverStateID string, dataRef types.Ref, checksum types.String, lastMutationID uint64) Commit {\n\tc := Commit{}\n\t// Note: no c.Parents.\n\tc.Meta.Snapshot.LastMutationID = lastMutationID\n\tc.Meta.Snapshot.ServerStateID = serverStateID\n\tc.Value.Data = dataRef\n\tc.Value.Checksum = checksum\n\tc.NomsStruct = marshal.MustMarshal(noms, c).(types.Struct)\n\treturn c\n}", "func CreateBlock(transactions []*Transaction, prevHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevHash, []byte{}, 0}\n\tpow := CreatePoW(block)\n\tnonce, hash := pow.Mine()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func (g *testGenerator) nextBlock(blockName string, spend *spendableOut, ticketSpends []spendableOut, mungers ...func(*wire.MsgBlock)) *wire.MsgBlock {\n\t// Generate the sorted live ticket pool for the current tip.\n\tliveTickets := g.sortedLiveTickets(g.tip)\n\tnextHeight := g.tip.Header.Height + 1\n\n\t// Calculate the next required stake difficulty (aka ticket price).\n\tticketPrice := dcrutil.Amount(g.calcNextRequiredStakeDifficulty())\n\n\t// Generate the appropriate votes and ticket purchases based on the\n\t// current tip block and provided ticket spendable outputs.\n\tvar stakeTxns []*wire.MsgTx\n\tvar finalState [6]byte\n\tif nextHeight > uint32(g.params.CoinbaseMaturity) {\n\t\t// Generate votes once the stake validation height has been\n\t\t// reached.\n\t\tif int64(nextHeight) >= g.params.StakeValidationHeight {\n\t\t\t// Generate and add the vote transactions for the\n\t\t\t// winning tickets to the stake tree.\n\t\t\tnumVotes := g.params.TicketsPerBlock\n\t\t\twinners, stateHash, err := winningTickets(g.tip,\n\t\t\t\tliveTickets, numVotes)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tfor _, ticket := range winners {\n\t\t\t\tvoteTx := g.createVoteTx(g.tip, ticket)\n\t\t\t\tstakeTxns = append(stakeTxns, voteTx)\n\t\t\t}\n\n\t\t\t// Calculate the final lottery state hash for use in the\n\t\t\t// block header.\n\t\t\tfinalState = calcFinalLotteryState(winners, stateHash)\n\t\t}\n\n\t\t// Generate ticket purchases (sstx) using the provided spendable\n\t\t// outputs.\n\t\tif ticketSpends != nil {\n\t\t\tconst ticketFee = dcrutil.Amount(2)\n\t\t\tfor i := 0; i < len(ticketSpends); i++ {\n\t\t\t\tout := &ticketSpends[i]\n\t\t\t\tpurchaseTx := g.createTicketPurchaseTx(out,\n\t\t\t\t\tticketPrice, ticketFee)\n\t\t\t\tstakeTxns = append(stakeTxns, purchaseTx)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Count the number of ticket purchases (sstx), votes (ssgen), and\n\t// ticket revocations (ssrtx) and calculate the total PoW fees generated\n\t// by the stake transactions.\n\tvar numVotes uint16\n\tvar numTicketPurchases, numTicketRevocations uint8\n\tvar stakeTreeFees dcrutil.Amount\n\tfor _, tx := range stakeTxns {\n\t\tswitch {\n\t\tcase isVoteTx(tx):\n\t\t\tnumVotes++\n\t\tcase isTicketPurchaseTx(tx):\n\t\t\tnumTicketPurchases++\n\t\tcase isRevocationTx(tx):\n\t\t\tnumTicketRevocations++\n\t\t}\n\n\t\t// Calculate any fees for the transaction.\n\t\tvar inputSum, outputSum dcrutil.Amount\n\t\tfor _, txIn := range tx.TxIn {\n\t\t\tinputSum += dcrutil.Amount(txIn.ValueIn)\n\t\t}\n\t\tfor _, txOut := range tx.TxOut {\n\t\t\toutputSum += dcrutil.Amount(txOut.Value)\n\t\t}\n\t\tstakeTreeFees += (inputSum - outputSum)\n\t}\n\n\t// Create a standard coinbase and spending transaction.\n\tvar regularTxns []*wire.MsgTx\n\t{\n\t\t// Create coinbase transaction for the block with no additional\n\t\t// dev or pow subsidy.\n\t\tcoinbaseTx := g.createCoinbaseTx(nextHeight, numVotes)\n\t\tregularTxns = []*wire.MsgTx{coinbaseTx}\n\n\t\t// Increase the PoW subsidy to account for any fees in the stake\n\t\t// tree.\n\t\tcoinbaseTx.TxOut[2].Value += int64(stakeTreeFees)\n\n\t\t// Create a transaction to spend the provided utxo if needed.\n\t\tif spend != nil {\n\t\t\t// Create the transaction with a fee of 1 atom for the\n\t\t\t// miner and increase the PoW subsidy accordingly.\n\t\t\tfee := dcrutil.Amount(1)\n\t\t\tcoinbaseTx.TxOut[2].Value += int64(fee)\n\n\t\t\t// Create a transaction that spends from the provided\n\t\t\t// spendable output and includes an additional unique\n\t\t\t// OP_RETURN output to ensure the transaction ends up\n\t\t\t// with a unique hash, then add it to the list of\n\t\t\t// transactions to include in the block. The script is\n\t\t\t// a simple OP_TRUE p2sh script in order to avoid the\n\t\t\t// need to track addresses and signature scripts in the\n\t\t\t// tests.\n\t\t\tspendTx := g.createSpendTx(spend, fee)\n\t\t\tregularTxns = append(regularTxns, spendTx)\n\t\t}\n\t}\n\n\t// Use a timestamp that is 7/8 of target timespan after the previous\n\t// block unless this is the first block in which case the current time\n\t// is used. This helps maintain the retarget difficulty low. Also,\n\t// ensure the timestamp is limited to one second precision.\n\tvar ts time.Time\n\tif nextHeight == 1 {\n\t\tts = time.Now()\n\t} else {\n\n\t\tts = g.tip.Header.Timestamp.Add(g.params.TargetTimespan * 7 / 8)\n\t}\n\tts = time.Unix(ts.Unix(), 0)\n\n\t// Create the unsolved block.\n\tblock := wire.MsgBlock{\n\t\tHeader: wire.BlockHeader{\n\t\t\tVersion: 1,\n\t\t\tPrevBlock: g.tip.BlockHash(),\n\t\t\tMerkleRoot: calcMerkleRoot(regularTxns),\n\t\t\tStakeRoot: calcMerkleRoot(stakeTxns),\n\t\t\tVoteBits: 1,\n\t\t\tFinalState: finalState,\n\t\t\tVoters: numVotes,\n\t\t\tFreshStake: numTicketPurchases,\n\t\t\tRevocations: numTicketRevocations,\n\t\t\tPoolSize: uint32(len(liveTickets)),\n\t\t\tBits: g.calcNextRequiredDifficulty(),\n\t\t\tSBits: int64(ticketPrice),\n\t\t\tHeight: nextHeight,\n\t\t\tSize: 0, // Filled in below.\n\t\t\tTimestamp: ts,\n\t\t\tNonce: 0, // To be solved.\n\t\t\tExtraData: [32]byte{},\n\t\t\tStakeVersion: 0,\n\t\t},\n\t\tTransactions: regularTxns,\n\t\tSTransactions: stakeTxns,\n\t}\n\tblock.Header.Size = uint32(block.SerializeSize())\n\n\t// Perform any block munging just before solving. Only recalculate the\n\t// merkle roots and block size if they weren't manually changed by a\n\t// munge function.\n\tcurMerkleRoot := block.Header.MerkleRoot\n\tcurStakeRoot := block.Header.StakeRoot\n\tcurSize := block.Header.Size\n\tcurNonce := block.Header.Nonce\n\tfor _, f := range mungers {\n\t\tf(&block)\n\t}\n\tif block.Header.MerkleRoot == curMerkleRoot {\n\t\tblock.Header.MerkleRoot = calcMerkleRoot(block.Transactions)\n\t}\n\tif block.Header.StakeRoot == curStakeRoot {\n\t\tblock.Header.StakeRoot = calcMerkleRoot(block.STransactions)\n\t}\n\tif block.Header.Size == curSize {\n\t\tblock.Header.Size = uint32(block.SerializeSize())\n\t}\n\n\t// Only solve the block if the nonce wasn't manually changed by a munge\n\t// function.\n\tif block.Header.Nonce == curNonce && !solveBlock(&block.Header) {\n\t\tpanic(fmt.Sprintf(\"Unable to solve block at height %d\",\n\t\t\tblock.Header.Height))\n\t}\n\n\t// Update generator state and return the block.\n\tblockHash := block.BlockHash()\n\tg.blocks[blockHash] = &block\n\tg.blocksByName[blockName] = &block\n\tg.tip = &block\n\tg.tipName = blockName\n\treturn &block\n}", "func NewGenesis(eg *ent.EntityGenerator, sim *sim.Simulation) *Genesis {\n\treturn &Genesis{eg, sim}\n}", "func InitBlockchain() {\n\t// fmt.Println(\"******TODO: IMPLEMENT InitBlockchain!******\")\n\tspew.Dump(Blockchain)\n\t// Fill me in, noble warrior.\n\tblock := Block{\"Genesis Block\", time.Now().Unix(), []byte{}, []byte{}}\n\tblock.Hash = block.calculateHash()\n\tBlockchain = append(Blockchain, block)\n}", "func (AppModule) GenerateGenesisState(simState *module.SimulationState) {\n\tsimulation.RandomizedGenState(simState)\n}" ]
[ "0.8338062", "0.79232156", "0.7768899", "0.73699194", "0.7312927", "0.7312893", "0.72981054", "0.7217498", "0.717386", "0.7148623", "0.7148288", "0.7131218", "0.71268797", "0.7094627", "0.7069991", "0.69981176", "0.69953555", "0.698607", "0.6977885", "0.6955806", "0.6951625", "0.6951625", "0.6951625", "0.694583", "0.69370866", "0.69290334", "0.6840799", "0.6794684", "0.6776669", "0.67760915", "0.67124414", "0.670947", "0.67013085", "0.669612", "0.66947836", "0.6689688", "0.66832745", "0.6659884", "0.6657396", "0.66259426", "0.66248554", "0.66078407", "0.65963304", "0.65430886", "0.6534655", "0.6525931", "0.65136516", "0.6506715", "0.6498454", "0.64819676", "0.6480441", "0.6475797", "0.6472426", "0.64711505", "0.6461617", "0.6446771", "0.641811", "0.64151233", "0.6409129", "0.6403723", "0.63806564", "0.63782096", "0.6367044", "0.63669217", "0.6366794", "0.63589686", "0.6354048", "0.63203", "0.6317886", "0.6297935", "0.62708884", "0.62549704", "0.6242733", "0.6237559", "0.62342936", "0.62173325", "0.620966", "0.620087", "0.620087", "0.6179268", "0.61674637", "0.61543477", "0.6154254", "0.61481255", "0.6139161", "0.61369693", "0.61306643", "0.6122116", "0.6120911", "0.6120355", "0.61166614", "0.6113514", "0.6108212", "0.61026305", "0.6085564", "0.60830176", "0.6071071", "0.60642403", "0.6062159", "0.6062023" ]
0.8215045
1
Perform tests to validate if a specific block is valid by comparing it to its own values
func isBlockValid(prior Block, current Block) bool { return true }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestBaseGradedBlock_Valid(t *testing.T) {\n\tt.Run(\"V1\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_valid(t, 1)\n\t})\n\tt.Run(\"V2\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_valid(t, 2)\n\t})\n\tt.Run(\"V3\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_valid(t, 3)\n\t})\n\tt.Run(\"V4\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_valid(t, 4)\n\t})\n\tt.Run(\"V5\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_valid(t, 5)\n\t})\n}", "func isBlockValid(newBlock, oldBlock Block) bool {\n\tif oldBlock.Index+1 != newBlock.Index {\n\t\tfmt.Println(\"Invalid index !!\", newBlock.Index, oldBlock.Index)\n\t\treturn false\n\t}\n\n\tif oldBlock.Hash != newBlock.PrevHash {\n\t\tfmt.Println(\"Invalid prev hash !!\")\n\t\treturn false\n\t}\n\n\tif calculateBlockHash(newBlock) != newBlock.Hash {\n\t\tfmt.Println(\"Invalid hash !!\")\n\t\treturn false\n\t}\n\tif !isServerData(newBlock.Data, newBlock.Hash) {\n\t\treturn false\n\t}\n\treturn true\n}", "func validate(b *protocol.Block, initialSetup bool) error {\n\n\t//This mutex is necessary that own-mined blocks and received blocks from the network are not\n\t//validated concurrently.\n\tblockValidation.Lock()\n\tdefer blockValidation.Unlock()\n\n\tif storage.ReadClosedBlock(b.Hash) != nil {\n\t\tlogger.Printf(\"Received block (%x) has already been validated.\\n\", b.Hash[0:8])\n\t\treturn errors.New(\"Received Block has already been validated.\")\n\t}\n\n\t//Prepare datastructure to fill tx payloads.\n\tblockDataMap := make(map[[32]byte]blockData)\n\n\t//Get the right branch, and a list of blocks to rollback (if necessary).\n\tblocksToRollback, blocksToValidate, err := getBlockSequences(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocksToRollback) > 0 {\n\t\tlogger.Printf(\" _____________________\")\n\t\tlogger.Printf(\"| Blocks To Rollback: |________________________________________________\")\n\t\tfor _, block := range blocksToRollback {\n\t\t\tlogger.Printf(\"| - %x |\", block.Hash)\n\t\t}\n\t\tlogger.Printf(\"|______________________________________________________________________|\")\n\t\tlogger.Printf(\" _____________________\")\n\t\tlogger.Printf(\"| Blocks To Validate: |________________________________________________\")\n\t\tfor _, block := range blocksToValidate {\n\t\t\tlogger.Printf(\"| - %x |\", block.Hash)\n\t\t}\n\t\tlogger.Printf(\"|______________________________________________________________________|\")\n\t}\n\n\t//Verify block time is dynamic and corresponds to system time at the time of retrieval.\n\t//If we are syncing or far behind, we cannot do this dynamic check,\n\t//therefore we include a boolean uptodate. If it's true we consider ourselves uptodate and\n\t//do dynamic time checking.\n\tif len(blocksToValidate) > DELAYED_BLOCKS {\n\t\tuptodate = false\n\t} else {\n\t\tuptodate = true\n\t}\n\n\t//No rollback needed, just a new block to validate.\n\tif len(blocksToRollback) == 0 {\n\t\tfor i, block := range blocksToValidate {\n\t\t\t//Fetching payload data from the txs (if necessary, ask other miners).\n\t\t\taccTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice, err := preValidate(block, initialSetup)\n\n\t\t\t//Check if the validator that added the block has previously voted on different competing chains (find slashing proof).\n\t\t\t//The proof will be stored in the global slashing dictionary.\n\t\t\tif block.Height > 0 {\n\t\t\t\tseekSlashingProof(block)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tblockDataMap[block.Hash] = blockData{accTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice,block}\n\t\t\tif err := validateState(blockDataMap[block.Hash], initialSetup); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpostValidate(blockDataMap[block.Hash], initialSetup)\n\t\t\tif i != len(blocksToValidate)-1 {\n\t\t\t\tlogger.Printf(\"Validated block (During Validation of other block %v): %vState:\\n%v\", b.Hash[0:8] , block, getState())\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//Rollback\n\t\tfor _, block := range blocksToRollback {\n\t\t\tif err := rollback(block); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t//Validation of new chain\n\t\tfor _, block := range blocksToValidate {\n\t\t\t//Fetching payload data from the txs (if necessary, ask other miners).\n\t\t\taccTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice, err := preValidate(block, initialSetup)\n\n\t\t\t//Check if the validator that added the block has previously voted on different competing chains (find slashing proof).\n\t\t\t//The proof will be stored in the global slashing dictionary.\n\t\t\tif block.Height > 0 {\n\t\t\t\tseekSlashingProof(block)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tblockDataMap[block.Hash] = blockData{accTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice,block}\n\t\t\tif err := validateState(blockDataMap[block.Hash], initialSetup); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpostValidate(blockDataMap[block.Hash], initialSetup)\n\t\t\t//logger.Printf(\"Validated block (after rollback): %x\", block.Hash[0:8])\n\t\t\tlogger.Printf(\"Validated block (after rollback for block %v): %vState:\\n%v\", b.Hash[0:8], block, getState())\n\t\t}\n\t}\n\n\treturn nil\n}", "func Test_ValidateBlockTransactions_IsValid(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif !result {\n\t\tt.Errorf(\"block transactions are valid so the result should be true\")\n\t}\n}", "func TestCheckBlockSanity(t *testing.T) {\n\tpocLimit := config.ChainParams.PocLimit\n\tblock, err := loadNthBlk(22)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tblk0, err := loadNthBlk(1)\n\tassert.Nil(t, err)\n\n\terr = CheckBlockSanity(block, blk0.MsgBlock().Header.ChainID, pocLimit)\n\tassert.Nil(t, err)\n\n\t// Ensure a block that has a timestamp with a precision higher than one\n\t// second fails.\n\ttimestamp := block.MsgBlock().Header.Timestamp\n\tblock.MsgBlock().Header.Timestamp = timestamp.Add(time.Nanosecond)\n\terr = CheckBlockSanity(block, blk0.MsgBlock().Header.ChainID, pocLimit)\n\tassert.Equal(t, ErrInvalidTime, err)\n}", "func isBlockValid(newBlock, oldBlock Block) bool {\n\tif oldBlock.Index+1 != newBlock.Index {\n\t\treturn false\n\t}\n\n\tif oldBlock.Hash != newBlock.PrevHash {\n\t\treturn false\n\t}\n\n\tif calculateHash(newBlock) != newBlock.Hash {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func isBlockValid(newBlock *Block, oldBlock *Block) bool {\n\tif oldBlock.Index+1 != newBlock.Index {\n\t\treturn false\n\t}\n\n\tif oldBlock.Hash != newBlock.PrevHash {\n\t\treturn false\n\t}\n\n\tif calculateHash(newBlock) != newBlock.Hash {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (v *validator) Validate(blk *Block, tipHeight uint64, tipHash common.Hash32B) error {\n\tif blk == nil {\n\t\treturn ErrInvalidBlock\n\t}\n\t// verify new block has height incremented by 1\n\tif blk.Header.height != 0 && blk.Header.height != tipHeight+1 {\n\t\treturn errors.Wrapf(\n\t\t\tErrInvalidTipHeight,\n\t\t\t\"Wrong block height %d, expecting %d\",\n\t\t\tblk.Header.height,\n\t\t\ttipHeight+1)\n\t}\n\t// verify new block has correctly linked to current tip\n\tif blk.Header.prevBlockHash != tipHash {\n\t\treturn errors.Wrapf(\n\t\t\tErrInvalidBlock,\n\t\t\t\"Wrong prev hash %x, expecting %x\",\n\t\t\tblk.Header.prevBlockHash,\n\t\t\ttipHash)\n\t}\n\n\tif v.utk != nil {\n\t\tif err := v.utk.ValidateUtxo(blk); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif v.sf != nil {\n\t\t// TODO: exam txs based on states\n\t}\n\n\treturn nil\n}", "func isBlockValidated(block Block, validateNum int) bool {\n\tif validateNum == 0 {\n\t\treturn true\n\t} else {\n\t\tfor _, child := range block.ChildrenHashes {\n\t\t\tmutex.Lock()\n\t\t\tchildBlock := blockChain[child]\n\t\t\tmutex.Unlock()\n\t\t\tfmt.Println(\"The child block has depth:\", childBlock.Depth)\n\t\t\tif isBlockValidated(childBlock, validateNum-1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}", "func isBlockValid(newBlock, oldBlock Block) bool {\n\tif oldBlock.Index+1 != newBlock.Index {\n\t\treturn false\n\t}\n\n\tif oldBlock.Hash != newBlock.PrevHash {\n\t\treturn false\n\t}\n\n\tif calculateBlockHash(newBlock) != newBlock.Hash {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (b Block) Validate(prevHash []byte) bool {\n\tif bytes.Compare(b.prevHash, prevHash) != 0 {\n\t\treturn false\n\t}\n\n\tif bytes.Compare(b.hash, b.createHash()) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func isValidBlock(newBlock, oldBlock Block) bool {\n\tif oldBlock.Index+1 != newBlock.Index {\n\t\treturn false\n\t}\n\n\tif oldBlock.Hash != newBlock.PrevHash {\n\t\treturn false\n\t}\n\n\tif calculateBlockHash(newBlock) != newBlock.Hash {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func TestCheckBlockSanity(t *testing.T) {\n\tparams := chaincfg.RegNetParams()\n\ttimeSource := NewMedianTime()\n\tblock := dcrutil.NewBlock(&badBlock)\n\terr := CheckBlockSanity(block, timeSource, params)\n\tif err == nil {\n\t\tt.Fatalf(\"block should fail.\\n\")\n\t}\n}", "func (bc BlockChain) Validate() bool {\n\tprevHash := []byte{0}\n\tvalide := true\n\tfor _, b := range bc.Blocks {\n\t\tvalide = valide && b.Validate(prevHash)\n\t\tprevHash = b.hash\n\t\tif !valide {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn valide\n}", "func BlockChainInfoValidation(Block *block.Block) (error) {\n ResponseBlock := block.ResponseBlock{}\n blockHash := ReverseEndian(Block.BlockHash)\n fmt.Println(\"block hash\", blockHash)\n resp, err := http.Get(BLOCKCHAININFOENDPOINT + blockHash)\n if err != nil {\n return err\n }\n defer resp.Body.Close()\n body, _ := ioutil.ReadAll(resp.Body)\n json.Unmarshal(body, &ResponseBlock)\n\n if blockHash == ResponseBlock.Hash {\n fmt.Println(\"Height: \", ResponseBlock.Height)\n return nil\n }\n return errors.New(\"Hashes do not match\")\n}", "func isNewBlockValid(newBlock Block) bool {\n\tlastBlock := Blockchain[len(Blockchain)-1]\n\tif lastBlock.Index+1 == newBlock.Index && makeLastBlockHeaderHash(lastBlock) == newBlock.PrevHashHeader && newBlock.blockHash == makeBlockHash(newBlock) {\n\t\treturn true\n\t}\n\treturn false\n}", "func TestBaseGradedBlock_Invalid(t *testing.T) {\n\tt.Run(\"V1\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_Invalid(t, 1)\n\t})\n\tt.Run(\"V2\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_Invalid(t, 2)\n\t})\n\tt.Run(\"V3\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_Invalid(t, 3)\n\t})\n\tt.Run(\"V4\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_Invalid(t, 4)\n\t})\n\tt.Run(\"V5\", func(t *testing.T) {\n\t\ttestBaseGradedBlock_Invalid(t, 5)\n\t})\n}", "func (t *Tortoise) OnValidBlock(header types.BlockHeader) {\n\tstart := time.Now()\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\twaitBlockDuration.Observe(float64(time.Since(start).Nanoseconds()))\n\tt.trtl.onBlock(header, true, true)\n\tif t.tracer != nil {\n\t\tt.tracer.On(&BlockTrace{Header: header, Valid: true})\n\t}\n}", "func TestValidBlockchain(t *testing.T) {\n\tblockchain := Blockchain{}\n\tblockchain.AddBlock(\"hello\")\n\tblockchain.AddBlock(\"data\")\n\n\tassertEq(t, blockchain.IsValid(), true)\n}", "func (syncer *Syncer) ValidateBlock(ctx context.Context, b *types.FullBlock) (err error) {\n\tdefer func() {\n\t\t// b.Cid() could panic for empty blocks that are used in tests.\n\t\tif rerr := recover(); rerr != nil {\n\t\t\terr = xerrors.Errorf(\"validate block panic: %w\", rerr)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tisValidated, err := syncer.store.IsBlockValidated(ctx, b.Cid())\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"check block validation cache %s: %w\", b.Cid(), err)\n\t}\n\n\tif isValidated {\n\t\treturn nil\n\t}\n\n\tvalidationStart := build.Clock.Now()\n\tdefer func() {\n\t\tstats.Record(ctx, metrics.BlockValidationDurationMilliseconds.M(metrics.SinceInMilliseconds(validationStart)))\n\t\tlog.Infow(\"block validation\", \"took\", time.Since(validationStart), \"height\", b.Header.Height, \"age\", time.Since(time.Unix(int64(b.Header.Timestamp), 0)))\n\t}()\n\n\tctx, span := trace.StartSpan(ctx, \"validateBlock\")\n\tdefer span.End()\n\n\tif err := blockSanityChecks(b.Header); err != nil {\n\t\treturn xerrors.Errorf(\"incoming header failed basic sanity checks: %w\", err)\n\t}\n\n\th := b.Header\n\n\tbaseTs, err := syncer.store.LoadTipSet(types.NewTipSetKey(h.Parents...))\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"load parent tipset failed (%s): %w\", h.Parents, err)\n\t}\n\n\tlbts, err := stmgr.GetLookbackTipSetForRound(ctx, syncer.sm, baseTs, h.Height)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to get lookback tipset for block: %w\", err)\n\t}\n\n\tlbst, _, err := syncer.sm.TipSetState(ctx, lbts)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to compute lookback tipset state: %w\", err)\n\t}\n\n\tprevBeacon, err := syncer.store.GetLatestBeaconEntry(baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to get latest beacon entry: %w\", err)\n\t}\n\n\t// fast checks first\n\tnulls := h.Height - (baseTs.Height() + 1)\n\tif tgtTs := baseTs.MinTimestamp() + build.BlockDelaySecs*uint64(nulls+1); h.Timestamp != tgtTs {\n\t\treturn xerrors.Errorf(\"block has wrong timestamp: %d != %d\", h.Timestamp, tgtTs)\n\t}\n\n\tnow := uint64(build.Clock.Now().Unix())\n\tif h.Timestamp > now+build.AllowableClockDriftSecs {\n\t\treturn xerrors.Errorf(\"block was from the future (now=%d, blk=%d): %w\", now, h.Timestamp, ErrTemporal)\n\t}\n\tif h.Timestamp > now {\n\t\tlog.Warn(\"Got block from the future, but within threshold\", h.Timestamp, build.Clock.Now().Unix())\n\t}\n\n\tmsgsCheck := async.Err(func() error {\n\t\tif err := syncer.checkBlockMessages(ctx, b, baseTs); err != nil {\n\t\t\treturn xerrors.Errorf(\"block had invalid messages: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tminerCheck := async.Err(func() error {\n\t\tif err := syncer.minerIsValid(ctx, h.Miner, baseTs); err != nil {\n\t\t\treturn xerrors.Errorf(\"minerIsValid failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tbaseFeeCheck := async.Err(func() error {\n\t\tbaseFee, err := syncer.store.ComputeBaseFee(ctx, baseTs)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"computing base fee: %w\", err)\n\t\t}\n\t\tif types.BigCmp(baseFee, b.Header.ParentBaseFee) != 0 {\n\t\t\treturn xerrors.Errorf(\"base fee doesn't match: %s (header) != %s (computed)\",\n\t\t\t\tb.Header.ParentBaseFee, baseFee)\n\t\t}\n\t\treturn nil\n\t})\n\tpweight, err := syncer.store.Weight(ctx, baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"getting parent weight: %w\", err)\n\t}\n\n\tif types.BigCmp(pweight, b.Header.ParentWeight) != 0 {\n\t\treturn xerrors.Errorf(\"parrent weight different: %s (header) != %s (computed)\",\n\t\t\tb.Header.ParentWeight, pweight)\n\t}\n\n\t// Stuff that needs stateroot / worker address\n\tstateroot, precp, err := syncer.sm.TipSetState(ctx, baseTs)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"get tipsetstate(%d, %s) failed: %w\", h.Height, h.Parents, err)\n\t}\n\n\tif stateroot != h.ParentStateRoot {\n\t\tmsgs, err := syncer.store.MessagesForTipset(baseTs)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to load messages for tipset during tipset state mismatch error: \", err)\n\t\t} else {\n\t\t\tlog.Warn(\"Messages for tipset with mismatching state:\")\n\t\t\tfor i, m := range msgs {\n\t\t\t\tmm := m.VMMessage()\n\t\t\t\tlog.Warnf(\"Message[%d]: from=%s to=%s method=%d params=%x\", i, mm.From, mm.To, mm.Method, mm.Params)\n\t\t\t}\n\t\t}\n\n\t\treturn xerrors.Errorf(\"parent state root did not match computed state (%s != %s)\", stateroot, h.ParentStateRoot)\n\t}\n\n\tif precp != h.ParentMessageReceipts {\n\t\treturn xerrors.Errorf(\"parent receipts root did not match computed value (%s != %s)\", precp, h.ParentMessageReceipts)\n\t}\n\n\twaddr, err := stmgr.GetMinerWorkerRaw(ctx, syncer.sm, lbst, h.Miner)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"GetMinerWorkerRaw failed: %w\", err)\n\t}\n\n\twinnerCheck := async.Err(func() error {\n\t\tif h.ElectionProof.WinCount < 1 {\n\t\t\treturn xerrors.Errorf(\"block is not claiming to be a winner\")\n\t\t}\n\n\t\thp, err := stmgr.MinerHasMinPower(ctx, syncer.sm, h.Miner, lbts)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"determining if miner has min power failed: %w\", err)\n\t\t}\n\n\t\tif !hp {\n\t\t\treturn xerrors.New(\"block's miner does not meet minimum power threshold\")\n\t\t}\n\n\t\trBeacon := *prevBeacon\n\t\tif len(h.BeaconEntries) != 0 {\n\t\t\trBeacon = h.BeaconEntries[len(h.BeaconEntries)-1]\n\t\t}\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := h.Miner.MarshalCBOR(buf); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to marshal miner address to cbor: %w\", err)\n\t\t}\n\n\t\tvrfBase, err := store.DrawRandomness(rBeacon.Data, crypto.DomainSeparationTag_ElectionProofProduction, h.Height, buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"could not draw randomness: %w\", err)\n\t\t}\n\n\t\tif err := VerifyElectionPoStVRF(ctx, waddr, vrfBase, h.ElectionProof.VRFProof); err != nil {\n\t\t\treturn xerrors.Errorf(\"validating block election proof failed: %w\", err)\n\t\t}\n\n\t\tslashed, err := stmgr.GetMinerSlashed(ctx, syncer.sm, baseTs, h.Miner)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to check if block miner was slashed: %w\", err)\n\t\t}\n\n\t\tif slashed {\n\t\t\treturn xerrors.Errorf(\"received block was from slashed or invalid miner\")\n\t\t}\n\n\t\tmpow, tpow, _, err := stmgr.GetPowerRaw(ctx, syncer.sm, lbst, h.Miner)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed getting power: %w\", err)\n\t\t}\n\n\t\tj := h.ElectionProof.ComputeWinCount(mpow.QualityAdjPower, tpow.QualityAdjPower)\n\t\tif h.ElectionProof.WinCount != j {\n\t\t\treturn xerrors.Errorf(\"miner claims wrong number of wins: miner: %d, computed: %d\", h.ElectionProof.WinCount, j)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tblockSigCheck := async.Err(func() error {\n\t\tif err := sigs.CheckBlockSignature(ctx, h, waddr); err != nil {\n\t\t\treturn xerrors.Errorf(\"check block signature failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tbeaconValuesCheck := async.Err(func() error {\n\t\tif os.Getenv(\"LOTUS_IGNORE_DRAND\") == \"_yes_\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err := beacon.ValidateBlockValues(syncer.beacon, h, baseTs.Height(), *prevBeacon); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to validate blocks random beacon values: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\ttktsCheck := async.Err(func() error {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := h.Miner.MarshalCBOR(buf); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to marshal miner address to cbor: %w\", err)\n\t\t}\n\n\t\tif h.Height > build.UpgradeSmokeHeight {\n\t\t\tbuf.Write(baseTs.MinTicket().VRFProof)\n\t\t}\n\n\t\tbeaconBase := *prevBeacon\n\t\tif len(h.BeaconEntries) != 0 {\n\t\t\tbeaconBase = h.BeaconEntries[len(h.BeaconEntries)-1]\n\t\t}\n\n\t\tvrfBase, err := store.DrawRandomness(beaconBase.Data, crypto.DomainSeparationTag_TicketProduction, h.Height-build.TicketRandomnessLookback, buf.Bytes())\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to compute vrf base for ticket: %w\", err)\n\t\t}\n\n\t\terr = VerifyElectionPoStVRF(ctx, waddr, vrfBase, h.Ticket.VRFProof)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"validating block tickets failed: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\twproofCheck := async.Err(func() error {\n\t\tif err := syncer.VerifyWinningPoStProof(ctx, h, *prevBeacon, lbst, waddr); err != nil {\n\t\t\treturn xerrors.Errorf(\"invalid election post: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\tawait := []async.ErrorFuture{\n\t\tminerCheck,\n\t\ttktsCheck,\n\t\tblockSigCheck,\n\t\tbeaconValuesCheck,\n\t\twproofCheck,\n\t\twinnerCheck,\n\t\tmsgsCheck,\n\t\tbaseFeeCheck,\n\t}\n\n\tvar merr error\n\tfor _, fut := range await {\n\t\tif err := fut.AwaitContext(ctx); err != nil {\n\t\t\tmerr = multierror.Append(merr, err)\n\t\t}\n\t}\n\tif merr != nil {\n\t\tmulErr := merr.(*multierror.Error)\n\t\tmulErr.ErrorFormat = func(es []error) string {\n\t\t\tif len(es) == 1 {\n\t\t\t\treturn fmt.Sprintf(\"1 error occurred:\\n\\t* %+v\\n\\n\", es[0])\n\t\t\t}\n\n\t\t\tpoints := make([]string, len(es))\n\t\t\tfor i, err := range es {\n\t\t\t\tpoints[i] = fmt.Sprintf(\"* %+v\", err)\n\t\t\t}\n\n\t\t\treturn fmt.Sprintf(\n\t\t\t\t\"%d errors occurred:\\n\\t%s\\n\\n\",\n\t\t\t\tlen(es), strings.Join(points, \"\\n\\t\"))\n\t\t}\n\t\treturn mulErr\n\t}\n\n\tif err := syncer.store.MarkBlockAsValidated(ctx, b.Cid()); err != nil {\n\t\treturn xerrors.Errorf(\"caching block validation %s: %w\", b.Cid(), err)\n\t}\n\n\treturn nil\n}", "func isBlockChainValid() bool {\n proofPrefix := strings.Repeat(\"0\", difficulty)\n\n for i, currBlock := range blockChain {\n if (i > 0 ) { // Skip first block\n prevBlock := blockChain[i - 1]\n if (currBlock.Index != prevBlock.Index + 1) {\n return false\n }\n if (currBlock.PrevHash != prevBlock.Hash) {\n return false\n }\n if (calculateHash(currBlock) != currBlock.Hash) {\n return false\n }\n if (currBlock.Hash[:difficulty] != proofPrefix) {\n // Work has not been done yet\n return false\n }\n } \n }\n return true\n}", "func assertBlock(block *Block, parentID ids.ID, expectedData []byte, passesVerify bool) error {\n\tif block.Parent() != parentID {\n\t\treturn fmt.Errorf(\"expect parent ID to be %s but was %s\", parentID, block.Parent())\n\t}\n\tif len(block.EncodedData) != len(expectedData) {\n\t\treturn fmt.Errorf(\"expected data to be %v but was %v\", expectedData, block.EncodedData)\n\t}\n\tif block.Verify() != nil && passesVerify {\n\t\treturn fmt.Errorf(\"expected block to pass verification but it fails\")\n\t}\n\tif block.Verify() == nil && !passesVerify {\n\t\treturn fmt.Errorf(\"expected block to fail verification but it passes\")\n\t}\n\treturn nil\n}", "func (bc *BlockCreate) check() error {\n\tif _, ok := bc.mutation.CreateTime(); !ok {\n\t\treturn &ValidationError{Name: \"create_time\", err: errors.New(\"ent: missing required field \\\"create_time\\\"\")}\n\t}\n\tif _, ok := bc.mutation.UpdateTime(); !ok {\n\t\treturn &ValidationError{Name: \"update_time\", err: errors.New(\"ent: missing required field \\\"update_time\\\"\")}\n\t}\n\tif _, ok := bc.mutation.Cid(); !ok {\n\t\treturn &ValidationError{Name: \"cid\", err: errors.New(\"ent: missing required field \\\"cid\\\"\")}\n\t}\n\tif v, ok := bc.mutation.Cid(); ok {\n\t\tif err := block.CidValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"cid\", err: fmt.Errorf(\"ent: validator failed for field \\\"cid\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := bc.mutation.GetType(); !ok {\n\t\treturn &ValidationError{Name: \"type\", err: errors.New(\"ent: missing required field \\\"type\\\"\")}\n\t}\n\tif v, ok := bc.mutation.GetType(); ok {\n\t\tif err := block.TypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"type\", err: fmt.Errorf(\"ent: validator failed for field \\\"type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bc.mutation.ActionType(); ok {\n\t\tif err := block.ActionTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"action_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"action_type\\\": %w\", err)}\n\t\t}\n\t}\n\tif v, ok := bc.mutation.TriggerType(); ok {\n\t\tif err := block.TriggerTypeValidator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"trigger_type\", err: fmt.Errorf(\"ent: validator failed for field \\\"trigger_type\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (env *Env) CheckBlock(pdu *libcoap.Pdu) (bool, *string, *libcoap.Block) {\n blockValue, err := pdu.GetOptionIntegerValue(libcoap.OptionBlock2)\n if err != nil {\n log.WithError(err).Warn(\"Get block2 option value failed.\")\n return false, nil, nil\n\t}\n block := libcoap.IntToBlock(int(blockValue))\n\n size2Value, err := pdu.GetOptionIntegerValue(libcoap.OptionSize2)\n\tif err != nil {\n\t\tlog.WithError(err).Warn(\"Get size 2 option value failed.\")\n return false, nil, nil\n }\n\n eTag := pdu.GetOptionOpaqueValue(libcoap.OptionEtag)\n\n if block != nil {\n isMoreBlock := true\n blockKey := eTag + string(pdu.Token)\n // If block.M = 1, block is more block. If block.M = 0, block is last block\n if block.M == libcoap.MORE_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v) for request (token=%+v), waiting for the next block.\", eTag, block.ToString(), size2Value, pdu.Token)\n if block.NUM == 0 {\n env.responseBlocks[blockKey] = pdu\n initialBlockSize := env.InitialRequestBlockSize()\n secondBlockSize := env.SecondRequestBlockSize()\n // Check what block_size is used for block2 option\n // If the initialBlockSize is set: client will always request with block2 option\n // If the initialBlockSize is not set and the secondBlockSize is set: if the secondBlockSize is greater than the\n // recommended block size -> use the recommended block size, reversely, use the configured block size\n // If both initialBlockSize and secondBlockSize are not set -> use the recommended block size\n if initialBlockSize == nil && secondBlockSize != nil {\n if *secondBlockSize > block.SZX {\n log.Warn(\"Second block size must not greater thans block size received from server\")\n block.NUM += 1\n } else {\n block.NUM = 1 << uint(block.SZX - *secondBlockSize)\n block.SZX = *secondBlockSize\n }\n } else {\n block.NUM += 1\n }\n } else {\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n block.NUM += 1\n } else {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n }\n }\n block.M = 0\n return isMoreBlock, &eTag, block\n } else if block.M == libcoap.LAST_BLOCK {\n log.Debugf(\"Response block is comming (eTag=%+v, block=%+v, size2=%+v), this is the last block.\", eTag, block.ToString(), size2Value)\n isMoreBlock = false\n if data, ok := env.responseBlocks[blockKey]; ok {\n env.responseBlocks[blockKey].Data = append(data.Data, pdu.Data...)\n } else if block.NUM > 0 {\n log.Warnf(\"The block version is not unknown. Re-request from the first block\")\n delete(env.responseBlocks, blockKey)\n block.NUM = 0\n isMoreBlock = true\n }\n return isMoreBlock, &eTag, block\n }\n }\n return false, nil, nil\n}", "func (v *Validator) Run() (bool, error) {\n\terr := v.verifyBlock()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = v.verifyUncles()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = v.verifyReceipts()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = v.verifyTrace()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = v.verifyReplay()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func TestFullBlocks(t *testing.T) {\n\tt.Parallel()\n\n\ttests, err := fullblocktests.Generate(false)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to generate tests: %v\", err)\n\t}\n\n\t// Create a new database and chain instance to run tests against.\n\tchain, err := chainSetup(t, chaincfg.RegNetParams())\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to setup chain instance: %v\", err)\n\t}\n\n\t// testAcceptedBlock attempts to process the block in the provided test\n\t// instance and ensures that it was accepted according to the flags\n\t// specified in the test.\n\ttestAcceptedBlock := func(item fullblocktests.AcceptedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\tvar isOrphan bool\n\t\tforkLen, err := chain.ProcessBlock(block)\n\t\tif errors.Is(err, ErrMissingParent) {\n\t\t\tisOrphan = true\n\t\t\terr = nil\n\t\t}\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should have \"+\n\t\t\t\t\"been accepted: %v\", item.Name, block.Hash(),\n\t\t\t\tblockHeight, err)\n\t\t}\n\n\t\t// Ensure the main chain and orphan flags match the values\n\t\t// specified in the test.\n\t\tisMainChain := !isOrphan && forkLen == 0\n\t\tif isMainChain != item.IsMainChain {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) unexpected main \"+\n\t\t\t\t\"chain flag -- got %v, want %v\", item.Name,\n\t\t\t\tblock.Hash(), blockHeight, isMainChain,\n\t\t\t\titem.IsMainChain)\n\t\t}\n\t\tif isOrphan != item.IsOrphan {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) unexpected \"+\n\t\t\t\t\"orphan flag -- got %v, want %v\", item.Name,\n\t\t\t\tblock.Hash(), blockHeight, isOrphan,\n\t\t\t\titem.IsOrphan)\n\t\t}\n\t}\n\n\t// testRejectedBlock attempts to process the block in the provided test\n\t// instance and ensures that it was rejected with the reject code\n\t// specified in the test.\n\ttestRejectedBlock := func(item fullblocktests.RejectedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t_, err := chain.ProcessBlock(block)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should not \"+\n\t\t\t\t\"have been accepted\", item.Name, block.Hash(),\n\t\t\t\tblockHeight)\n\t\t}\n\n\t\t// Convert the full block test error kind to the associated local\n\t\t// blockchain error kind.\n\t\twantRejectKind := fullBlockTestErrToLocalErr(t, item.RejectKind)\n\n\t\t// Ensure the error reject kind matches the value specified in the test\n\t\t// instance.\n\t\tif !errors.Is(err, wantRejectKind) {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) does not have \"+\n\t\t\t\t\"expected reject code -- got %v, want %v\",\n\t\t\t\titem.Name, block.Hash(), blockHeight, err, wantRejectKind)\n\t\t}\n\t}\n\n\t// testRejectedNonCanonicalBlock attempts to decode the block in the\n\t// provided test instance and ensures that it failed to decode with a\n\t// message error.\n\ttestRejectedNonCanonicalBlock := func(item fullblocktests.RejectedNonCanonicalBlock) {\n\t\theaderLen := wire.MaxBlockHeaderPayload\n\t\tif headerLen > len(item.RawBlock) {\n\t\t\theaderLen = len(item.RawBlock)\n\t\t}\n\t\tblockHeader := item.RawBlock[0:headerLen]\n\t\tblockHash := chainhash.HashH(chainhash.HashB(blockHeader))\n\t\tblockHeight := item.Height\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\", item.Name,\n\t\t\tblockHash, blockHeight)\n\n\t\t// Ensure there is an error due to deserializing the block.\n\t\tvar msgBlock wire.MsgBlock\n\t\terr := msgBlock.BtcDecode(bytes.NewReader(item.RawBlock), 0)\n\t\tvar werr *wire.MessageError\n\t\tif !errors.As(err, &werr) {\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should have \"+\n\t\t\t\t\"failed to decode\", item.Name, blockHash,\n\t\t\t\tblockHeight)\n\t\t}\n\t}\n\n\t// testOrphanOrRejectedBlock attempts to process the block in the\n\t// provided test instance and ensures that it was either accepted as an\n\t// orphan or rejected with a rule violation.\n\ttestOrphanOrRejectedBlock := func(item fullblocktests.OrphanOrRejectedBlock) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t_, err := chain.ProcessBlock(block)\n\t\tif err != nil {\n\t\t\t// Ensure the error is of the expected type. Note that orphans are\n\t\t\t// rejected with ErrMissingParent, so this check covers both\n\t\t\t// conditions.\n\t\t\tvar rerr RuleError\n\t\t\tif !errors.As(err, &rerr) {\n\t\t\t\tt.Fatalf(\"block %q (hash %s, height %d) \"+\n\t\t\t\t\t\"returned unexpected error type -- \"+\n\t\t\t\t\t\"got %T, want blockchain.RuleError\",\n\t\t\t\t\titem.Name, block.Hash(), blockHeight,\n\t\t\t\t\terr)\n\t\t\t}\n\t\t}\n\t}\n\n\t// testExpectedTip ensures the current tip of the blockchain is the\n\t// block specified in the provided test instance.\n\ttestExpectedTip := func(item fullblocktests.ExpectedTip) {\n\t\tblockHeight := item.Block.Header.Height\n\t\tblock := dcrutil.NewBlock(item.Block)\n\t\tt.Logf(\"Testing tip for block %s (hash %s, height %d)\",\n\t\t\titem.Name, block.Hash(), blockHeight)\n\n\t\t// Ensure hash and height match.\n\t\tbest := chain.BestSnapshot()\n\t\tif best.Hash != item.Block.BlockHash() ||\n\t\t\tbest.Height != int64(blockHeight) {\n\n\t\t\tt.Fatalf(\"block %q (hash %s, height %d) should be \"+\n\t\t\t\t\"the current tip -- got (hash %s, height %d)\",\n\t\t\t\titem.Name, block.Hash(), blockHeight, best.Hash,\n\t\t\t\tbest.Height)\n\t\t}\n\t}\n\n\tfor testNum, test := range tests {\n\t\tfor itemNum, item := range test {\n\t\t\tswitch item := item.(type) {\n\t\t\tcase fullblocktests.AcceptedBlock:\n\t\t\t\ttestAcceptedBlock(item)\n\t\t\tcase fullblocktests.RejectedBlock:\n\t\t\t\ttestRejectedBlock(item)\n\t\t\tcase fullblocktests.RejectedNonCanonicalBlock:\n\t\t\t\ttestRejectedNonCanonicalBlock(item)\n\t\t\tcase fullblocktests.OrphanOrRejectedBlock:\n\t\t\t\ttestOrphanOrRejectedBlock(item)\n\t\t\tcase fullblocktests.ExpectedTip:\n\t\t\t\ttestExpectedTip(item)\n\t\t\tdefault:\n\t\t\t\tt.Fatalf(\"test #%d, item #%d is not one of \"+\n\t\t\t\t\t\"the supported test instance types -- \"+\n\t\t\t\t\t\"got type: %T\", testNum, itemNum, item)\n\t\t\t}\n\t\t}\n\t}\n}", "func (bc *Blockchain) ValidateChain() bool {\n for i := 1; i <= len(bc.Chain); i++ {\n\t\t//current block\n block := bc.Chain[len(bc.Chain) - 1]\n\t\t//previous block\n\tprev_block := bc.Chain[len(bc.Chain) - 2]\n\tproof_hash := bc.ProofOfWorkCalc(block.Proof, prev_block.Proof, block.Timestamp)\n\t//verify index\n if block.Index != prev_block.Index + 1 {\n fmt.Println(\"the new block had the wrong index\")\n fmt.Println(block)\n\t return false\n\t}\n\t//verify time stamp\n if block.Timestamp < prev_block.Timestamp {\n fmt.Println(\"the new block had a bad timestamp\")\n fmt.Println(block)\n\t return false\n\t}\n\t//verify proof\n\tif strings.Compare(proof_hash, prev_block.Difficulty) != -1 {\n fmt.Println(\"the new block did not reach the difficulty target\")\n fmt.Println(block)\n\t return false\n }\n\tif bc.HashBlock(prev_block) != block.PreviousHash {\n fmt.Println(\"the new block had a bad previous hash field\")\n fmt.Println(block)\n\t return false\n\t}\n }\n return true\n}", "func verifyBlock(tree io.ReadSeeker, layout Layout, dataBlock []byte, blockIndex int64, expectedRoot []byte) error {\n\tif len(dataBlock) != int(layout.blockSize) {\n\t\treturn fmt.Errorf(\"incorrect block size\")\n\t}\n\n\texpectedDigest := make([]byte, layout.digestSize)\n\ttreeBlock := make([]byte, layout.blockSize)\n\tvar digest []byte\n\tfor level := 0; level < layout.numLevels(); level++ {\n\t\t// Calculate hash.\n\t\tif level == 0 {\n\t\t\tdigestArray := sha256.Sum256(dataBlock)\n\t\t\tdigest = digestArray[:]\n\t\t} else {\n\t\t\t// Read a block in previous level that contains the\n\t\t\t// hash we just generated, and generate a next level\n\t\t\t// hash from it.\n\t\t\tif _, err := tree.Seek(layout.blockOffset(level-1, blockIndex), io.SeekStart); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := tree.Read(treeBlock); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdigestArray := sha256.Sum256(treeBlock)\n\t\t\tdigest = digestArray[:]\n\t\t}\n\n\t\t// Move to stored hash for the current block, read the digest\n\t\t// and store in expectedDigest.\n\t\tif _, err := tree.Seek(layout.digestOffset(level, blockIndex), io.SeekStart); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := tree.Read(expectedDigest); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !bytes.Equal(digest, expectedDigest) {\n\t\t\treturn fmt.Errorf(\"Verification failed\")\n\t\t}\n\n\t\t// If this is the root layer, no need to generate next level\n\t\t// hash.\n\t\tif level == layout.rootLevel() {\n\t\t\tbreak\n\t\t}\n\t\tblockIndex = blockIndex / layout.hashesPerBlock()\n\t}\n\n\t// Verification for the tree succeeded. Now compare the root hash in the\n\t// tree with expectedRoot.\n\tif !bytes.Equal(digest[:], expectedRoot) {\n\t\treturn fmt.Errorf(\"Verification failed\")\n\t}\n\treturn nil\n}", "func TestHaveBlock(t *testing.T) {\n\t// Load up blocks such that there is a side chain.\n\t// (genesis block) -> 1 -> 2 -> 3 -> 4 -> 5\n\t// \\-> 3a\n\n\tparivateKeyList := []string{\n\t\t\"0xd0f0461b7b4d26cf370e6c73b58ef7fa26e8e30853a8cee901ed42cf0879cb6e\", //privateKey0\n\t}\n\ttestRoundSize := uint16(10)\n\taccList, netParam, chain, teardownFunc, err := createFakeChainByPrivateKeys(parivateKeyList, testRoundSize)\n\tdefer teardownFunc()\n\n\tvalidators, filters, _ := chain.GetValidatorsByNode(1, chain.bestChain.tip())\n\n\tmainChainBlkNums := 5\n\tforkBlkHeightIdx := 3\n\torphanBlkHeightIdx := 5\n\n\tbestChainHashList := make([]common.Hash, 0)\n\tnode0 := chain.bestChain.NodeByHeight(0)\n\tbestChainHashList = append(bestChainHashList, node0.hash)\n\tvar forkHash common.Hash\n\tvar orphanHash common.Hash\n\tcurSlot := uint16(0)\n\tcurEpoch := uint32(1)\n\t//create block:\n\tfor i := 0; i < mainChainBlkNums; i++ {\n\t\tif i != 0 {\n\t\t\tif i == int(netParam.RoundSize) {\n\t\t\t\tcurSlot = 0\n\t\t\t\tcurEpoch += 1\n\t\t\t\tvalidators, filters, _ = chain.GetValidatorsByNode(curEpoch, chain.bestChain.tip())\n\t\t\t} else {\n\t\t\t\tcurSlot ++\n\t\t\t}\n\t\t}\n\n\t\tvar block *asiutil.Block\n\t\tvar frokBlock *asiutil.Block\n\t\tif i == (orphanBlkHeightIdx - 1) {\n\t\t\tblock, _, err = createAndSignBlock(netParam, accList, validators, filters, chain, uint32(curEpoch),\n\t\t\t\tuint16(curSlot), chain.bestChain.height(), protos.Asset{0, 0}, 0,\n\t\t\t\tvalidators[curSlot], nil, 0, chain.bestChain.tip())\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"create block error %v\", err)\n\t\t\t}\n\t\t\t//create orphanBlock:\n\t\t\torphanBlock := block\n\t\t\torphanBlock.MsgBlock().Header.PrevBlock = common.Hash{0x01,}\n\t\t\torphanHash = *orphanBlock.Hash()\n\t\t} else {\n\t\t\t//create block:\n\t\t\tblock, _, err = createAndSignBlock(netParam, accList, validators, filters, chain, uint32(curEpoch),\n\t\t\t\tuint16(curSlot), chain.bestChain.height(), protos.Asset{0, 0}, 0,\n\t\t\t\tvalidators[curSlot], nil, 0, chain.bestChain.tip())\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"create block error %v\", err)\n\t\t\t}\n\n\t\t\tif i == int(forkBlkHeightIdx - 1) {\n\t\t\t\tfrokBlock, _, err = createAndSignBlock(netParam, accList, validators, filters, chain, uint32(curEpoch),\n\t\t\t\t\tuint16(curSlot), chain.bestChain.height(), protos.Asset{0, 0}, 0,\n\t\t\t\t\tvalidators[curSlot], nil, int32(i+1), chain.bestChain.tip())\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Errorf(\"create block error %v\", err)\n\t\t\t\t}\n\t\t\t\tforkHash = *frokBlock.Hash()\n\t\t\t}\n\t\t}\n\t\t// Insert the block to bestChain:\n\t\t_, isOrphan, err := chain.ProcessBlock(block, nil, nil, nil, common.BFNone)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ProcessBlock err %v\", err)\n\t\t}\n\t\tlog.Infof(\"isOrphan = %v\", isOrphan)\n\t\tif i == int(forkBlkHeightIdx - 1) {\n\t\t\t_, forkIsOrphan, err := chain.ProcessBlock(frokBlock, nil, nil, nil, common.BFNone)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"ProcessBlock err %v\", err)\n\t\t\t}\n\t\t\tlog.Infof(\"frokBlock isOrphan = %v\", forkIsOrphan)\n\t\t}\n\n\t\tif !isOrphan {\n\t\t\tnode := chain.bestChain.nodeByHeight(chain.bestChain.height())\n\t\t\tbestChainHashList = append(bestChainHashList, node.hash)\n\t\t}\n\t}\n\n\tmainblklen := len(bestChainHashList)\n\ttmpHash := bestChainHashList[mainblklen-1]\n\totherHash := append(tmpHash[:1], tmpHash[:common.HashLength-1]...)\n\tvar resultHash common.Hash\n\tcopy(resultHash[:], otherHash)\n\n\ttests := []struct {\n\t\thash common.Hash\n\t\twant bool\n\t}{\n\t\t//blockHash in bestchain: test0\n\t\t{\n\t\t\tbestChainHashList[mainChainBlkNums-2],\n\t\t\ttrue,\n\t\t},\n\t\t//block hash in fork chain: test1\n\t\t{\n\t\t\tforkHash,\n\t\t\ttrue,\n\t\t},\n\t\t//orphan block hash: test2\n\t\t{\n\t\t\torphanHash,\n\t\t\ttrue,\n\t\t},\n\t\t//Random hashes should not be available\n\t\t{\n\t\t\tresultHash,\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor i, test := range tests {\n\t\tt.Logf(\"start test %d\", i)\n\t\tresult, err := chain.HaveBlock(&test.hash)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"HaveBlock #%d unexpected error: %v\", i, err)\n\t\t}\n\t\tif result != test.want {\n\t\t\tt.Errorf(\"HaveBlock #%d got %v want %v\", i, result, test.want)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (v *AllowAll) ValidateBlock(\n\tctx context.Context,\n\tproposedBlk *block.Block,\n\tparentBlk *block.Block,\n) (bool, error) {\n\treturn false, nil\n}", "func (b *Block) IsBlockValid(previousBlock Block) bool {\n\tif b.Index != previousBlock.Index+1 {\n\t\treturn false\n\t}\n\n\tif b.PrevHash != previousBlock.Hash {\n\t\treturn false\n\t}\n\n\tif b.Hash != calculateBlockHash(*b) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (block *Block) IsValid() bool {\n\tflagBits := util.BytesToBitField(block.Flags)\n\thashes := make([][]byte, len(block.Hashes))\n\tfor i, hash := range block.Hashes {\n\t\thashes[i] = make([]byte, len(hash))\n\t\tcopy(hashes[i], hash)\n\t\tutil.ReverseByteArray(hashes[i])\n\t}\n\ttree := NewTree(int(block.Total))\n\ttree.PopulateTree(flagBits, hashes)\n\treturn bytes.Equal(util.ReverseByteArray(tree.Root()), block.MerkleRoot[:])\n}", "func (s *SimpleBlockFactory) IsBlockValid(*types.Block, *types.Block) error {\n\t// SimpleBlockFactory has no block valid check.\n\treturn nil\n}", "func (honest *Honest) hasBlock(iterationCount int) bool {\n\t\n\tif (honest.bc.getBlock(iterationCount) != nil) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n\n}", "func Test_ValidateBlockTransactions_Coinbase(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"invalid-coinbase\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func (w Work) Validate(blockHash BlockHash) bool {\n\thash, err := blake2b.New(8, nil)\n\tif err != nil {\n\t\tpanic(\"Unable to create hash\")\n\t}\n\n\thash.Write(w[:])\n\thash.Write(blockHash[:])\n\n\tworkValue := hash.Sum(nil)\n\tworkValueInt := binary.LittleEndian.Uint64(workValue)\n\n\treturn workValueInt >= WorkThreshold\n}", "func (bh *BlockHeader) Valid() bool {\r\n\ttarget, err := ExpandTargetFromAsInt(hex.EncodeToString(bh.Bits))\r\n\tif err != nil {\r\n\t\treturn false\r\n\t}\r\n\r\n\tdigest := bt.ReverseBytes(crypto.Sha256d(bh.Bytes()))\r\n\tvar bn *big.Int = big.NewInt(0)\r\n\tbn.SetBytes(digest)\r\n\r\n\treturn bn.Cmp(target) < 0\r\n}", "func verifyChain(db ethdb.Database) {\n\tengine := ethash.NewFaker()\n\tchain, err := core.NewBlockChain(db, nil, params.TestChainConfig, engine, vm.Config{})\n\tif err != nil {\n\t\tfmt.Printf(\"failed to create new chain manager: %v\", err)\n\t}\n\tfmt.Println(\"chain=\", chain)\n\t/*\n\t\tvar results <-chan error\n\t\t_, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})\n\n\t\t\t// Wait for the verification result\n\t\t\t\tselect {\n\t\t\t\tcase result := <-results:\n\t\t\t\t\tif (result == nil) != valid {\n\t\t\t\t\t\tt.Errorf(\"test %d.%d: validity mismatch: have %v, want %v\", i, j, result, valid)\n\t\t\t\t\t}\n\t\t\t\tcase <-time.After(time.Second):\n\t\t\t\t\tt.Fatalf(\"test %d.%d: verification timeout\", i, j)\n\t\t\t\t}\n\t\t\t\t// Make sure no more data is returned\n\t\t\t\tselect {\n\t\t\t\tcase result := <-results:\n\t\t\t\t\tt.Fatalf(\"test %d.%d: unexpected result returned: %v\", i, j, result)\n\t\t\t\tcase <-time.After(25 * time.Millisecond):\n\t\t\t\t}\n\t\t\t}\n\t\t\tchain.InsertChain(blocks[i : i+1])\n\t\t}*/\n}", "func (bc *Blockchain) validProof(nonce int, previousHash [32]byte, transactions []*Transaction, difficulty int) bool {\n\tb := Block{nonce, previousHash, 0, transactions}\n\thashStr := fmt.Sprintf(\"%x\", b.Hash())\n\treturn hashStr[:difficulty] == strings.Repeat(\"0\", difficulty)\n}", "func Test_ValidateBlockTransactions_Transactions(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func checkBlockData(u interface{}, data []byte) ([]byte, uint64, error) {\n\tbn := u.(*bftnode)\n\n\tvar blockData DataStu\n\n\tif err := json.Unmarshal(data, &blockData); err != nil {\n\t\tlogger.Error(\"checkBlockData Unmarshal error\", zap.Error(err))\n\t\treturn nil, 0, err\n\t}\n\tb := blockData.Block\n\tif b == nil {\n\t\tlogger.Error(\"block is nil\")\n\t\treturn nil, 0, errors.New(\"block data is nil\")\n\t}\n\n\t//not an expect block data,so return error here.\n\tif b.Height != 1+bn.lastHeight {\n\t\tlogger.Error(\"checkBlockData block error: b.Height != 1 + bn.lastHeight.\", zap.Uint64(\"b.height\", b.Height), zap.Uint64(\"last height\", bn.lastHeight))\n\t\treturn b.Hash, b.Height, errors.New(\"checkBlockData block error: b.Height != 1+bn.lastHeight\")\n\t}\n\n\tp := bn.pool\n\tp.Filter(*b)\n\n\t//logger.Info(\"checkBlockData info\", zap.Uint64(\"Height\", b.Height), zap.ByteString(\"res hash\", blockData.ResultHash))\n\tfmt.Println(\"checkBlockData info:\", \"Height\", b.Height, \"res hash\", blockData.ResultHash)\n\n\tif !bn.checkBlock(b, blockData.ResultHash) {\n\t\tlogger.Error(\"Follow checkBlock error!\", zap.Uint64(\"hegiht:\", b.Height))\n\t\treturn b.Hash, b.Height, errors.New(\"CheckBlock ERROR\")\n\t}\n\n\tif !txpool.VerifyBlock(*b, bn.bc) {\n\t\tlogger.Error(\"Follow verifyBlcok error!\", zap.Uint64(\"hegiht:\", b.Height))\n\t\treturn b.Hash, b.Height, errors.New(\"VerifyBlcok ERROR\")\n\t}\n\n\treturn b.Hash, b.Height, nil\n}", "func validateCommit(req CommitRequest) {\n\tfmt.Println(\"In validateCommit()\")\n\tfor {\n\t\t// always refresh the hashes list in case other block for same tx has been added\n\t\tmutex.Lock()\n\t\ttx := transactions[req.Transaction.ID]\n\t\tmutex.Unlock()\n\t\thashes := tx.AllHashes\n\t\tfor _, hash := range hashes {\n\t\t\tmutex.Lock()\n\t\t\tblock := blockChain[hash]\n\t\t\tmutex.Unlock()\n\t\t\tfmt.Println(\"Trying to validate a block with ID\", block.HashBlock.TxID, \"and children:\", len(block.ChildrenHashes))\n\t\t\tif isBlockValidated(block, req.ValidateNum) {\n\t\t\t\t// set the correct commit values for returning to client\n\t\t\t\ttx.CommitHash = hash\n\t\t\t\ttx.CommitID = block.Depth\n\t\t\t\tmutex.Lock()\n\t\t\t\ttransactions[req.Transaction.ID] = tx\n\t\t\t\tmutex.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t\tfmt.Println(\"block not yet validated...\")\n\t}\n}", "func verify(chain *Chain, unverified Block) bool {\n\tlast := chain.Last()\n\n\thash, err := hashOf(last.Index, last.Hash, unverified.Timestamp, unverified.Data)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn hash == unverified.Hash\n}", "func (b *Block) ValidateBasic() error {\n\tif b == nil {\n\t\treturn errors.New(\"nil block\")\n\t}\n\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif err := b.Header.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"invalid header: %w\", err)\n\t}\n\n\tif b.CoreChainLock != nil {\n\t\tif err := b.CoreChainLock.ValidateBasic(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid chain lock data: %w\", err)\n\t\t}\n\t}\n\n\t// Validate the last commit and its hash.\n\tif b.LastCommit == nil {\n\t\treturn errors.New(\"nil LastPrecommits\")\n\t}\n\tif err := b.LastCommit.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastPrecommits: %v\", err)\n\t}\n\n\tif !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.LastCommitHash. Expected %v, got %v\",\n\t\t\tb.LastCommit.Hash(),\n\t\t\tb.LastCommitHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.\n\tif !bytes.Equal(b.DataHash, b.Data.Hash()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"wrong Header.DataHash. Expected %v, got %v\",\n\t\t\tb.Data.Hash(),\n\t\t\tb.DataHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Evidence.Evidence may be nil, but we're just looping.\n\tfor i, ev := range b.Evidence.Evidence {\n\t\tif err := ev.ValidateBasic(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid evidence (#%d): %v\", i, err)\n\t\t}\n\t}\n\n\tif !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.EvidenceHash. Expected %v, got %v\",\n\t\t\tb.EvidenceHash,\n\t\t\tb.Evidence.Hash(),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (b *Block) IsValid() bool {\n\treturn b.valid\n}", "func (v *Validator) ValidateAndPrepareBatch(block *common.Block, doMVCCValidation bool) (*statedb.UpdateBatch, error) {\n\tlogger.Debugf(\"New block arrived for validation:%#v, doMVCCValidation=%t\", block, doMVCCValidation)\n\tupdates := statedb.NewUpdateBatch()\n\tlogger.Debugf(\"Validating a block with [%d] transactions\", len(block.Data.Data))\n\n\t// Committer validator has already set validation flags based on well formed tran checks\n\ttxsFilter := util.TxValidationFlags(block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER])\n\n\t// Precaution in case committer validator has not added validation flags yet\n\tif len(txsFilter) == 0 {\n\t\ttxsFilter = util.NewTxValidationFlags(len(block.Data.Data))\n\t\tblock.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] = txsFilter\n\t}\n\n\tfor txIndex, envBytes := range block.Data.Data {\n\t\tif txsFilter.IsInvalid(txIndex) {\n\t\t\t// Skiping invalid transaction\n\t\t\tlogger.Warningf(\"Block [%d] Transaction index [%d] marked as invalid by committer. Reason code [%d]\",\n\t\t\t\tblock.Header.Number, txIndex, txsFilter.Flag(txIndex))\n\t\t\tcontinue\n\t\t}\n\n\t\tenv, err := putils.GetEnvelopeFromBlock(envBytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpayload, err := putils.GetPayload(env)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tchdr, err := putils.UnmarshalChannelHeader(payload.Header.ChannelHeader)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttxType := common.HeaderType(chdr.Type)\n\n\t\tif txType != common.HeaderType_ENDORSER_TRANSACTION {\n\t\t\tlogger.Debugf(\"Skipping mvcc validation for Block [%d] Transaction index [%d] because, the transaction type is [%s]\",\n\t\t\t\tblock.Header.Number, txIndex, txType)\n\t\t\tcontinue\n\t\t}\n\n\t\ttxRWSet, txResult, err := v.validateEndorserTX(envBytes, doMVCCValidation, updates)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttxsFilter.SetFlag(txIndex, txResult)\n\n\t\t//txRWSet != nil => t is valid\n\t\tif txRWSet != nil {\n\t\t\tcommittingTxHeight := version.NewHeight(block.Header.Number, uint64(txIndex))\n\t\t\taddWriteSetToBatch(txRWSet, committingTxHeight, updates)\n\t\t\ttxsFilter.SetFlag(txIndex, peer.TxValidationCode_VALID)\n\t\t}\n\n\t\tif txsFilter.IsValid(txIndex) {\n\t\t\tlogger.Debugf(\"Block [%d] Transaction index [%d] TxId [%s] marked as valid by state validator\",\n\t\t\t\tblock.Header.Number, txIndex, chdr.TxId)\n\t\t} else {\n\t\t\tlogger.Warningf(\"Block [%d] Transaction index [%d] TxId [%s] marked as invalid by state validator. Reason code [%d]\",\n\t\t\t\tblock.Header.Number, txIndex, chdr.TxId, txsFilter.Flag(txIndex))\n\t\t}\n\t}\n\tblock.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] = txsFilter\n\treturn updates, nil\n}", "func (s *TXPoolServer) verifyBlock(req *tc.VerifyBlockReq, sender *actor.PID) {\n\tif req == nil || len(req.Txs) == 0 {\n\t\treturn\n\t}\n\n\ts.setHeight(req.Height)\n\ts.pendingBlock.mu.Lock()\n\tdefer s.pendingBlock.mu.Unlock()\n\n\ts.pendingBlock.sender = sender\n\ts.pendingBlock.height = req.Height\n\ts.pendingBlock.processedTxs = make(map[common.Uint256]*tc.VerifyTxResult, len(req.Txs))\n\ts.pendingBlock.unProcessedTxs = make(map[common.Uint256]*tx.Transaction, 0)\n\n\ttxs := make(map[common.Uint256]bool, len(req.Txs))\n\n\t// Check whether a tx's gas price is lower than the required, if yes,\n\t// just return error\n\tfor _, t := range req.Txs {\n\t\tif t.GasPrice < s.gasPrice {\n\t\t\tentry := &tc.VerifyTxResult{\n\t\t\t\tHeight: s.pendingBlock.height,\n\t\t\t\tTx: t,\n\t\t\t\tErrCode: errors.ErrGasPrice,\n\t\t\t}\n\t\t\ts.pendingBlock.processedTxs[t.Hash()] = entry\n\t\t\ts.sendBlkResult2Consensus()\n\t\t\treturn\n\t\t}\n\t\t// Check whether double spent\n\t\tif _, ok := txs[t.Hash()]; ok {\n\t\t\tentry := &tc.VerifyTxResult{\n\t\t\t\tHeight: s.pendingBlock.height,\n\t\t\t\tTx: t,\n\t\t\t\tErrCode: errors.ErrDoubleSpend,\n\t\t\t}\n\t\t\ts.pendingBlock.processedTxs[t.Hash()] = entry\n\t\t\ts.sendBlkResult2Consensus()\n\t\t\treturn\n\t\t}\n\t\ttxs[t.Hash()] = true\n\t}\n\n\tcheckBlkResult := s.txPool.GetUnverifiedTxs(req.Txs, req.Height)\n\n\tfor _, t := range checkBlkResult.UnverifiedTxs {\n\t\ts.assignTxToWorker(t, tc.NilSender, nil)\n\t\ts.pendingBlock.unProcessedTxs[t.Hash()] = t\n\t}\n\n\tfor _, t := range checkBlkResult.OldTxs {\n\t\ts.reVerifyStateful(t, tc.NilSender)\n\t\ts.pendingBlock.unProcessedTxs[t.Hash()] = t\n\t}\n\n\tfor _, t := range checkBlkResult.VerifiedTxs {\n\t\ts.pendingBlock.processedTxs[t.Tx.Hash()] = t\n\t}\n\n\t/* If all the txs in the blocks are verified, send response\n\t * to the consensus directly\n\t */\n\tif len(s.pendingBlock.unProcessedTxs) == 0 {\n\t\ts.sendBlkResult2Consensus()\n\t}\n}", "func (v *Live) Validate(channel bcgo.Channel, cache bcgo.Cache, network bcgo.Network, hash []byte, block *bcgo.Block) error {\n\texpected := os.Getenv(bcgo.LIVE_FLAG)\n\treturn bcgo.Iterate(channel.Name(), hash, block, cache, network, func(h []byte, b *bcgo.Block) error {\n\t\tfor _, entry := range b.Entry {\n\t\t\tvar flag string\n\t\t\tif meta := entry.Record.Meta; meta != nil {\n\t\t\t\tflag = meta[bcgo.LIVE_FLAG]\n\t\t\t}\n\t\t\tif flag != expected {\n\t\t\t\treturn ErrDifferentLiveFlag{Expected: expected, Actual: flag}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func TestCheckTransactionSanity(t *testing.T) {\n\t// Create a base transaction that is further manipulated in the tests below\n\t// to test error conditions.\n\t//\n\t// This is mainnet block 373, tx[5] (two inputs, two outputs).\n\ttxHex := \"010000000201261057a5ecaf6edede86c5446c62f067f30d654117668325090\" +\n\t\t\"9ac3e45bec00100000000ffffffff03c65ad19cb990cc916e38dc94f0255f344c5e9\" +\n\t\t\"b7af3b69bfa19931f6027e44c0100000000ffffffff02c1c57600000000000000197\" +\n\t\t\"6a914e07c0b2a499312f5d95e3bd4f126e618087a15a588ac402c420600000000000\" +\n\t\t\"01976a91411f2b3135e457259009bdd14cfcb942eec58bd7a88ac000000000000000\" +\n\t\t\"0023851f6050000000073010000040000006a473044022009ff5aed5d2e5eeec8931\" +\n\t\t\"9d0a700b7abdf842e248641804c82dee17df446c24202207c252cc36199ea8a6cc71\" +\n\t\t\"d2252a3f7e61f9cce272dff82c5818e3bf08167e3a6012102773925f9ee53837aa0e\" +\n\t\t\"fba2212f71ee8ab20aeb603fa7324a8c2555efe5c482709ec0e01000000002501000\" +\n\t\t\"0050000006a47304402201165136a2b792cc6d7e75f576ed64e1919cbf954afb989f\" +\n\t\t\"8590844a628e58def02206ba7e60f5ae9810794297359cc883e7ff97ecd21bc7177f\" +\n\t\t\"cc668a84f64a4b9120121026a4151513b4e6650e3d213451037cd6b78ed829d12ed1\" +\n\t\t\"d43d5d34ce0834831e9\"\n\ttxBytes, err := hex.DecodeString(txHex)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected err parsing base tx hex: %v\", err)\n\t}\n\tvar baseTx wire.MsgTx\n\tif err := baseTx.FromBytes(txBytes); err != nil {\n\t\tt.Fatalf(\"nexpected err parsing base tx: %v\", err)\n\t}\n\n\tconst maxTxSize = 393216\n\ttests := []struct {\n\t\tname string // test description\n\t\ttx *wire.MsgTx // transaction to test\n\t\terr error // expected error\n\t}{{\n\t\tname: \"ok\",\n\t\ttx: &baseTx,\n\t\terr: nil,\n\t}, {\n\t\tname: \"transaction has no inputs\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxIn = nil\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrNoTxInputs,\n\t}, {\n\t\tname: \"transaction has no outputs\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxOut = nil\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrNoTxOutputs,\n\t}, {\n\t\tname: \"transaction too big\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxOut[0].PkScript = bytes.Repeat([]byte{0x00}, maxTxSize)\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrTxTooBig,\n\t}, {\n\t\tname: \"transaction with negative output amount\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxOut[0].Value = -1\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrBadTxOutValue,\n\t}, {\n\t\tname: \"transaction with single output amount > max per tx\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxOut[0].Value = maxAtoms + 1\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrBadTxOutValue,\n\t}, {\n\t\tname: \"transaction with outputs sum > max per tx\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxOut[0].Value = maxAtoms\n\t\t\ttx.TxOut[1].Value = 1\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrBadTxOutValue,\n\t}, {\n\t\tname: \"transaction spending duplicate input\",\n\t\ttx: func() *wire.MsgTx {\n\t\t\ttx := baseTx.Copy()\n\t\t\ttx.TxIn[1].PreviousOutPoint = tx.TxIn[0].PreviousOutPoint\n\t\t\treturn tx\n\t\t}(),\n\t\terr: ErrDuplicateTxInputs,\n\t}}\n\n\tfor _, test := range tests {\n\t\terr := CheckTransactionSanity(test.tx, maxTxSize)\n\t\tif !errors.Is(err, test.err) {\n\t\t\tt.Errorf(\"%q: unexpected err -- got %v, want %v\", test.name, err,\n\t\t\t\ttest.err)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (syncer *Syncer) checkBlockMessages(ctx context.Context, b *types.FullBlock, baseTs *types.TipSet) error {\n\t{\n\t\tvar sigCids []cid.Cid // this is what we get for people not wanting the marshalcbor method on the cid type\n\t\tvar pubks [][]byte\n\n\t\tfor _, m := range b.BlsMessages {\n\t\t\tsigCids = append(sigCids, m.Cid())\n\n\t\t\tpubk, err := syncer.sm.GetBlsPublicKey(ctx, m.From, baseTs)\n\t\t\tif err != nil {\n\t\t\t\treturn xerrors.Errorf(\"failed to load bls public to validate block: %w\", err)\n\t\t\t}\n\n\t\t\tpubks = append(pubks, pubk)\n\t\t}\n\n\t\tif err := syncer.verifyBlsAggregate(ctx, b.Header.BLSAggregate, sigCids, pubks); err != nil {\n\t\t\treturn xerrors.Errorf(\"bls aggregate signature was invalid: %w\", err)\n\t\t}\n\t}\n\n\tnonces := make(map[address.Address]uint64)\n\n\tstateroot, _, err := syncer.sm.TipSetState(ctx, baseTs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcst := cbor.NewCborStore(syncer.store.Blockstore())\n\tst, err := state.LoadStateTree(cst, stateroot)\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"failed to load base state tree: %w\", err)\n\t}\n\n\tpl := vm.PricelistByEpoch(baseTs.Height())\n\tvar sumGasLimit int64\n\tcheckMsg := func(msg types.ChainMsg) error {\n\t\tm := msg.VMMessage()\n\n\t\t// Phase 1: syntactic validation, as defined in the spec\n\t\tminGas := pl.OnChainMessage(msg.ChainLength())\n\t\tif err := m.ValidForBlockInclusion(minGas.Total()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// ValidForBlockInclusion checks if any single message does not exceed BlockGasLimit\n\t\t// So below is overflow safe\n\t\tsumGasLimit += m.GasLimit\n\t\tif sumGasLimit > build.BlockGasLimit {\n\t\t\treturn xerrors.Errorf(\"block gas limit exceeded\")\n\t\t}\n\n\t\t// Phase 2: (Partial) semantic validation:\n\t\t// the sender exists and is an account actor, and the nonces make sense\n\t\tif _, ok := nonces[m.From]; !ok {\n\t\t\t// `GetActor` does not validate that this is an account actor.\n\t\t\tact, err := st.GetActor(m.From)\n\t\t\tif err != nil {\n\t\t\t\treturn xerrors.Errorf(\"failed to get actor: %w\", err)\n\t\t\t}\n\n\t\t\tif !act.IsAccountActor() {\n\t\t\t\treturn xerrors.New(\"Sender must be an account actor\")\n\t\t\t}\n\t\t\tnonces[m.From] = act.Nonce\n\t\t}\n\n\t\tif nonces[m.From] != m.Nonce {\n\t\t\treturn xerrors.Errorf(\"wrong nonce (exp: %d, got: %d)\", nonces[m.From], m.Nonce)\n\t\t}\n\t\tnonces[m.From]++\n\n\t\treturn nil\n\t}\n\n\tstore := adt.WrapStore(ctx, cst)\n\n\tbmArr := adt.MakeEmptyArray(store)\n\tfor i, m := range b.BlsMessages {\n\t\tif err := checkMsg(m); err != nil {\n\t\t\treturn xerrors.Errorf(\"block had invalid bls message at index %d: %w\", i, err)\n\t\t}\n\n\t\tc := cbg.CborCid(m.Cid())\n\t\tif err := bmArr.Set(uint64(i), &c); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to put bls message at index %d: %w\", i, err)\n\t\t}\n\t}\n\n\tsmArr := adt.MakeEmptyArray(store)\n\tfor i, m := range b.SecpkMessages {\n\t\tif err := checkMsg(m); err != nil {\n\t\t\treturn xerrors.Errorf(\"block had invalid secpk message at index %d: %w\", i, err)\n\t\t}\n\n\t\t// `From` being an account actor is only validated inside the `vm.ResolveToKeyAddr` call\n\t\t// in `StateManager.ResolveToKeyAddress` here (and not in `checkMsg`).\n\t\tkaddr, err := syncer.sm.ResolveToKeyAddress(ctx, m.Message.From, baseTs)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to resolve key addr: %w\", err)\n\t\t}\n\n\t\tif err := sigs.Verify(&m.Signature, kaddr, m.Message.Cid().Bytes()); err != nil {\n\t\t\treturn xerrors.Errorf(\"secpk message %s has invalid signature: %w\", m.Cid(), err)\n\t\t}\n\n\t\tc := cbg.CborCid(m.Cid())\n\t\tif err := smArr.Set(uint64(i), &c); err != nil {\n\t\t\treturn xerrors.Errorf(\"failed to put secpk message at index %d: %w\", i, err)\n\t\t}\n\t}\n\n\tbmroot, err := bmArr.Root()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsmroot, err := smArr.Root()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmrcid, err := cst.Put(ctx, &types.MsgMeta{\n\t\tBlsMessages: bmroot,\n\t\tSecpkMessages: smroot,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif b.Header.Messages != mrcid {\n\t\treturn fmt.Errorf(\"messages didnt match message root in header\")\n\t}\n\n\treturn nil\n}", "func (b *Block) ValidateBasic() error {\n\tif b == nil {\n\t\treturn errors.New(\"nil block\")\n\t}\n\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif err := b.Header.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"invalid header: %w\", err)\n\t}\n\n\t// Validate the last commit and its hash.\n\tif b.LastCommit == nil {\n\t\treturn errors.New(\"nil LastCommit\")\n\t}\n\tif err := b.LastCommit.ValidateBasic(); err != nil {\n\t\treturn fmt.Errorf(\"wrong LastCommit: %v\", err)\n\t}\n\n\tif !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.LastCommitHash. Expected %v, got %v\",\n\t\t\tb.LastCommit.Hash(),\n\t\t\tb.LastCommitHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Data.Txs may be nil, but b.Data.Hash() still works fine.\n\tif !bytes.Equal(b.DataHash, b.Data.Hash()) {\n\t\treturn fmt.Errorf(\n\t\t\t\"wrong Header.DataHash. Expected %v, got %v\",\n\t\t\tb.Data.Hash(),\n\t\t\tb.DataHash,\n\t\t)\n\t}\n\n\t// NOTE: b.Evidence.Evidence may be nil, but we're just looping.\n\tfor i, ev := range b.Evidence.Evidence {\n\t\tif err := ev.ValidateBasic(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid evidence (#%d): %v\", i, err)\n\t\t}\n\t}\n\n\tif !bytes.Equal(b.EvidenceHash, b.Evidence.Hash()) {\n\t\treturn fmt.Errorf(\"wrong Header.EvidenceHash. Expected %v, got %v\",\n\t\t\tb.EvidenceHash,\n\t\t\tb.Evidence.Hash(),\n\t\t)\n\t}\n\n\treturn nil\n}", "func TestCheckConnectBlockTemplate(t *testing.T) {\n\tt.Parallel()\n\n\t// Create a test harness initialized with the genesis block as the tip.\n\tparams := chaincfg.RegNetParams()\n\tg := newChaingenHarness(t, params)\n\n\t// Define some additional convenience helper functions to process the\n\t// current tip block associated with the generator.\n\t//\n\t// acceptedBlockTemplate expected the block to considered a valid block\n\t// template.\n\t//\n\t// rejectedBlockTemplate expects the block to be considered an invalid\n\t// block template due to the provided error kind.\n\tacceptedBlockTemplate := func() {\n\t\tmsgBlock := g.Tip()\n\t\tblockHeight := msgBlock.Header.Height\n\t\tblock := dcrutil.NewBlock(msgBlock)\n\t\tt.Logf(\"Testing block template %s (hash %s, height %d)\",\n\t\t\tg.TipName(), block.Hash(), blockHeight)\n\n\t\terr := g.chain.CheckConnectBlockTemplate(block)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"block template %q (hash %s, height %d) should \"+\n\t\t\t\t\"have been accepted: %v\", g.TipName(),\n\t\t\t\tblock.Hash(), blockHeight, err)\n\t\t}\n\t}\n\trejectedBlockTemplate := func(kind ErrorKind) {\n\t\tmsgBlock := g.Tip()\n\t\tblockHeight := msgBlock.Header.Height\n\t\tblock := dcrutil.NewBlock(msgBlock)\n\t\tt.Logf(\"Testing block template %s (hash %s, height %d)\",\n\t\t\tg.TipName(), block.Hash(), blockHeight)\n\n\t\terr := g.chain.CheckConnectBlockTemplate(block)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"block template %q (hash %s, height %d) should \"+\n\t\t\t\t\"not have been accepted\", g.TipName(), block.Hash(),\n\t\t\t\tblockHeight)\n\t\t}\n\n\t\t// Ensure the error reject kind matches the value specified in the test\n\t\t// instance.\n\t\tif !errors.Is(err, kind) {\n\t\t\tt.Fatalf(\"block template %q (hash %s, height %d) does \"+\n\t\t\t\t\"not have expected reject code -- got %v, want %v\",\n\t\t\t\tg.TipName(), block.Hash(), blockHeight, err, kind)\n\t\t}\n\t}\n\n\t// changeNonce is a munger that modifies the block by changing the header\n\t// nonce to a pseudo-random value.\n\tprng := mrand.New(mrand.NewSource(0))\n\tchangeNonce := func(b *wire.MsgBlock) {\n\t\t// Change the nonce so the block isn't actively solved.\n\t\tb.Header.Nonce = prng.Uint32()\n\t}\n\n\t// Shorter versions of useful params for convenience.\n\tticketsPerBlock := params.TicketsPerBlock\n\tcoinbaseMaturity := params.CoinbaseMaturity\n\tstakeEnabledHeight := params.StakeEnabledHeight\n\tstakeValidationHeight := params.StakeValidationHeight\n\n\t// ---------------------------------------------------------------------\n\t// First block templates.\n\t//\n\t// NOTE: The advance funcs on the harness are intentionally not used in\n\t// these tests since they need to manually test block templates at all\n\t// heights.\n\t// ---------------------------------------------------------------------\n\n\t// Produce an initial block with too much coinbase and ensure the block\n\t// template is rejected.\n\t//\n\t// genesis\n\t// \\-> bfbbad\n\tg.CreateBlockOne(\"bfbbad\", 1)\n\tg.AssertTipHeight(1)\n\trejectedBlockTemplate(ErrBadCoinbaseValue)\n\n\t// Produce a valid, but unsolved initial block and ensure the block template\n\t// is accepted while the unsolved block is rejected.\n\t//\n\t// genesis\n\t// \\-> bfbunsolved\n\tg.SetTip(\"genesis\")\n\tbfbunsolved := g.CreateBlockOne(\"bfbunsolved\", 0, changeNonce)\n\t// Since the difficulty is so low in the tests, the block might still\n\t// end up being inadvertently solved. It can't be checked inside the\n\t// munger because the block is finalized after the function returns and\n\t// those changes could also inadvertently solve the block. Thus, just\n\t// increment the nonce until it's not solved and then replace it in the\n\t// generator's state.\n\t{\n\t\torigHash := bfbunsolved.BlockHash()\n\t\tfor g.IsSolved(&bfbunsolved.Header) {\n\t\t\tbfbunsolved.Header.Nonce++\n\t\t}\n\t\tg.UpdateBlockState(\"bfbunsolved\", origHash, \"bfbunsolved\", bfbunsolved)\n\t}\n\tg.AssertTipHeight(1)\n\tacceptedBlockTemplate()\n\tg.RejectTipBlock(ErrHighHash)\n\tg.ExpectTip(\"genesis\")\n\n\t// Produce a valid and solved initial block.\n\t//\n\t// genesis -> bfb\n\tg.SetTip(\"genesis\")\n\tg.CreateBlockOne(\"bfb\", 0)\n\tg.AssertTipHeight(1)\n\tg.AcceptTipBlock()\n\n\t// ---------------------------------------------------------------------\n\t// Generate enough blocks to have mature coinbase outputs to work with.\n\t//\n\t// Also, ensure that each block is considered a valid template along the\n\t// way.\n\t//\n\t// genesis -> bfb -> bm0 -> bm1 -> ... -> bm#\n\t// ---------------------------------------------------------------------\n\n\tvar tipName string\n\tfor i := uint16(0); i < coinbaseMaturity; i++ {\n\t\tblockName := fmt.Sprintf(\"bm%d\", i)\n\t\tg.NextBlock(blockName, nil, nil)\n\t\tg.SaveTipCoinbaseOuts()\n\t\tacceptedBlockTemplate()\n\t\tg.AcceptTipBlock()\n\t\ttipName = blockName\n\t}\n\tg.AssertTipHeight(uint32(coinbaseMaturity) + 1)\n\n\t// ---------------------------------------------------------------------\n\t// Generate block templates that include invalid ticket purchases.\n\t// ---------------------------------------------------------------------\n\n\t// Create a block template with a ticket that claims too much input\n\t// amount.\n\t//\n\t// ... -> bm#\n\t// \\-> btixt1\n\ttempOuts := g.OldestCoinbaseOuts()\n\ttempTicketOuts := tempOuts[1:]\n\tg.NextBlock(\"btixt1\", nil, tempTicketOuts, func(b *wire.MsgBlock) {\n\t\tchangeNonce(b)\n\t\tb.STransactions[3].TxIn[0].ValueIn--\n\t})\n\trejectedBlockTemplate(ErrFraudAmountIn)\n\n\t// Create a block template with a ticket that does not pay enough.\n\t//\n\t// ... -> bm#\n\t// \\-> btixt2\n\tg.SetTip(tipName)\n\tg.NextBlock(\"btixt2\", nil, tempTicketOuts, func(b *wire.MsgBlock) {\n\t\tchangeNonce(b)\n\t\tb.STransactions[2].TxOut[0].Value--\n\t})\n\trejectedBlockTemplate(ErrNotEnoughStake)\n\n\t// ---------------------------------------------------------------------\n\t// Generate enough blocks to reach the stake enabled height while\n\t// creating ticket purchases that spend from the coinbases matured\n\t// above. This will also populate the pool of immature tickets.\n\t//\n\t// Also, ensure that each block is considered a valid template along the\n\t// way.\n\t//\n\t// ... -> bm# ... -> bse0 -> bse1 -> ... -> bse#\n\t// ---------------------------------------------------------------------\n\n\t// Use the already popped outputs.\n\tg.SetTip(tipName)\n\tg.NextBlock(\"bse0\", nil, tempTicketOuts)\n\tg.SaveTipCoinbaseOuts()\n\tacceptedBlockTemplate()\n\tg.AcceptTipBlock()\n\n\tvar ticketsPurchased int\n\tfor i := int64(1); int64(g.Tip().Header.Height) < stakeEnabledHeight; i++ {\n\t\touts := g.OldestCoinbaseOuts()\n\t\tticketOuts := outs[1:]\n\t\tticketsPurchased += len(ticketOuts)\n\t\tblockName := fmt.Sprintf(\"bse%d\", i)\n\t\tg.NextBlock(blockName, nil, ticketOuts)\n\t\tg.SaveTipCoinbaseOuts()\n\t\tacceptedBlockTemplate()\n\t\tg.AcceptTipBlock()\n\t}\n\tg.AssertTipHeight(uint32(stakeEnabledHeight))\n\n\t// ---------------------------------------------------------------------\n\t// Generate enough blocks to reach the stake validation height while\n\t// continuing to purchase tickets using the coinbases matured above and\n\t// allowing the immature tickets to mature and thus become live.\n\t//\n\t// Also, ensure that each block is considered a valid template along the\n\t// way.\n\t//\n\t// ... -> bse# -> bsv0 -> bsv1 -> ... -> bsv#\n\t// ---------------------------------------------------------------------\n\n\ttargetPoolSize := g.Params().TicketPoolSize * ticketsPerBlock\n\tfor i := int64(0); int64(g.Tip().Header.Height) < stakeValidationHeight; i++ {\n\t\t// Only purchase tickets until the target ticket pool size is\n\t\t// reached.\n\t\touts := g.OldestCoinbaseOuts()\n\t\tticketOuts := outs[1:]\n\t\tif ticketsPurchased+len(ticketOuts) > int(targetPoolSize) {\n\t\t\tticketsNeeded := int(targetPoolSize) - ticketsPurchased\n\t\t\tif ticketsNeeded > 0 {\n\t\t\t\tticketOuts = ticketOuts[1 : ticketsNeeded+1]\n\t\t\t} else {\n\t\t\t\tticketOuts = nil\n\t\t\t}\n\t\t}\n\t\tticketsPurchased += len(ticketOuts)\n\n\t\tblockName := fmt.Sprintf(\"bsv%d\", i)\n\t\tg.NextBlock(blockName, nil, ticketOuts)\n\t\tg.SaveTipCoinbaseOuts()\n\t\tacceptedBlockTemplate()\n\t\tg.AcceptTipBlock()\n\t}\n\tg.AssertTipHeight(uint32(stakeValidationHeight))\n\n\t// ---------------------------------------------------------------------\n\t// Generate enough blocks to have a known distance to the first mature\n\t// coinbase outputs for all tests that follow. These blocks continue\n\t// to purchase tickets to avoid running out of votes.\n\t//\n\t// Also, ensure that each block is considered a valid template along the\n\t// way.\n\t//\n\t// ... -> bsv# -> bbm0 -> bbm1 -> ... -> bbm#\n\t// ---------------------------------------------------------------------\n\n\tfor i := uint16(0); i < coinbaseMaturity; i++ {\n\t\touts := g.OldestCoinbaseOuts()\n\t\tblockName := fmt.Sprintf(\"bbm%d\", i)\n\t\tg.NextBlock(blockName, nil, outs[1:])\n\t\tg.SaveTipCoinbaseOuts()\n\t\tacceptedBlockTemplate()\n\t\tg.AcceptTipBlock()\n\t}\n\tg.AssertTipHeight(uint32(stakeValidationHeight) + uint32(coinbaseMaturity))\n\n\t// Collect spendable outputs into two different slices. The outs slice\n\t// is intended to be used for regular transactions that spend from the\n\t// output, while the ticketOuts slice is intended to be used for stake\n\t// ticket purchases.\n\tvar outs []*chaingen.SpendableOut\n\tvar ticketOuts [][]chaingen.SpendableOut\n\tfor i := uint16(0); i < coinbaseMaturity; i++ {\n\t\tcoinbaseOuts := g.OldestCoinbaseOuts()\n\t\touts = append(outs, &coinbaseOuts[0])\n\t\tticketOuts = append(ticketOuts, coinbaseOuts[1:])\n\t}\n\n\t// ---------------------------------------------------------------------\n\t// Generate block templates that build on ancestors of the tip.\n\t// ---------------------------------------------------------------------\n\n\t// Start by building a few of blocks at current tip (value in parens\n\t// is which output is spent):\n\t//\n\t// ... -> b1(0) -> b2(1) -> b3(2)\n\tg.NextBlock(\"b1\", outs[0], ticketOuts[0])\n\tg.AcceptTipBlock()\n\n\tg.NextBlock(\"b2\", outs[1], ticketOuts[1])\n\tg.AcceptTipBlock()\n\n\tg.NextBlock(\"b3\", outs[2], ticketOuts[2])\n\tg.AcceptTipBlock()\n\n\t// Create a block template that forks from b1. It should not be allowed\n\t// since it is not the current tip or its parent.\n\t//\n\t// ... -> b1(0) -> b2(1) -> b3(2)\n\t// \\-> b2at(1)\n\tg.SetTip(\"b1\")\n\tg.NextBlock(\"b2at\", outs[1], ticketOuts[1], changeNonce)\n\trejectedBlockTemplate(ErrInvalidTemplateParent)\n\n\t// Create a block template that forks from b2. It should be accepted\n\t// because it is the current tip's parent.\n\t//\n\t// ... -> b2(1) -> b3(2)\n\t// \\-> b3at(2)\n\tg.SetTip(\"b2\")\n\tg.NextBlock(\"b3at\", outs[2], ticketOuts[2], changeNonce)\n\tacceptedBlockTemplate()\n\n\t// ---------------------------------------------------------------------\n\t// Generate block templates that build on the tip's parent, but include\n\t// invalid votes.\n\t// ---------------------------------------------------------------------\n\n\t// Create a block template that forks from b2 (the tip's parent) with\n\t// votes that spend invalid tickets.\n\t//\n\t// ... -> b2(1) -> b3(2)\n\t// \\-> b3bt(2)\n\tg.SetTip(\"b2\")\n\tg.NextBlock(\"b3bt\", outs[2], ticketOuts[1], changeNonce)\n\trejectedBlockTemplate(ErrMissingTxOut)\n\n\t// Same as before but based on the current tip.\n\t//\n\t// ... -> b2(1) -> b3(2)\n\t// \\-> b4at(3)\n\tg.SetTip(\"b3\")\n\tg.NextBlock(\"b4at\", outs[3], ticketOuts[2], changeNonce)\n\trejectedBlockTemplate(ErrMissingTxOut)\n\n\t// Create a block template that forks from b2 (the tip's parent) with\n\t// a vote that pays too much.\n\t//\n\t// ... -> b2(1) -> b3(2)\n\t// \\-> b3ct(2)\n\tg.SetTip(\"b2\")\n\tg.NextBlock(\"b3ct\", outs[2], ticketOuts[2], func(b *wire.MsgBlock) {\n\t\tchangeNonce(b)\n\t\tb.STransactions[0].TxOut[0].Value++\n\t})\n\trejectedBlockTemplate(ErrSpendTooHigh)\n\n\t// Same as before but based on the current tip.\n\t//\n\t// ... -> b2(1) -> b3(2)\n\t// \\-> b4bt(3)\n\tg.SetTip(\"b3\")\n\tg.NextBlock(\"b4bt\", outs[3], ticketOuts[3], func(b *wire.MsgBlock) {\n\t\tchangeNonce(b)\n\t\tb.STransactions[0].TxOut[0].Value++\n\t})\n\trejectedBlockTemplate(ErrSpendTooHigh)\n\n\t// ---------------------------------------------------------------------\n\t// Generate block templates that build on the tip and its parent after a\n\t// forced reorg.\n\t// ---------------------------------------------------------------------\n\n\t// Create a fork from b2. There should not be a reorg since b3 was seen\n\t// first.\n\t//\n\t// ... -> b2(1) -> b3(2)\n\t// \\-> b3a(2)\n\tg.SetTip(\"b2\")\n\tg.NextBlock(\"b3a\", outs[2], ticketOuts[2])\n\tg.AcceptedToSideChainWithExpectedTip(\"b3\")\n\n\t// Force tip reorganization to b3a.\n\t//\n\t// ... -> b2(1) -> b3a(2)\n\t// \\-> b3(2)\n\tg.ForceTipReorg(\"b3\", \"b3a\")\n\tg.ExpectTip(\"b3a\")\n\n\t// Create a block template that forks from b2 (the tip's parent) and\n\t// ensure it is still accepted after the forced reorg.\n\t//\n\t// ... -> b2(1) -> b3a(2)\n\t// \\-> b3dt(2)\n\tg.SetTip(\"b2\")\n\tg.NextBlock(\"b3dt\", outs[2], ticketOuts[2], changeNonce)\n\tacceptedBlockTemplate()\n\tg.ExpectTip(\"b3a\") // Ensure chain tip didn't change.\n\n\t// Create a block template that builds on the current tip and ensure it\n\t// is still accepted after the forced reorg.\n\t//\n\t// ... -> b2(1) -> b3a(2)\n\t// \\-> b4ct(3)\n\tg.SetTip(\"b3a\")\n\tg.NextBlock(\"b4ct\", outs[3], ticketOuts[3], changeNonce)\n\tacceptedBlockTemplate()\n}", "func TestBlockchain_Validate(t *testing.T) {\n\tblkchain, err := New(genesisBlock)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tblkchain.AddSHA512([]byte(\"NewSTring\"))\n\tblkchain.AddSHA512([]byte(\"NewSTring\"))\n\n\tif err := blkchain.Validate(); err != nil {\n\t\tblkchain.Print()\n\t\tt.Error(err)\n\t}\n\tblkchain2, err := New(genesisBlock)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tblkchain2.AddSHA512([]byte(\"chain2str\"))\n\tblkchain2.AddSHA512([]byte(\"chain2str\"))\n\tblkchain2.AddSHA512([]byte(\"data\"))\n\terr = blkchain2.Validate()\n\tif err != nil {\n\t\tt.Error(\"Failed to Valiate Blockchain\")\n\t}\n\n\tif Equal(blkchain, blkchain2) {\n\t\tt.Error(\"Validity check for blockchain binaries failed\")\n\t}\n}", "func TestInvalidBlockchain(t *testing.T) {\n\tblockchain := Blockchain{}\n\tblockchain.AddBlock(\"hello\")\n\tblockchain.AddBlock(\"data\")\n\n\tblockchain[len(blockchain)-2].Data = \"fake\"\n\n\tassertEq(t, blockchain.IsValid(), false)\n}", "func (m *BlockResult) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateBlock(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateOperationGroups(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}", "func TestAssigningVariableToInvokedBlockWithMultipleValues(t *testing.T) {\n ast := []Node{\n Node{Token: \"ASSIGNMENT\", Row: 3, Col: 1, Data: map[string]interface{}{\"Names\": \"a b\", \"Values\": []Node{}}},\n Node{\n Token: \"INVOCATION\",\n Row: 3,\n Col: 1,\n Data: map[string]interface{}{\"Name\": \"foo\"},\n Children: &[]Node{\n Node{Token: \"BOOL\", Row: 3, Col: 1, Data: map[string]interface{}{\"Value\": true}},\n },\n },\n }\n\n stack := []*StackFrame{\n &StackFrame{\n Blocks: []*Block{\n &Block{\n Name: \"foo\",\n Content: &Node{\n Token: \"BLOCK\",\n Data: map[string]interface{}{\n \"Name\": \"foo\",\n \"Params\": \"a\",\n \"InputQuantity\": 1,\n \"OutputQuantity\": 2,\n },\n Children: &[]Node{\n Node{Token: \"BLOCK_RETURN\"},\n Node{Token: \"IDENTIFIER\", Data: map[string]interface{}{\"Value\": \"a\"}},\n Node{Token: \"IDENTIFIER\", Data: map[string]interface{}{\"Value\": \"a\"}},\n },\n },\n },\n },\n },\n }\n\n wireId = 0\n gateId = 0\n stackFrameId = 0\n gates, wires, callingcontexts, outputs, err := Parse(&ast, stack)\n\n // Verify error\n if err != nil {\n t.Errorf(fmt.Sprintf(\"Error returned! %s\", err))\n return\n }\n\n // Verify gates\n if !reflect.DeepEqual(gates, []*Gate{\n &Gate{\n Id: 1,\n Type: SOURCE,\n Inputs: []*Wire{},\n Outputs: []*Wire{ &Wire{Id: 1} },\n CallingContext: 0,\n },\n &Gate{\n Id: 2,\n Type: BLOCK_INPUT,\n Label: \"Input 0 into block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 1} },\n Outputs: []*Wire{ &Wire{Id: 2} },\n CallingContext: 1,\n },\n &Gate{\n Id: 3,\n Type: BLOCK_OUTPUT,\n Label: \"Output 0 from block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 2} },\n Outputs: []*Wire{ &Wire{Id: 3} },\n CallingContext: 1,\n },\n &Gate{\n Id: 4,\n Type: BLOCK_OUTPUT,\n Label: \"Output 1 from block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 2} },\n Outputs: []*Wire{ &Wire{Id: 4} },\n CallingContext: 1,\n },\n }) {\n // Dereference so we can see the contents of the pointers\n deref := []Gate{}\n for _, gate := range gates {\n deref = append(deref, *gate)\n }\n t.Error(fmt.Sprintf(\"Gates don't match! %+v\", deref))\n }\n\n // Verify wires\n if !reflect.DeepEqual(wires, []*Wire{\n &Wire{Id: 1},\n &Wire{Id: 2},\n &Wire{Id: 2},\n &Wire{Id: 2},\n &Wire{Id: 3},\n &Wire{Id: 4},\n &Wire{Id: 3},\n &Wire{Id: 4},\n }) {\n t.Error(fmt.Sprintf(\"Wires don't match! %+v\", wires))\n }\n\n // Verify calling contexts\n if !reflect.DeepEqual(callingcontexts, []*CallingContext{\n {Id: 1, Name: \"foo\", Depth: 1, Parent: 0, Children: []int{}},\n }) {\n // Dereference so we can see the contents of the pointers\n deref := []CallingContext{}\n for _, cc := range callingcontexts {\n deref = append(deref, *cc)\n }\n t.Error(fmt.Sprintf(\"Calling Contexts don't match! %+v\", deref))\n }\n\n // Verify outputs\n if !reflect.DeepEqual(outputs, []*Wire{}) {\n t.Error(fmt.Sprintf(\"Outputs don't match! %+v\", gates))\n }\n\n // Ensure that the right variables are on the stack\n for _, variable := range stack[0].Variables {\n if variable.Name == \"a\" {\n if variable.Value.Id != 3 {\n t.Errorf(\"Variable a is attached to the wrong wire!\")\n }\n continue\n }\n if variable.Name == \"b\" {\n if variable.Value.Id != 4 {\n t.Errorf(\"Variable b is attached to the wrong wire!\")\n }\n continue\n }\n t.Errorf(fmt.Sprintf(\"Unknown variable %s!\", variable.Name))\n }\n}", "func ValidateEpochBlocks(i interface{}) error {\n\t_, ok := i.(uint32)\n\tif !ok {\n\t\treturn fmt.Errorf(\"invalid parameter type: %T\", i)\n\t}\n\treturn nil\n}", "func TestHandleNewValidator(t *testing.T) {\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\n\taddrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\tvalAddrs := simapp.ConvertAddrsToValAddrs(addrDels)\n\tpks := simapp.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\tctx = ctx.WithBlockHeight(1)\n\n\t// Validator created\n\ttstaking.CreateValidator(addr, val, true)\n\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// Now a validator, for two blocks\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\tctx = ctx.WithBlockHeight(2)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\n\tinfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(1), info.StartHeight)\n\trequire.Equal(t, int64(1), info.MischanceConfidence)\n\trequire.Equal(t, int64(0), info.Mischance)\n\trequire.Equal(t, int64(1), info.MissedBlocksCounter)\n\trequire.Equal(t, int64(1), info.ProducedBlocksCounter)\n\trequire.Equal(t, time.Unix(0, 0).UTC(), info.InactiveUntil)\n\n\t// validator should be active still, should not have been inactivated\n\tvalidator, _ := app.CustomStakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\trequire.Equal(t, stakingtypes.Active, validator.GetStatus())\n}", "func TestBlock(t *testing.T) {\n\tb := btcutil.NewBlock(&Block100000)\n\n\t// Ensure we get the same data back out.\n\tif msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {\n\t\tt.Errorf(\"MsgBlock: mismatched MsgBlock - got %v, want %v\",\n\t\t\tspew.Sdump(msgBlock), spew.Sdump(&Block100000))\n\t}\n\n\t// Ensure block height set and get work properly.\n\twantHeight := int32(100000)\n\tb.SetHeight(wantHeight)\n\tif gotHeight := b.Height(); gotHeight != wantHeight {\n\t\tt.Errorf(\"Height: mismatched height - got %v, want %v\",\n\t\t\tgotHeight, wantHeight)\n\t}\n\n\t// Hash for block 100,000.\n\twantHashStr := \"3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506\"\n\twantHash, err := chainhash.NewHashFromStr(wantHashStr)\n\tif err != nil {\n\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t}\n\n\t// Request the hash multiple times to test generation and caching.\n\tfor i := 0; i < 2; i++ {\n\t\thash := b.Hash()\n\t\tif !hash.IsEqual(wantHash) {\n\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, want %v\",\n\t\t\t\ti, hash, wantHash)\n\t\t}\n\t}\n\n\t// Hashes for the transactions in Block100000.\n\twantTxHashes := []string{\n\t\t\"8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87\",\n\t\t\"fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4\",\n\t\t\"6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4\",\n\t\t\"e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d\",\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request hash for all transactions one at a time via Tx.\n\tfor i, txHash := range wantTxHashes {\n\t\twantHash, err := chainhash.NewHashFromStr(txHash)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t}\n\n\t\t// Request the hash multiple times to test generation and\n\t\t// caching.\n\t\tfor j := 0; j < 2; j++ {\n\t\t\ttx, err := b.Tx(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Tx #%d: %v\", i, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, \"+\n\t\t\t\t\t\"want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request slice of all transactions multiple times to test generation\n\t// and caching.\n\tfor i := 0; i < 2; i++ {\n\t\ttransactions := b.Transactions()\n\n\t\t// Ensure we get the expected number of transactions.\n\t\tif len(transactions) != len(wantTxHashes) {\n\t\t\tt.Errorf(\"Transactions #%d mismatched number of \"+\n\t\t\t\t\"transactions - got %d, want %d\", i,\n\t\t\t\tlen(transactions), len(wantTxHashes))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure all of the hashes match.\n\t\tfor j, tx := range transactions {\n\t\t\twantHash, err := chainhash.NewHashFromStr(wantTxHashes[j])\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Transactions #%d mismatched hashes \"+\n\t\t\t\t\t\"- got %v, want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Serialize the test block.\n\tvar block100000Buf bytes.Buffer\n\terr = Block100000.Serialize(&block100000Buf)\n\tif err != nil {\n\t\tt.Errorf(\"Serialize: %v\", err)\n\t}\n\tblock100000Bytes := block100000Buf.Bytes()\n\n\t// Request serialized bytes multiple times to test generation and\n\t// caching.\n\tfor i := 0; i < 2; i++ {\n\t\tserializedBytes, err := b.Bytes()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Bytes: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(serializedBytes, block100000Bytes) {\n\t\t\tt.Errorf(\"Bytes #%d wrong bytes - got %v, want %v\", i,\n\t\t\t\tspew.Sdump(serializedBytes),\n\t\t\t\tspew.Sdump(block100000Bytes))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// Transaction offsets and length for the transaction in Block100000.\n\twantTxLocs := []wire.TxLoc{\n\t\t{TxStart: 81, TxLen: 144},\n\t\t{TxStart: 225, TxLen: 259},\n\t\t{TxStart: 484, TxLen: 257},\n\t\t{TxStart: 741, TxLen: 225},\n\t}\n\n\t// Ensure the transaction location information is accurate.\n\ttxLocs, err := b.TxLoc()\n\tif err != nil {\n\t\tt.Errorf(\"TxLoc: %v\", err)\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(txLocs, wantTxLocs) {\n\t\tt.Errorf(\"TxLoc: mismatched transaction location information \"+\n\t\t\t\"- got %v, want %v\", spew.Sdump(txLocs),\n\t\t\tspew.Sdump(wantTxLocs))\n\t}\n}", "func (blockExec *BlockExecutor) ValidateBlock(s State, block *ttypes.QbftBlock) error {\n\treturn validateBlock(blockExec.db, s, block)\n}", "func TestAttrStore_Blocks(t *testing.T) {\n\ts := MustOpenAttrStore()\n\tdefer s.Close()\n\n\t// Set attributes.\n\tif err := s.SetAttrs(1, map[string]interface{}{\"A\": uint64(100)}); err != nil {\n\t\tt.Fatal(err)\n\t} else if err := s.SetAttrs(2, map[string]interface{}{\"A\": uint64(200)}); err != nil {\n\t\tt.Fatal(err)\n\t} else if err := s.SetAttrs(100, map[string]interface{}{\"B\": \"VALUE\"}); err != nil {\n\t\tt.Fatal(err)\n\t} else if err := s.SetAttrs(350, map[string]interface{}{\"C\": \"FOO\"}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Retrieve blocks.\n\tblks0, err := s.Blocks()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t} else if len(blks0) != 3 || blks0[0].ID != 0 || blks0[1].ID != 1 || blks0[2].ID != 3 {\n\t\tt.Fatalf(\"unexpected blocks: %#v\", blks0)\n\t}\n\n\t// Change second block.\n\tif err := s.SetAttrs(100, map[string]interface{}{\"X\": 12}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Ensure second block changed.\n\tblks1, err := s.Blocks()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t} else if !reflect.DeepEqual(blks0[0], blks1[0]) {\n\t\tt.Fatalf(\"block 0 mismatch: %#v != %#v\", blks0[0], blks1[0])\n\t} else if reflect.DeepEqual(blks0[1], blks1[1]) {\n\t\tt.Fatalf(\"block 1 match: %#v \", blks0[0])\n\t} else if !reflect.DeepEqual(blks0[2], blks1[2]) {\n\t\tt.Fatalf(\"block 2 mismatch: %#v != %#v\", blks0[2], blks1[2])\n\t}\n}", "func Test_ValidateBlockTransactions_EmptyTransaction(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func (b AcceptedBlock) FullBlockTestInstance() {}", "func (b AcceptedBlock) FullBlockTestInstance() {}", "func CheckSizeBlocks(start, end uint64) error {\n\ttxn := globalOpt.Txn(true)\n\tdefer txn.Commit()\n\n\tlist := make([]interface{}, 0, 64)\n\n\tit, err := txn.Get(TableBlockKey, HeightBlockKey)\n\tif err != nil {\n\t\ttxn.Abort()\n\t\treturn err\n\t}\n\tfor obj := it.Next(); obj != nil; obj = it.Next() {\n\t\tv, ok := obj.(*fabclient.MiddleCommonBlock)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif v.Number < start || v.Number > end {\n\t\t\tlist = append(list, obj)\n\t\t}\n\t}\n\n\tfor _, one := range list {\n\t\terr = txn.Delete(TableBlockKey, one)\n\t\tif err != nil {\n\t\t\ttxn.Abort()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (sb SubdirectoryBlock) Validate() (errors []error) {\n\tfor _, desc := range sb.Descriptors {\n\t\terrors = append(errors, desc.Validate()...)\n\t}\n\tif sb.Extra != 0 {\n\t\terrors = append(errors, fmt.Errorf(\"expected last byte of Subdirectory Block == 0x0; got 0x%02x\", sb.Extra))\n\t}\n\treturn errors\n}", "func checkAndCleanLessFitItems(blocks *[]Block, curentLine, matchedLine int) bool {\n\tfor i, block := range *blocks {\n\t\tif block.IsEqual() {\n\t\t\tfor j, equal := range block.(EqualBlock).Equals {\n\t\t\t\tif equal.RightLine >= matchedLine {\n\t\t\t\t\tif math.Abs(float64(equal.LeftLine-equal.RightLine)) > math.Abs(float64(curentLine-matchedLine)) {\n\t\t\t\t\t\t(*blocks)[i] = EqualBlock{removeItemFromEquals(block.(EqualBlock).Equals, j)}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func BlockFailed(blockNumber uint64){\r\n\r\n}", "func (entry *POEntry) mustApplyBlock(s *Scanner, pluralCount int) {\n\tentry.checkObsolete(s)\n\n\tswitch [2]string{s.Border, s.Prefix} {\n\tcase [2]string{\"#\", \"\"}, [2]string{\"# \", \"\"}:\n\t\tif entry.TComment != \"\" {\n\t\t\tentry.TComment += \"\\n\"\n\t\t}\n\t\tentry.TComment += s.Buffer.String()\n\tcase [2]string{\"#. \", \"\"}:\n\t\tentry.mustBeEmpty(s, entry.EComment)\n\t\tentry.EComment = s.Buffer.String()\n\tcase [2]string{\"#: \", \"\"}:\n\t\tentry.mustBeEmpty(s, entry.Reference)\n\t\tentry.Reference = s.Buffer.String()\n\tcase [2]string{\"#, \", \"\"}:\n\t\tentry.mustBeEmpty(s, entry.Flags.String())\n\t\tentry.Flags.Parse(s.Buffer.String())\n\tcase [2]string{prevBorder, \"msgctxt \"}:\n\t\tentry.mustBeEmpty(s, entry.PrevMsgCtxt)\n\t\tentry.PrevMsgCtxt = s.Buffer.String()\n\tcase [2]string{prevBorder, \"msgid \"}:\n\t\tentry.mustBeEmpty(s, entry.PrevMsgID)\n\t\tentry.PrevMsgID = s.Buffer.String()\n\tcase [2]string{prevBorder, \"msgid_plural \"}:\n\t\tentry.mustBeEmpty(s, entry.PrevMsgIDP)\n\t\tentry.PrevMsgIDP = s.Buffer.String()\n\tcase [2]string{\"\", \"msgctxt \"},\n\t\t[2]string{\"#~ \", \"msgctxt \"}:\n\t\tentry.mustBeEmpty(s, entry.MsgCtxt)\n\t\tentry.MsgCtxt = s.Buffer.String()\n\tcase [2]string{\"\", \"msgid \"},\n\t\t[2]string{\"#~ \", \"msgid \"}:\n\t\tentry.mustBeEmpty(s, entry.MsgID)\n\t\tentry.MsgID = s.Buffer.String()\n\tcase [2]string{\"\", \"msgid_plural \"},\n\t\t[2]string{\"#~ \", \"msgid_plural \"}:\n\t\tentry.mustBeEmpty(s, entry.MsgIDP)\n\t\tentry.MsgIDP = s.Buffer.String()\n\tcase [2]string{\"\", \"msgstr \"},\n\t\t[2]string{\"#~ \", \"msgstr \"}:\n\t\tentry.mustBeEmpty(s, entry.MsgStr)\n\t\tentry.MsgStr = s.Buffer.String()\n\tdefault:\n\t\tentry.updateMsgStrP(s, pluralCount)\n\t}\n}", "func (p *Proof) Validate(header *BlockHeader, cuckooSize uint8) error {\n\tlogrus.Infof(\"block POW validate for size %d\", cuckooSize)\n\n\tcuckoo := cuckoo.NewCuckaroo(header.bytesWithoutPOW())\n\tif cuckoo.Verify(header.POW.Nonces, header.POW.EdgeBits) {\n\t\treturn nil\n\t}\n\n\treturn errInvalidPow\n}", "func TestMissedBlockAndRankStreakCounter(t *testing.T) {\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\n\taddrDels := simapp.AddTestAddrsIncremental(app, ctx, 1, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\tvalAddrs := simapp.ConvertAddrsToValAddrs(addrDels)\n\tpks := simapp.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\tvalAddr := sdk.ValAddress(addr)\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\tctx = ctx.WithBlockHeight(1)\n\n\t// Validator created\n\ttstaking.CreateValidator(addr, val, true)\n\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// Now a validator, for two blocks\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\tctx = ctx.WithBlockHeight(2)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\n\tv := tstaking.CheckValidator(valAddr, stakingtypes.Active)\n\trequire.Equal(t, v.Rank, int64(1))\n\trequire.Equal(t, v.Streak, int64(1))\n\n\tinfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(1), info.MischanceConfidence)\n\trequire.Equal(t, int64(0), info.Mischance)\n\trequire.Equal(t, int64(1), info.MissedBlocksCounter)\n\trequire.Equal(t, int64(1), info.ProducedBlocksCounter)\n\n\theight := ctx.BlockHeight() + 1\n\tfor i := int64(0); i < 10; i++ {\n\t\tctx = ctx.WithBlockHeight(height + i)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\t}\n\tctx = ctx.WithBlockHeight(height + 10)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\tinfo, found = app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\trequire.True(t, found)\n\trequire.Equal(t, int64(0), info.MischanceConfidence)\n\trequire.Equal(t, int64(0), info.Mischance)\n\trequire.Equal(t, int64(11), info.MissedBlocksCounter)\n\trequire.Equal(t, int64(2), info.ProducedBlocksCounter)\n\n\tv = tstaking.CheckValidator(valAddr, stakingtypes.Active)\n\trequire.Equal(t, v.Rank, int64(1))\n\trequire.Equal(t, v.Streak, int64(1))\n\n\t// sign 100 blocks successfully\n\theight = ctx.BlockHeight() + 1\n\tfor i := int64(0); i < 100; i++ {\n\t\tctx = ctx.WithBlockHeight(height + i)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\t}\n\n\tv = tstaking.CheckValidator(valAddr, stakingtypes.Active)\n\trequire.Equal(t, v.Rank, int64(101))\n\trequire.Equal(t, v.Streak, int64(101))\n\n\t// miss one block\n\tctx = ctx.WithBlockHeight(height + 100)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\tv = tstaking.CheckValidator(valAddr, stakingtypes.Active)\n\trequire.Equal(t, v.Rank, int64(101))\n\trequire.Equal(t, v.Streak, int64(101))\n\n\tapp.CustomSlashingKeeper.Inactivate(ctx, sdk.ConsAddress(val.Address()))\n\tv = tstaking.CheckValidator(valAddr, stakingtypes.Inactive)\n\trequire.Equal(t, v.Rank, int64(50))\n\trequire.Equal(t, v.Streak, int64(0))\n\n\tapp.CustomSlashingKeeper.Activate(ctx, valAddr)\n\t// miss 5 blocks\n\theight = ctx.BlockHeight() + 1\n\tfor i := int64(0); i < 5; i++ {\n\t\tctx = ctx.WithBlockHeight(height + i)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\t}\n\tv = tstaking.CheckValidator(valAddr, stakingtypes.Active)\n\trequire.Equal(t, v.Rank, int64(50))\n\trequire.Equal(t, v.Streak, int64(0))\n}", "func ValidateBlockLength(blockLength uint32) (bool) {\n if blockLength <= 4294967295 && blockLength > 0 { //2^32 -1 ~ 4GB or maximum possible block length\n return true\n }\n return false\n}", "func CheckBlockNumValidateWithOp(n uint8, blockHash string) bool {\n\t// access the block for the operation\n\treturn true\n}", "func AddBlock(block *types.Block, db *types.DB) {\n\ttxCheck := func(txs []*types.Tx) bool {\n\t\t// start = copy.deepcopy(txs)\n\t\tvar start = txs\n\t\tvar txsSource []*types.Tx\n\t\tvar startCopy []*types.Tx\n\n\t\tfor !reflect.DeepEqual(start, startCopy) {\n\t\t\t// Block passes this test\n\t\t\tif start == nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// startCopy = copy.deepcopy(start)\n\t\t\tstartCopy = start\n\t\t\tlast := start[len(start)-1]\n\n\t\t\t// transactions.tx_check[start[-1]['type']](start[-1], out, DB)\n\t\t\tfn := transactionVerify[last.Type]\n\t\t\tif fn(last, txsSource, db) {\n\t\t\t\t// start.pop()\n\t\t\t\tstart = start[:len(start)-1]\n\t\t\t\ttxsSource = append(txsSource, last)\n\t\t\t} else {\n\t\t\t\t// Block is invalid\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// Block is invalid\n\t\treturn true\n\t}\n\n\t// if \"error\" in block: return False\n\tif block.Error != nil {\n\t\treturn\n\t}\n\n\t// if \"length\" not in block: return False\n\t// NOTE: block.Length not being set means it takes its \"zero value\".\n\t// This shouldn't be a problem, check out next if stmt.\n\tif block.Length == 0 {\n\t\treturn\n\t}\n\n\tlength := db.Length\n\tif block.Length != length+1 {\n\t\treturn\n\t}\n\n\tif block.DiffLength != HexSum(db.DiffLength, HexInv(block.Target)) {\n\t\treturn\n\t}\n\n\tif length >= 0 && tools.DetHash(db.GetBlock(length)) != block.PrevHash {\n\t\treturn\n\t}\n\n\t// a = copy.deepcopy(block)\n\t// a.pop(\"nonce\")\n\tblockCopy := block\n\tblockCopy.Nonce = nil\n\n\t//if \"target\" not in block.keys(): return False\n\tif block.Target == \"\" {\n\t\treturn\n\t}\n\n\thalfWay := &types.HalfWay{\n\t\tNonce: block.Nonce,\n\t\tHalfHash: tools.DetHash(blockCopy),\n\t}\n\n\tif tools.DetHash(halfWay) > block.Target {\n\t\treturn\n\t}\n\n\tif block.Target != Target(db, block.Length) {\n\t\treturn\n\t}\n\n\t// TODO: Figure out why 8 (length)?\n\tearliestMedian := median(RecentBlockTimes(db, config.Get().Mmm, 8))\n\t// `float64` (unix epoch) back to `time.Time`\n\tsec, nsec := math.Modf(earliestMedian)\n\tearliest := time.Unix(int64(sec), int64(nsec*1e9))\n\n\t// if block.Time > time.time(): return false\n\t// if block.Time < earliest: return false\n\tif block.Time.After(time.Now()) || block.Time.Before(earliest) {\n\t\treturn\n\t}\n\n\tif txCheck(block.Txs) {\n\t\treturn\n\t}\n\n\t// block_check was unnecessary because it was only called once\n\t// and it only returned true at its end\n\n\t// if block_check(block, db):\n\tlog.Println(\"add_block:\", block)\n\tdb.Put(strconv.Itoa(block.Length), block)\n\n\tdb.Length = block.Length\n\tdb.DiffLength = block.DiffLength\n\n\torphans := db.Txs\n\tdb.Txs = nil\n\n\tfor _, tx := range block.Txs {\n\t\tdb.AddBlock = true\n\t\tfn := transactionUpdate[tx.Type]\n\t\tfn(tx, db)\n\t}\n\n\tfor _, tx := range orphans {\n\t\tAddTx(tx, db)\n\t}\n}", "func (*BasicBlock) isValue() {}", "func validate(tx *Tx) bool {\n\tfor _, txIn := range tx.TxIns {\n\t\t// Find the transaction that created the transaction input\n\t\tprevTx := FindTx(Blockchain(), txIn.TxId)\n\t\tif prevTx == nil {\n\t\t\t// Fake input: not on the blockchain\n\t\t\treturn false\n\t\t}\n\t\tprevTxOut := prevTx.TxOuts[txIn.Index]\n\t\taddress := prevTxOut.Address\n\t\t// If the public key (address) cannot verify the signature that I just\n\t\t// created w/ my wallet, that means the TxOuts/funds are not actually mine\n\t\tif !wallet.Verify(tx.Id, txIn.Signature, address) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true // All transaction inputs verfied\n}", "func (pow *ProofOfWork) Validate() bool {\n\t// we run the Run() loop one more time\n\tvar attempt big.Int\n\n\tdata := pow.InitiateData(pow.Block.Nonce)\n\thash := sha256.Sum256(data)\n\tattempt.SetBytes(hash[:])\n\n\treturn attempt.Cmp(pow.Target) == -1\n}", "func TestValidatorDippingInAndOut(t *testing.T) {\n\t// initial setup\n\tapp := simapp.Setup(false)\n\tctx := app.BaseApp.NewContext(false, tmproto.Header{})\n\tapp.CustomSlashingKeeper.SetParams(ctx, testslashing.TestParams())\n\n\tpower := int64(100)\n\n\tpks := simapp.CreateTestPubKeys(3)\n\tsimapp.AddTestAddrsFromPubKeys(app, ctx, pks, sdk.TokensFromConsensusPower(200, sdk.DefaultPowerReduction))\n\n\taddr, val := pks[0].Address(), pks[0]\n\tconsAddr := sdk.ConsAddress(addr)\n\ttstaking := teststaking.NewHelper(t, ctx, app.CustomStakingKeeper, app.CustomGovKeeper)\n\tvalAddr := sdk.ValAddress(addr)\n\n\ttstaking.CreateValidator(valAddr, val, true)\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\n\t// 100 first blocks OK\n\theight := int64(0)\n\tfor ; height < int64(100); height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), power, true)\n\t}\n\n\t// add one more validator into the set\n\ttstaking.CreateValidator(sdk.ValAddress(pks[1].Address()), pks[1], true)\n\tvalidatorUpdates := staking.EndBlocker(ctx, app.CustomStakingKeeper)\n\trequire.Equal(t, 1, len(validatorUpdates))\n\ttstaking.CheckValidator(valAddr, stakingtypes.Active)\n\ttstaking.CheckValidator(sdk.ValAddress(pks[1].Address()), stakingtypes.Active)\n\n\t// 600 more blocks happened\n\theight = 700\n\tctx = ctx.WithBlockHeight(height)\n\n\tvalidatorUpdates = staking.EndBlocker(ctx, app.CustomStakingKeeper)\n\trequire.Equal(t, 0, len(validatorUpdates))\n\ttstaking.CheckValidator(valAddr, stakingtypes.Active)\n\n\t// shouldn't be inactive/kicked yet\n\ttstaking.CheckValidator(valAddr, stakingtypes.Active)\n\n\t// validator misses 500 more blocks, 501 total\n\tlatest := height\n\tfor ; height < latest+501; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, addr, 1, false)\n\t}\n\n\t// should now be inactive & kicked\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Inactive)\n\n\t// check all the signing information\n\tsignInfo, found := app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, consAddr)\n\trequire.True(t, found)\n\trequire.Equal(t, int64(10), signInfo.MischanceConfidence)\n\trequire.Equal(t, int64(111), signInfo.Mischance)\n\trequire.Equal(t, int64(99), signInfo.LastPresentBlock)\n\trequire.Equal(t, int64(121), signInfo.MissedBlocksCounter)\n\trequire.Equal(t, int64(100), signInfo.ProducedBlocksCounter)\n\n\t// some blocks pass\n\theight = int64(5000)\n\tctx = ctx.WithBlockHeight(height)\n\n\t// Try pausing on inactive node here, should fail\n\terr := app.CustomSlashingKeeper.Pause(ctx, valAddr)\n\trequire.Error(t, err)\n\n\t// validator rejoins and starts signing again\n\tapp.CustomSlashingKeeper.Activate(ctx, valAddr)\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 1, true)\n\theight++\n\n\t// validator should be active after signing next block after active\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Active)\n\n\t// miss one block after pause\n\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 1, false)\n\theight++\n\n\t// Try pausing on active node here, should success\n\terr = app.CustomSlashingKeeper.Pause(ctx, valAddr)\n\trequire.NoError(t, err)\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Paused)\n\n\t// validator misses 501 blocks\n\tlatest = height\n\tfor ; height < latest+501; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 1, false)\n\t}\n\n\t// validator should not be in inactive status since node is paused\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Paused)\n\n\t// After reentering after unpause, check if signature info is recovered correctly\n\tsignInfo, found = app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, consAddr)\n\trequire.True(t, found)\n\trequire.Equal(t, int64(1), signInfo.MischanceConfidence)\n\trequire.Equal(t, int64(0), signInfo.Mischance)\n\trequire.Equal(t, int64(5000), signInfo.LastPresentBlock)\n\trequire.Equal(t, int64(122), signInfo.MissedBlocksCounter)\n\trequire.Equal(t, int64(101), signInfo.ProducedBlocksCounter)\n\n\t// Try activating paused node: should unpause but it's activating - should fail\n\terr = app.CustomSlashingKeeper.Activate(ctx, valAddr)\n\trequire.Error(t, err)\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Paused)\n\n\t// Unpause node and it should be active\n\terr = app.CustomSlashingKeeper.Unpause(ctx, valAddr)\n\trequire.NoError(t, err)\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Active)\n\n\t// After reentering after unpause, check if signature info is recovered correctly\n\tsignInfo, found = app.CustomSlashingKeeper.GetValidatorSigningInfo(ctx, consAddr)\n\trequire.True(t, found)\n\trequire.Equal(t, int64(1), signInfo.MischanceConfidence)\n\trequire.Equal(t, int64(0), signInfo.Mischance)\n\trequire.Equal(t, int64(5000), signInfo.LastPresentBlock)\n\trequire.Equal(t, int64(122), signInfo.MissedBlocksCounter)\n\trequire.Equal(t, int64(101), signInfo.ProducedBlocksCounter)\n\n\t// Miss another 501 blocks\n\tlatest = height\n\tfor ; height < latest+501; height++ {\n\t\tctx = ctx.WithBlockHeight(height)\n\t\tapp.CustomSlashingKeeper.HandleValidatorSignature(ctx, val.Address(), 1, false)\n\t}\n\n\t// validator should be in inactive status\n\tstaking.EndBlocker(ctx, app.CustomStakingKeeper)\n\ttstaking.CheckValidator(valAddr, stakingtypes.Inactive)\n}", "func TestSimulateValidatorsChange(t *testing.T) {\n\tnPeers := 7\n\tnVals := 4\n\tcss, genDoc, config, cleanup := randConsensusNetWithPeers(\n\t\tnVals,\n\t\tnPeers,\n\t\t\"replay_test\",\n\t\tnewMockTickerFunc(true),\n\t\tnewPersistentKVStoreWithPath)\n\tsim.Config = config\n\tsim.GenesisState, _ = sm.MakeGenesisState(genDoc)\n\tsim.CleanupFunc = cleanup\n\n\tpartSize := types.BlockPartSizeBytes\n\n\tnewRoundCh := subscribe(css[0].eventBus, types.EventQueryNewRound)\n\tproposalCh := subscribe(css[0].eventBus, types.EventQueryCompleteProposal)\n\n\tvss := make([]*validatorStub, nPeers)\n\tfor i := 0; i < nPeers; i++ {\n\t\tvss[i] = newValidatorStub(css[i].privValidator, int32(i))\n\t}\n\theight, round := css[0].Height, css[0].Round\n\n\t// start the machine\n\tstartTestRound(css[0], height, round)\n\tincrementHeight(vss...)\n\tensureNewRound(newRoundCh, height, 0)\n\tensureNewProposal(proposalCh, height, round)\n\trs := css[0].GetRoundState()\n\tsignAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)\n\tensureNewRound(newRoundCh, height+1, 0)\n\n\t// HEIGHT 2\n\theight++\n\tincrementHeight(vss...)\n\tnewValidatorPubKey1, err := css[nVals].privValidator.GetPubKey()\n\trequire.NoError(t, err)\n\tvalPubKey1ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey1)\n\trequire.NoError(t, err)\n\tnewValidatorTx1 := kvstore.MakeValSetChangeTx(valPubKey1ABCI, testMinPower)\n\terr = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx1, nil, mempl.TxInfo{})\n\tassert.Nil(t, err)\n\tpropBlock, _ := css[0].createProposalBlock() // changeProposer(t, cs1, vs2)\n\tpropBlockParts := propBlock.MakePartSet(partSize)\n\tblockID := types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}\n\n\tproposal := types.NewProposal(vss[1].Height, round, -1, blockID)\n\tp := proposal.ToProto()\n\tif err := vss[1].SignProposal(config.ChainID(), p); err != nil {\n\t\tt.Fatal(\"failed to sign bad proposal\", err)\n\t}\n\tproposal.Signature = p.Signature\n\n\t// set the proposal block\n\tif err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, \"some peer\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tensureNewProposal(proposalCh, height, round)\n\trs = css[0].GetRoundState()\n\tsignAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)\n\tensureNewRound(newRoundCh, height+1, 0)\n\n\t// HEIGHT 3\n\theight++\n\tincrementHeight(vss...)\n\tupdateValidatorPubKey1, err := css[nVals].privValidator.GetPubKey()\n\trequire.NoError(t, err)\n\tupdatePubKey1ABCI, err := cryptoenc.PubKeyToProto(updateValidatorPubKey1)\n\trequire.NoError(t, err)\n\tupdateValidatorTx1 := kvstore.MakeValSetChangeTx(updatePubKey1ABCI, 25)\n\terr = assertMempool(css[0].txNotifier).CheckTx(updateValidatorTx1, nil, mempl.TxInfo{})\n\tassert.Nil(t, err)\n\tpropBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)\n\tpropBlockParts = propBlock.MakePartSet(partSize)\n\tblockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}\n\n\tproposal = types.NewProposal(vss[2].Height, round, -1, blockID)\n\tp = proposal.ToProto()\n\tif err := vss[2].SignProposal(config.ChainID(), p); err != nil {\n\t\tt.Fatal(\"failed to sign bad proposal\", err)\n\t}\n\tproposal.Signature = p.Signature\n\n\t// set the proposal block\n\tif err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, \"some peer\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tensureNewProposal(proposalCh, height, round)\n\trs = css[0].GetRoundState()\n\tsignAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), vss[1:nVals]...)\n\tensureNewRound(newRoundCh, height+1, 0)\n\n\t// HEIGHT 4\n\theight++\n\tincrementHeight(vss...)\n\tnewValidatorPubKey2, err := css[nVals+1].privValidator.GetPubKey()\n\trequire.NoError(t, err)\n\tnewVal2ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey2)\n\trequire.NoError(t, err)\n\tnewValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, testMinPower)\n\terr = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx2, nil, mempl.TxInfo{})\n\tassert.Nil(t, err)\n\tnewValidatorPubKey3, err := css[nVals+2].privValidator.GetPubKey()\n\trequire.NoError(t, err)\n\tnewVal3ABCI, err := cryptoenc.PubKeyToProto(newValidatorPubKey3)\n\trequire.NoError(t, err)\n\tnewValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, testMinPower)\n\terr = assertMempool(css[0].txNotifier).CheckTx(newValidatorTx3, nil, mempl.TxInfo{})\n\tassert.Nil(t, err)\n\tpropBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)\n\tpropBlockParts = propBlock.MakePartSet(partSize)\n\tblockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}\n\tnewVss := make([]*validatorStub, nVals+1)\n\tcopy(newVss, vss[:nVals+1])\n\tsort.Sort(ValidatorStubsByPower(newVss))\n\n\tvalIndexFn := func(cssIdx int) int {\n\t\tfor i, vs := range newVss {\n\t\t\tvsPubKey, err := vs.GetPubKey()\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcssPubKey, err := css[cssIdx].privValidator.GetPubKey()\n\t\t\trequire.NoError(t, err)\n\n\t\t\tif vsPubKey.Equals(cssPubKey) {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\tpanic(fmt.Sprintf(\"validator css[%d] not found in newVss\", cssIdx))\n\t}\n\n\tselfIndex := valIndexFn(0)\n\n\tproposal = types.NewProposal(vss[3].Height, round, -1, blockID)\n\tp = proposal.ToProto()\n\tif err := vss[3].SignProposal(config.ChainID(), p); err != nil {\n\t\tt.Fatal(\"failed to sign bad proposal\", err)\n\t}\n\tproposal.Signature = p.Signature\n\n\t// set the proposal block\n\tif err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, \"some peer\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tensureNewProposal(proposalCh, height, round)\n\n\tremoveValidatorTx2 := kvstore.MakeValSetChangeTx(newVal2ABCI, 0)\n\terr = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx2, nil, mempl.TxInfo{})\n\tassert.Nil(t, err)\n\n\trs = css[0].GetRoundState()\n\tfor i := 0; i < nVals+1; i++ {\n\t\tif i == selfIndex {\n\t\t\tcontinue\n\t\t}\n\t\tsignAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])\n\t}\n\n\tensureNewRound(newRoundCh, height+1, 0)\n\n\t// HEIGHT 5\n\theight++\n\tincrementHeight(vss...)\n\t// Reflect the changes to vss[nVals] at height 3 and resort newVss.\n\tnewVssIdx := valIndexFn(nVals)\n\tnewVss[newVssIdx].VotingPower = 25\n\tsort.Sort(ValidatorStubsByPower(newVss))\n\tselfIndex = valIndexFn(0)\n\tensureNewProposal(proposalCh, height, round)\n\trs = css[0].GetRoundState()\n\tfor i := 0; i < nVals+1; i++ {\n\t\tif i == selfIndex {\n\t\t\tcontinue\n\t\t}\n\t\tsignAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])\n\t}\n\tensureNewRound(newRoundCh, height+1, 0)\n\n\t// HEIGHT 6\n\theight++\n\tincrementHeight(vss...)\n\tremoveValidatorTx3 := kvstore.MakeValSetChangeTx(newVal3ABCI, 0)\n\terr = assertMempool(css[0].txNotifier).CheckTx(removeValidatorTx3, nil, mempl.TxInfo{})\n\tassert.Nil(t, err)\n\tpropBlock, _ = css[0].createProposalBlock() // changeProposer(t, cs1, vs2)\n\tpropBlockParts = propBlock.MakePartSet(partSize)\n\tblockID = types.BlockID{Hash: propBlock.Hash(), PartSetHeader: propBlockParts.Header()}\n\tnewVss = make([]*validatorStub, nVals+3)\n\tcopy(newVss, vss[:nVals+3])\n\tsort.Sort(ValidatorStubsByPower(newVss))\n\n\tselfIndex = valIndexFn(0)\n\tproposal = types.NewProposal(vss[1].Height, round, -1, blockID)\n\tp = proposal.ToProto()\n\tif err := vss[1].SignProposal(config.ChainID(), p); err != nil {\n\t\tt.Fatal(\"failed to sign bad proposal\", err)\n\t}\n\tproposal.Signature = p.Signature\n\n\t// set the proposal block\n\tif err := css[0].SetProposalAndBlock(proposal, propBlock, propBlockParts, \"some peer\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tensureNewProposal(proposalCh, height, round)\n\trs = css[0].GetRoundState()\n\tfor i := 0; i < nVals+3; i++ {\n\t\tif i == selfIndex {\n\t\t\tcontinue\n\t\t}\n\t\tsignAddVotes(css[0], tmproto.PrecommitType, rs.ProposalBlock.Hash(), rs.ProposalBlockParts.Header(), newVss[i])\n\t}\n\tensureNewRound(newRoundCh, height+1, 0)\n\n\tsim.Chain = make([]*types.Block, 0)\n\tsim.Commits = make([]*types.Commit, 0)\n\tfor i := 1; i <= numBlocks; i++ {\n\t\tsim.Chain = append(sim.Chain, css[0].blockStore.LoadBlock(int64(i)))\n\t\tsim.Commits = append(sim.Commits, css[0].blockStore.LoadBlockCommit(int64(i)))\n\t}\n}", "func (n *NodeBlockMaker) checkGoodTimeToMakeBlock() bool {\n\treturn true\n}", "func TestAssigningVariableToInvokedBlock(t *testing.T) {\n ast := []Node{\n Node{Token: \"ASSIGNMENT\", Row: 3, Col: 1, Data: map[string]interface{}{\"Names\": \"a\", \"Values\": []Node{}}},\n Node{\n Token: \"INVOCATION\",\n Row: 3,\n Col: 1,\n Data: map[string]interface{}{\"Name\": \"foo\"},\n Children: &[]Node{\n Node{Token: \"BOOL\", Row: 3, Col: 1, Data: map[string]interface{}{\"Value\": true}},\n },\n },\n }\n\n stack := []*StackFrame{\n &StackFrame{\n Blocks: []*Block{\n &Block{\n Name: \"foo\",\n Content: &Node{\n Token: \"BLOCK\",\n Data: map[string]interface{}{\n \"Name\": \"foo\",\n \"Params\": \"a\",\n \"InputQuantity\": 1,\n \"OutputQuantity\": 1,\n },\n Children: &[]Node{\n Node{Token: \"BLOCK_RETURN\"},\n Node{Token: \"IDENTIFIER\", Data: map[string]interface{}{\"Value\": \"a\"}},\n },\n },\n },\n },\n },\n }\n\n wireId = 0\n gateId = 0\n stackFrameId = 0\n gates, wires, callingcontexts, outputs, err := Parse(&ast, stack)\n\n // Verify error\n if err != nil {\n t.Errorf(fmt.Sprintf(\"Error returned! %s\", err))\n return\n }\n\n // Verify gates\n if !reflect.DeepEqual(gates, []*Gate{\n &Gate{\n Id: 1,\n Type: SOURCE,\n Inputs: []*Wire{},\n Outputs: []*Wire{ &Wire{Id: 1} },\n CallingContext: 0,\n },\n &Gate{\n Id: 2,\n Type: BLOCK_INPUT,\n Label: \"Input 0 into block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 1} },\n Outputs: []*Wire{ &Wire{Id: 2} },\n CallingContext: 1,\n },\n &Gate{\n Id: 3,\n Type: BLOCK_OUTPUT,\n Label: \"Output 0 from block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 2} },\n Outputs: []*Wire{ &Wire{Id: 3} },\n CallingContext: 1,\n },\n }) {\n // Dereference so we can see the contents of the pointers\n deref := []Gate{}\n for _, gate := range gates {\n deref = append(deref, *gate)\n }\n t.Error(fmt.Sprintf(\"Gates don't match! %+v\", deref))\n }\n\n // Verify wires\n if !reflect.DeepEqual(wires, []*Wire{\n &Wire{Id: 1},\n &Wire{Id: 2},\n &Wire{Id: 2},\n &Wire{Id: 3},\n &Wire{Id: 3},\n }) {\n t.Error(fmt.Sprintf(\"Wires don't match! %+v\", wires))\n }\n\n // Verify calling contexts\n if !reflect.DeepEqual(callingcontexts, []*CallingContext{\n {Id: 1, Name: \"foo\", Depth: 1, Parent: 0, Children: []int{}},\n }) {\n // Dereference so we can see the contents of the pointers\n deref := []CallingContext{}\n for _, cc := range callingcontexts {\n deref = append(deref, *cc)\n }\n t.Error(fmt.Sprintf(\"Calling Contexts don't match! %+v\", deref))\n }\n\n // Verify outputs\n if !reflect.DeepEqual(outputs, []*Wire{}) {\n t.Error(fmt.Sprintf(\"Outputs don't match! %+v\", gates))\n }\n\n // Ensure that the right variables are on the stack\n for _, variable := range stack[0].Variables {\n if variable.Name == \"a\" {\n if variable.Value.Id != 3 {\n t.Errorf(\"Variable a is attached to the wrong wire!\")\n }\n continue\n }\n t.Errorf(fmt.Sprintf(\"Unknown variable %s!\", variable.Name))\n }\n}", "func TestAssigningVariableToInvokedBlockWithMultipleValuesAcrossMultipleTokens(t *testing.T) {\n ast := []Node{\n Node{\n Token: \"ASSIGNMENT\",\n Row: 3,\n Col: 1,\n Data: map[string]interface{}{\n \"Names\": \"a b c\",\n \"Values\": []Node{},\n },\n },\n Node{\n Token: \"INVOCATION\",\n Row: 3,\n Col: 1,\n Data: map[string]interface{}{\"Name\": \"foo\"},\n Children: &[]Node{\n Node{Token: \"BOOL\", Row: 3, Col: 1, Data: map[string]interface{}{\"Value\": true}},\n },\n },\n Node{Token: \"BOOL\", Row: 3, Col: 1, Data: map[string]interface{}{\"Value\": true}},\n }\n\n stack := []*StackFrame{\n &StackFrame{\n Blocks: []*Block{\n &Block{\n Name: \"foo\",\n Content: &Node{\n Token: \"BLOCK\",\n Data: map[string]interface{}{\n \"Name\": \"foo\",\n \"Params\": \"a\",\n \"InputQuantity\": 1,\n \"OutputQuantity\": 2,\n },\n Children: &[]Node{\n Node{Token: \"BLOCK_RETURN\"},\n Node{Token: \"IDENTIFIER\", Data: map[string]interface{}{\"Value\": \"a\"}},\n Node{Token: \"IDENTIFIER\", Data: map[string]interface{}{\"Value\": \"a\"}},\n },\n },\n },\n },\n },\n }\n\n wireId = 0\n gateId = 0\n stackFrameId = 0\n gates, wires, callingcontexts, outputs, err := Parse(&ast, stack)\n\n // Verify error\n if err != nil {\n t.Errorf(fmt.Sprintf(\"Error returned! %s\", err))\n return\n }\n\n // Verify gates\n if !reflect.DeepEqual(gates, []*Gate{\n &Gate{\n Id: 1,\n Type: SOURCE,\n Inputs: []*Wire{},\n Outputs: []*Wire{ &Wire{Id: 1} },\n CallingContext: 0,\n },\n &Gate{\n Id: 2,\n Type: BLOCK_INPUT,\n Label: \"Input 0 into block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 1} },\n Outputs: []*Wire{ &Wire{Id: 2} },\n CallingContext: 1,\n },\n &Gate{\n Id: 3,\n Type: BLOCK_OUTPUT,\n Label: \"Output 0 from block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 2} },\n Outputs: []*Wire{ &Wire{Id: 3} },\n CallingContext: 1,\n },\n &Gate{\n Id: 4,\n Type: BLOCK_OUTPUT,\n Label: \"Output 1 from block foo invocation 1\",\n Inputs: []*Wire{ &Wire{Id: 2} },\n Outputs: []*Wire{ &Wire{Id: 4} },\n CallingContext: 1,\n },\n &Gate{\n Id: 5,\n Type: SOURCE,\n Inputs: []*Wire{},\n Outputs: []*Wire{ &Wire{Id: 5} },\n CallingContext: 0,\n },\n }) {\n // Dereference so we can see the contents of the pointers\n deref := []Gate{}\n for _, gate := range gates {\n deref = append(deref, *gate)\n }\n t.Error(fmt.Sprintf(\"Gates don't match! %+v\", deref))\n }\n\n // Verify wires\n if !reflect.DeepEqual(wires, []*Wire{\n &Wire{Id: 1},\n &Wire{Id: 2},\n &Wire{Id: 2},\n &Wire{Id: 2},\n &Wire{Id: 3},\n &Wire{Id: 4},\n &Wire{Id: 5},\n &Wire{Id: 3},\n &Wire{Id: 4},\n &Wire{Id: 5},\n }) {\n t.Error(fmt.Sprintf(\"Wires don't match! %+v\", wires))\n }\n\n // Ensure that the right variables are on the stack\n for _, variable := range stack[0].Variables {\n if variable.Name == \"a\" {\n if variable.Value.Id != 3 {\n t.Errorf(\"Variable a is attached to the wrong wire!\")\n }\n continue\n }\n if variable.Name == \"b\" {\n if variable.Value.Id != 4 {\n t.Errorf(\"Variable b is attached to the wrong wire!\")\n }\n continue\n }\n if variable.Name == \"c\" {\n if variable.Value.Id != 5 {\n t.Errorf(\"Variable c is attached to the wrong wire!\")\n }\n continue\n }\n\n t.Errorf(fmt.Sprintf(\"Unknown variable %s!\", variable.Name))\n }\n\n // Verify calling contexts\n if !reflect.DeepEqual(callingcontexts, []*CallingContext{\n {Id: 1, Name: \"foo\", Depth: 1, Parent: 0, Children: []int{}},\n }) {\n // Dereference so we can see the contents of the pointers\n deref := []CallingContext{}\n for _, cc := range callingcontexts {\n deref = append(deref, *cc)\n }\n t.Error(fmt.Sprintf(\"Calling Contexts don't match! %+v\", deref))\n }\n\n // Verify outputs\n if !reflect.DeepEqual(outputs, []*Wire{}) {\n t.Error(fmt.Sprintf(\"Outputs don't match! %+v\", gates))\n }\n}", "func (bc *Blockchain) Validate() bool {\n\tfor i := 0; i < len(*bc); i++ {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif !(*bc)[i].Validate((*bc)[i-1]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (pow *ProofOfWork) Validate() bool {\n\tvar intHash big.Int\n\n\t// run the cycle with the processed hash\n\tdata := pow.InitData(pow.Block.Nonce)\n\n\thash := sha256.Sum256(data)\n\tintHash.SetBytes(hash[:])\n\n\t// compare if the target is greater than the hash\n\treturn intHash.Cmp(pow.Target) == -1\n}", "func TestThatAByzantineLeaderCanNotCauseAForkBySendingTwoBlocks(t *testing.T) {\n\ttest.WithContextWithTimeout(t, 15*time.Second, func(ctx context.Context) {\n\t\tblock1 := mocks.ABlock(interfaces.GenesisBlock)\n\t\tnet := network.\n\t\t\tNewTestNetworkBuilder().\n\t\t\tWithNodeCount(4).\n\t\t\tWithTimeBasedElectionTrigger(1000 * time.Millisecond).\n\t\t\tWithBlocks(block1).\n\t\t\tBuild(ctx)\n\n\t\tnode0 := net.Nodes[0]\n\t\tnode1 := net.Nodes[1]\n\t\tnode2 := net.Nodes[2]\n\n\t\tnode0.Communication.SetOutgoingWhitelist([]primitives.MemberId{\n\t\t\tnode1.MemberId,\n\t\t\tnode2.MemberId,\n\t\t})\n\n\t\t// the leader (node0) is suggesting block1 to node1 and node2 (not to node3)\n\t\tnet.StartConsensus(ctx)\n\n\t\t// node0, node1 and node2 should reach consensus\n\t\tnet.WaitUntilNodesEventuallyCommitASpecificBlock(ctx, t, 0, block1, node0, node1, node2)\n\t})\n}", "func ValidateBlockObject(schema *tfschema.BlockType, val cty.Value) Diagnostics {\n\tvar diags Diagnostics\n\tif !val.Type().IsObjectType() {\n\t\tdiags = diags.Append(Diagnostic{\n\t\t\tSeverity: Error,\n\t\t\tSummary: \"Invalid block object\",\n\t\t\tDetail: \"An object value is required to represent this block.\",\n\t\t})\n\t\treturn diags\n\t}\n\n\t// Capacity 3 here is so that we have room for a nested block type, an\n\t// index, and a nested attribute name without allocating more. Each loop\n\t// below will mutate this backing array but not the original empty slice.\n\tpath := make(cty.Path, 0, 3)\n\n\tfor name, attrS := range schema.Attributes {\n\t\tpath := path.GetAttr(name)\n\t\tav := val.GetAttr(name)\n\t\tattrDiags := ValidateAttrValue(attrS, av)\n\t\tdiags = diags.Append(attrDiags.UnderPath(path))\n\t}\n\n\tfor name, blockS := range schema.NestedBlockTypes {\n\t\tpath := path.GetAttr(name)\n\t\tav := val.GetAttr(name)\n\n\t\tswitch blockS.Nesting {\n\t\tcase tfschema.NestingSingle:\n\t\t\tif !av.IsNull() {\n\t\t\t\tblockDiags := ValidateBlockObject(&blockS.Content, av)\n\t\t\t\tdiags = diags.Append(blockDiags.UnderPath(path))\n\t\t\t}\n\t\tcase tfschema.NestingList, tfschema.NestingMap:\n\t\t\tfor it := av.ElementIterator(); it.Next(); {\n\t\t\t\tek, ev := it.Element()\n\t\t\t\tpath := path.Index(ek)\n\t\t\t\tblockDiags := ValidateBlockObject(&blockS.Content, ev)\n\t\t\t\tdiags = diags.Append(blockDiags.UnderPath(path))\n\t\t\t}\n\t\tcase tfschema.NestingSet:\n\t\t\t// We handle sets separately because we can't describe a path\n\t\t\t// through a set element (it has no key to use) and so any errors\n\t\t\t// in a set block are indicated at the set itself. Nested blocks\n\t\t\t// backed by sets are fraught with oddities like these, so providers\n\t\t\t// should avoid using them except for historical compatibilty.\n\t\t\tfor it := av.ElementIterator(); it.Next(); {\n\t\t\t\t_, ev := it.Element()\n\t\t\t\tblockDiags := ValidateBlockObject(&blockS.Content, ev)\n\t\t\t\tdiags = diags.Append(blockDiags.UnderPath(path))\n\t\t\t}\n\t\tdefault:\n\t\t\tdiags = diags.Append(Diagnostic{\n\t\t\t\tSeverity: Error,\n\t\t\t\tSummary: \"Unsupported nested block mode\",\n\t\t\t\tDetail: fmt.Sprintf(\"Block type %q has an unsupported nested block mode %#v. This is a bug in the provider; please report it in the provider's own issue tracker.\", name, blockS.Nesting),\n\t\t\t\tPath: path,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn diags\n}", "func TestCheckSerializedHeight(t *testing.T) {\n\n\ttests := []struct {\n\t\tname string\n\t\tblkNth int // block index in blks50.dat\n\t\twantHeight uint64 // Expected height\n\t\terr error // Expected error type\n\t}{\n\t\t{\n\t\t\t\"height 1\",\n\t\t\t2, 1, nil,\n\t\t},\n\t\t{\n\t\t\t\"height 21\",\n\t\t\t22, 21, nil,\n\t\t},\n\t\t{\n\t\t\t\"height 25\",\n\t\t\t26, 25, nil,\n\t\t},\n\t}\n\n\tt.Logf(\"Running %d tests\", len(tests))\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tblock, err := loadNthBlk(test.blkNth)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tcoinbaseTx := block.MsgBlock().Transactions[0]\n\t\t\ttx := massutil.NewTx(coinbaseTx)\n\n\t\t\terr = TstCheckSerializedHeight(tx, test.wantHeight)\n\t\t\tassert.Equal(t, test.err, err)\n\t\t})\n\t}\n}", "func (chain *BlockChainAtomic) ValidateBlockAtIndex(index int) error {\r\n\r\n\tblock, err := chain.GetBlockByIndex(index, true)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\terr = block.validateFields()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tpreviousBlock, err := chain.GetBlockByIndex(index-1, true)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\terr = block.validateBlockWithParent(previousBlock)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (t *Table) ValidPass(cardsPassed []*card.Card) bool {\n\treturn len(cardsPassed) == 3\n}", "func (s *KeeperTestSuite) TestHandleNewValidator() {\n\tctx := s.ctx\n\n\taddrDels := simtestutil.AddTestAddrsIncremental(s.bankKeeper, s.stakingKeeper, ctx, 1, s.stakingKeeper.TokensFromConsensusPower(ctx, 0))\n\tvalAddrs := simtestutil.ConvertAddrsToValAddrs(addrDels)\n\tpks := simtestutil.CreateTestPubKeys(1)\n\taddr, val := valAddrs[0], pks[0]\n\ttstaking := stakingtestutil.NewHelper(s.T(), ctx, s.stakingKeeper)\n\tctx = ctx.WithBlockHeight(s.slashingKeeper.SignedBlocksWindow(ctx) + 1)\n\n\t// Validator created\n\tamt := tstaking.CreateValidatorWithValPower(addr, val, 100, true)\n\n\tstaking.EndBlocker(ctx, s.stakingKeeper)\n\ts.Require().Equal(\n\t\ts.bankKeeper.GetAllBalances(ctx, sdk.AccAddress(addr)),\n\t\tsdk.NewCoins(sdk.NewCoin(s.stakingKeeper.GetParams(ctx).BondDenom, InitTokens.Sub(amt))),\n\t)\n\ts.Require().Equal(amt, s.stakingKeeper.Validator(ctx, addr).GetBondedTokens())\n\n\t// Now a validator, for two blocks\n\ts.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, true)\n\tctx = ctx.WithBlockHeight(s.slashingKeeper.SignedBlocksWindow(ctx) + 2)\n\ts.slashingKeeper.HandleValidatorSignature(ctx, val.Address(), 100, false)\n\n\tinfo, found := s.slashingKeeper.GetValidatorSigningInfo(ctx, sdk.ConsAddress(val.Address()))\n\ts.Require().True(found)\n\ts.Require().Equal(s.slashingKeeper.SignedBlocksWindow(ctx)+1, info.StartHeight)\n\ts.Require().Equal(int64(2), info.IndexOffset)\n\ts.Require().Equal(int64(1), info.MissedBlocksCounter)\n\ts.Require().Equal(time.Unix(0, 0).UTC(), info.JailedUntil)\n\n\t// validator should be bonded still, should not have been jailed or slashed\n\tvalidator, _ := s.stakingKeeper.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(val))\n\ts.Require().Equal(stakingtypes.Bonded, validator.GetStatus())\n\tbondPool := s.stakingKeeper.GetBondedPool(ctx)\n\texpTokens := s.stakingKeeper.TokensFromConsensusPower(ctx, 100)\n\t// adding genesis validator tokens\n\texpTokens = expTokens.Add(s.stakingKeeper.TokensFromConsensusPower(ctx, 1))\n\ts.Require().True(expTokens.Equal(s.bankKeeper.GetBalance(ctx, bondPool.GetAddress(), s.stakingKeeper.BondDenom(ctx)).Amount))\n}", "func TestBlock(t *testing.T) {\n\tet, err := createExplorerTester(\"TestStatistics\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgb := et.cs.GenesisBlock()\n\tgbFetch, height, exists := et.explorer.Block(gb.ID())\n\tif !exists || height != 0 || gbFetch.ID() != gb.ID() {\n\t\tt.Error(\"call to 'Block' inside explorer failed\")\n\t}\n}", "func TestCheckBlockHeaderContext(t *testing.T) {\n\t// Create a test block database.\n\tconst testDbType = \"ffldb\"\n\tparams := chaincfg.RegNetParams()\n\tdb, err := createTestDatabase(t, testDbType, params.Net)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create database: %v\\n\", err)\n\t}\n\n\t// Create a test UTXO database.\n\tutxoDb, teardownUtxoDb, err := createTestUtxoDatabase(t)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create UTXO database: %v\\n\", err)\n\t}\n\tdefer teardownUtxoDb()\n\n\t// Create a new BlockChain instance using the underlying database for\n\t// the simnet network.\n\tutxoBackend := NewLevelDbUtxoBackend(utxoDb)\n\tchain, err := New(context.Background(),\n\t\t&Config{\n\t\t\tDB: db,\n\t\t\tUtxoBackend: utxoBackend,\n\t\t\tChainParams: params,\n\t\t\tTimeSource: NewMedianTime(),\n\t\t\tUtxoCache: NewUtxoCache(&UtxoCacheConfig{\n\t\t\t\tBackend: utxoBackend,\n\t\t\t\tFlushBlockDB: func() error {\n\t\t\t\t\treturn nil\n\t\t\t\t},\n\t\t\t\tMaxSize: 100 * 1024 * 1024, // 100 MiB\n\t\t\t}),\n\t\t})\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create chain instance: %v\\n\", err)\n\t\treturn\n\t}\n\n\terr = chain.checkBlockHeaderContext(&params.GenesisBlock.Header, nil, BFNone)\n\tif err != nil {\n\t\tt.Fatalf(\"genesisblock should pass just by definition: %v\\n\", err)\n\t\treturn\n\t}\n\n\t// Test failing checkBlockHeaderContext when calcNextRequiredDifficulty\n\t// fails.\n\tblock := dcrutil.NewBlock(&badBlock)\n\tnewNode := newBlockNode(&block.MsgBlock().Header, nil)\n\terr = chain.checkBlockHeaderContext(&block.MsgBlock().Header, newNode, BFNone)\n\tif err == nil {\n\t\tt.Fatalf(\"Should fail due to bad diff in newNode\\n\")\n\t\treturn\n\t}\n}", "func verifyStateTransition(pBlock *Block) bool {\n\t// TODO: Checking validity of accounts\n\t// Initialize state\n\tvar modifiedState = pBlock.Parent.RecentState\n\t// Go through the lists of transactions\n\tfor _, v := range pBlock.Transactions {\n\t\t// Create if necessary an account for the sender\n\t\tif _, ok := modifiedState[v.Origin]; !ok {\n\t\t\tsenderAccount := CreateAccount(v.Origin)\n\t\t\tmodifiedState[v.Origin] = &senderAccount\n\t\t}\n\t\tswitch true {\n\t\t// Checking transaction is valid and well formed\n\t\tcase v.Value < 0:\n\t\t\treturn false\n\t\t// Signature of sender does not match owner\n\t\t// TODO: Calculating signature\n\t\t// Referenced UTXO is not in the state\n\t\tcase modifiedState[v.Origin].Balance < v.Value:\n\t\t\treturn false\n\t\t}\n\t\t// Update state\n\t\tmodifiedState[v.Origin].Balance -= v.Value\n\t\t// Check that the recipient of the UTXO exists, if not, create it\n\t\tif _, ok := modifiedState[v.Destination]; ok {\n\t\t\tmodifiedState[v.Destination].Balance += v.Value\n\t\t} else {\n\t\t\ttheAccount := CreateAccount(v.Destination)\n\t\t\tmodifiedState[v.Destination] = &theAccount\n\t\t\tmodifiedState[v.Destination].Balance = v.Value\n\t\t}\n\t}\n\t// Update the state\n\tpBlock.RecentState = modifiedState\n\treturn true\n}", "func (s BlockchainStatus) Valid() error {\n\tswitch s {\n\tcase Created, Preferred, Validating, Syncing:\n\t\treturn nil\n\tdefault:\n\t\treturn errUnknownBlockchainStatus\n\t}\n}", "func TestValidatorSet_VerifyCommit_All(t *testing.T) {\n\tvar (\n\t\tprivKey = ed25519.GenPrivKey()\n\t\tpubKey = privKey.PubKey()\n\t\tv1 = NewValidator(pubKey, 1000)\n\t\tvset = NewValidatorSet([]*Validator{v1})\n\n\t\tchainID = \"Lalande21185\"\n\t)\n\n\tvote := examplePrecommit()\n\tvote.ValidatorAddress = pubKey.Address()\n\tv := vote.ToProto()\n\tsig, err := privKey.Sign(VoteSignBytes(chainID, v))\n\trequire.NoError(t, err)\n\tvote.Signature = sig\n\n\tcommit := NewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{vote.CommitSig()})\n\n\tvote2 := *vote\n\tsig2, err := privKey.Sign(VoteSignBytes(\"EpsilonEridani\", v))\n\trequire.NoError(t, err)\n\tvote2.Signature = sig2\n\n\ttestCases := []struct {\n\t\tdescription string\n\t\tchainID string\n\t\tblockID BlockID\n\t\theight int64\n\t\tcommit *Commit\n\t\texpErr bool\n\t}{\n\t\t{\"good\", chainID, vote.BlockID, vote.Height, commit, false},\n\n\t\t{\"wrong signature (#0)\", \"EpsilonEridani\", vote.BlockID, vote.Height, commit, true},\n\t\t{\"wrong block ID\", chainID, makeBlockIDRandom(), vote.Height, commit, true},\n\t\t{\"wrong height\", chainID, vote.BlockID, vote.Height - 1, commit, true},\n\n\t\t{\"wrong set size: 1 vs 0\", chainID, vote.BlockID, vote.Height,\n\t\t\tNewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{}), true},\n\n\t\t{\"wrong set size: 1 vs 2\", chainID, vote.BlockID, vote.Height,\n\t\t\tNewCommit(vote.Height, vote.Round, vote.BlockID,\n\t\t\t\t[]CommitSig{vote.CommitSig(), {BlockIDFlag: BlockIDFlagAbsent}}), true},\n\n\t\t{\"insufficient voting power: got 0, needed more than 666\", chainID, vote.BlockID, vote.Height,\n\t\t\tNewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{{BlockIDFlag: BlockIDFlagAbsent}}), true},\n\n\t\t{\"wrong signature (#0)\", chainID, vote.BlockID, vote.Height,\n\t\t\tNewCommit(vote.Height, vote.Round, vote.BlockID, []CommitSig{vote2.CommitSig()}), true},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tt.Run(tc.description, func(t *testing.T) {\n\t\t\terr := vset.VerifyCommit(tc.chainID, tc.blockID, tc.height, tc.commit)\n\t\t\tif tc.expErr {\n\t\t\t\tif assert.Error(t, err, \"VerifyCommit\") {\n\t\t\t\t\tassert.Contains(t, err.Error(), tc.description, \"VerifyCommit\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err, \"VerifyCommit\")\n\t\t\t}\n\n\t\t\terr = vset.VerifyCommitLight(tc.chainID, tc.blockID, tc.height, tc.commit)\n\t\t\tif tc.expErr {\n\t\t\t\tif assert.Error(t, err, \"VerifyCommitLight\") {\n\t\t\t\t\tassert.Contains(t, err.Error(), tc.description, \"VerifyCommitLight\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err, \"VerifyCommitLight\")\n\t\t\t}\n\t\t})\n\t}\n}", "func (evpool *Pool) verify(evidence types.Evidence) error {\n\tvar (\n\t\tstate = evpool.State()\n\t\theight = state.LastBlockHeight\n\t\tevidenceParams = state.ConsensusParams.Evidence\n\t\tageNumBlocks = height - evidence.Height()\n\t)\n\n\t// verify the time of the evidence\n\tblockMeta := evpool.blockStore.LoadBlockMeta(evidence.Height())\n\tif blockMeta == nil {\n\t\treturn fmt.Errorf(\"don't have header #%d\", evidence.Height())\n\t}\n\tevTime := blockMeta.Header.Time\n\tif evidence.Time() != evTime {\n\t\treturn fmt.Errorf(\"evidence has a different time to the block it is associated with (%v != %v)\",\n\t\t\tevidence.Time(), evTime)\n\t}\n\tageDuration := state.LastBlockTime.Sub(evTime)\n\n\t// check that the evidence hasn't expired\n\tif ageDuration > evidenceParams.MaxAgeDuration && ageNumBlocks > evidenceParams.MaxAgeNumBlocks {\n\t\treturn fmt.Errorf(\n\t\t\t\"evidence from height %d (created at: %v) is too old; min height is %d and evidence can not be older than %v\",\n\t\t\tevidence.Height(),\n\t\t\tevTime,\n\t\t\theight-evidenceParams.MaxAgeNumBlocks,\n\t\t\tstate.LastBlockTime.Add(evidenceParams.MaxAgeDuration),\n\t\t)\n\t}\n\n\t// apply the evidence-specific verification logic\n\tswitch ev := evidence.(type) {\n\tcase *types.DuplicateVoteEvidence:\n\t\tvalSet, err := evpool.stateDB.LoadValidators(evidence.Height())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn VerifyDuplicateVote(ev, state.ChainID, valSet)\n\n\tcase *types.LightClientAttackEvidence:\n\t\tcommonHeader, err := getSignedHeader(evpool.blockStore, evidence.Height())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcommonVals, err := evpool.stateDB.LoadValidators(evidence.Height())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttrustedHeader := commonHeader\n\t\t// in the case of lunatic the trusted header is different to the common header\n\t\tif evidence.Height() != ev.ConflictingBlock.Height {\n\t\t\ttrustedHeader, err = getSignedHeader(evpool.blockStore, ev.ConflictingBlock.Height)\n\t\t\tif err != nil {\n\t\t\t\t// FIXME: This multi step process is a bit unergonomic. We may want to consider a more efficient process\n\t\t\t\t// that doesn't require as much io and is atomic.\n\n\t\t\t\t// If the node doesn't have a block at the height of the conflicting block, then this could be\n\t\t\t\t// a forward lunatic attack. Thus the node must get the latest height it has\n\t\t\t\tlatestHeight := evpool.blockStore.Height()\n\t\t\t\ttrustedHeader, err = getSignedHeader(evpool.blockStore, latestHeight)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif trustedHeader.Time.Before(ev.ConflictingBlock.Time) {\n\t\t\t\t\treturn fmt.Errorf(\"latest block time (%v) is before conflicting block time (%v)\",\n\t\t\t\t\t\ttrustedHeader.Time, ev.ConflictingBlock.Time,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\terr = VerifyLightClientAttack(ev, commonHeader, trustedHeader, commonVals, state.LastBlockTime,\n\t\t\tstate.ConsensusParams.Evidence.MaxAgeDuration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognized evidence type: %T\", evidence)\n\t}\n\n}", "func CheckValid(data Dstream) bool {\n\n\tdata.Reset()\n\tnames := data.Names()\n\n\tfor c := 0; data.Next(); c++ {\n\t\tn0 := ilen(data.GetPos(0))\n\t\tfor j := 1; j < len(names); j++ {\n\t\t\tn1 := ilen(data.GetPos(j))\n\t\t\tif n1 != n0 {\n\t\t\t\tmsg := fmt.Sprintf(\"Length mismatch in chunk %d: len(%s) = %d, len(%s) = %d\\n\",\n\t\t\t\t\tc, names[0], n0, names[j], n1)\n\t\t\t\t_, _ = io.WriteString(os.Stderr, msg)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\tdata.Reset()\n\n\treturn true\n}", "func (pow *ProofOfWork) Validate() bool {\n\tvar hashInt big.Int\n\n\tdata := pow.prepareData(pow.block.Nonce)\n\thash := sha256.Sum256(data)\n\thashInt.SetBytes(hash[:])\n\n\tisValid := hashInt.Cmp(pow.target) == -1\n\n\treturn isValid\n}", "func CheckNextBlock(prev, next Block) bool {\n\t// first check the work on the new block. 33 bits needed.\n\tif !CheckWork(next, 33) {\n\t\tlog.Printf(\"not enought work! \")\n\t\treturn false\n\t}\n\n\t// first, check that next points back to prev\n\tif prev.Hash() != next.PrevHash {\n\t\tlog.Printf(\"hashes don't chain up! \")\n\t\treturn false\n\t}\n\n\t// probably enough checks for now?\n\n\treturn true\n}", "func TestCheckBlockScripts(t *testing.T) {\n\tt.Skip() // TODO: Reactivate this test once we have blocks from testnet.\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\ttestBlockNum := 277647\n\tblockDataFile := fmt.Sprintf(\"%d.dat\", testBlockNum)\n\tblocks, err := LoadBlocks(filepath.Join(\"testdata/\", blockDataFile))\n\tif err != nil {\n\t\tt.Errorf(\"Error loading file: %v\\n\", err)\n\t\treturn\n\t}\n\tif len(blocks) > 1 {\n\t\tt.Errorf(\"The test block file must only have one block in it\")\n\t\treturn\n\t}\n\tif len(blocks) == 0 {\n\t\tt.Errorf(\"The test block file may not be empty\")\n\t\treturn\n\t}\n\n\tstoreDataFile := fmt.Sprintf(\"%d.utxostore\", testBlockNum)\n\tutxoSet, err := loadUTXOSet(storeDataFile)\n\tif err != nil {\n\t\tt.Errorf(\"Error loading txstore: %v\\n\", err)\n\t\treturn\n\t}\n\n\tnode := &blockNode{\n\t\thash: blocks[0].Hash(),\n\t}\n\n\tscriptFlags := txscript.ScriptNoFlags\n\terr = checkBlockScripts(node, utxoSet, blocks[0].Transactions(), scriptFlags, nil)\n\tif err != nil {\n\t\tt.Errorf(\"Transaction script validation failed: %v\\n\", err)\n\t\treturn\n\t}\n}" ]
[ "0.7005355", "0.67256606", "0.6663936", "0.6658995", "0.65298724", "0.65101755", "0.6502856", "0.6467316", "0.64659816", "0.646173", "0.6443889", "0.6409351", "0.63813853", "0.63750744", "0.63302433", "0.62938285", "0.62859845", "0.62698686", "0.6257908", "0.6239302", "0.6231104", "0.6227707", "0.6139429", "0.61182946", "0.6087244", "0.6056148", "0.6024047", "0.599745", "0.5965339", "0.5940803", "0.592769", "0.59068453", "0.58990395", "0.5895075", "0.5855602", "0.58475685", "0.58166504", "0.5752116", "0.5720848", "0.57155395", "0.5696342", "0.56791884", "0.5671289", "0.5653694", "0.5653455", "0.5651189", "0.5643675", "0.564213", "0.56328934", "0.5615795", "0.5584222", "0.55723494", "0.5558445", "0.5544313", "0.5520222", "0.5509017", "0.550811", "0.54776627", "0.54713935", "0.54663265", "0.5465175", "0.54635024", "0.54554695", "0.54554695", "0.5447822", "0.5437511", "0.54360527", "0.54256487", "0.54177344", "0.5416081", "0.541442", "0.5396079", "0.53938115", "0.53885436", "0.5386491", "0.5376738", "0.5375435", "0.5365465", "0.5353648", "0.5351531", "0.53303343", "0.5328338", "0.53218234", "0.53196895", "0.531356", "0.53103036", "0.530682", "0.52909666", "0.5284984", "0.5279838", "0.5269828", "0.52653974", "0.5265187", "0.5258574", "0.525645", "0.5247062", "0.5242862", "0.5242485", "0.5237512", "0.5232704" ]
0.691765
1
Replace the current chain by adding a new block
func replaceChain(newBlock Block) bool { // make this thread safe blockchainwritelock.Lock() defer blockchainwritelock.Unlock() // Is the block valid and if so then append it to the chain if isBlockValid(newBlock, Blockchain[len(Blockchain)-1]) { Blockchain = append(Blockchain, newBlock) BlockchainLength = len(Blockchain) var registration string // Update vehicle lookups log.Printf("INFO: replaceChain(): Adding vehicle to vehicle and blocklookup map.") lastregindex := len(newBlock.Event.PerformedOnVehicle.VehicleRegistration) registration = newBlock.Event.PerformedOnVehicle.VehicleRegistration[lastregindex-1] registration = strings.ToUpper(registration) registration = strings.Replace(registration, " ", "", -1) blocklist := vehicleMap[registration] log.Printf("INFO: replaceChain(): REG %s, BLOCKLIST SIZE %s", registration, strconv.Itoa(len(blocklist))) log.Printf("INFO: replaceChain(): Captured registration: %s with %s previous entries", registration, strconv.Itoa(len(blocklist))) if (len(blocklist)) > 0 { log.Printf("INFO: replaceChain(): Vehicle been added before. Appending new block id with value %s", strconv.Itoa(newBlock.Index)) vehicleMap[registration] = append(blocklist, newBlock.Index) } else { newBlockSlice := []int{newBlock.Index} log.Printf("INFO: replaceChain(): created new list of blocks for registration %s, size is %s", registration, strconv.Itoa(len(newBlockSlice))) // vehicleMap not initialised so set it up if len(vehicleMap) < 1 { log.Printf("INFO: replaceChain(): vehicleMap is not initialised, size is %s", strconv.Itoa(len(vehicleMap))) vehicleMap = make(map[string][]int) } // Add the new vehicle to the map log.Printf("INFO: replaceChain(): Adding vehicle %s to new vehicleMap", registration) vehicleMap[registration] = newBlockSlice } log.Printf("INFO: replaceChain(): Added vehicle reg %s to block lookup table, blockid %s", registration, strconv.Itoa(newBlock.Index)) log.Printf("INFO: replaceChain(): Appended new block, writing to disk with ID %s", strconv.Itoa(BlockchainLength)) err := interfaceToFile("./saved_chains/md5589_blockchain_"+strconv.Itoa(BlockchainLength), Blockchain) if err != nil { log.Printf("ERROR: Unable to write blockchain to disk: %s", strconv.Itoa(BlockchainLength)) } return true } return false }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Blockchain) addBlock(block Block) {\n mutex.Lock()\n this.chain = append(this.chain, block)\n mutex.Unlock()\n // reset pending Transactions\n this.pendingTransactions = nil\n}", "func AddToMyChain(data BlockData) error {\r\n\t// Create the new block (get parent, create block)\r\n\tpreviousBlock, err := myChain.GetLastBlock(true)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tblock, err := generateBlock(previousBlock, data)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\terr = myChain.AppendBlock(block)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tlog.Printf(\"a block has been added...\")\r\n\treturn nil\r\n}", "func replaceChain(newChain []Block) {\n\tif len(newChain) > len(BlockChain) {\n\t\tBlockChain = newChain\n\t}\n}", "func (s *BlockchainService) replaceChain(newChain []*Block) {\n\tif len(newChain) > len(s.chain) {\n\t\ts.chain = newChain\n\t}\n}", "func (gossiper *Gossiper) addBlockToBlockchain() {\n\tfor block := range gossiper.ToAddToBlockchain {\n\t\tnewHash := block.Hash()\n\t\tnewHashHex := hex.EncodeToString(newHash[:])\n\t\tprevHashHex := hex.EncodeToString(block.PrevHash[:])\n\t\t//CHECKING IF WE ARE ON LONGEST CHAIN\n\t\tif prevHashHex == gossiper.CurrentBlock.GetCurrentHash() {\n\t\t\tstr := gossiper.printChain(block)\n\t\t\tgossiper.ToPrint <- str\n\t\t}\n\t\tgossiper.Blockchain.Store(newHashHex, block)\n\n\t\tif gossiper.CurrentBlock.GetCurrentHash() == prevHashHex {\n\t\t\tgossiper.CurrentBlock.IncrementDepth()\n\t\t\tgossiper.CurrentBlock.SetCurrentHash(newHashHex)\n\t\t\tfor _, transaction := range block.Transactions {\n\t\t\t\tgossiper.NameToMetaHash.Store(transaction.File.Name, transaction.File.MetafileHash)\n\t\t\t}\n\t\t\tgossiper.BlockMined <- Signal{}\n\t\t\tgossiper.mineBlock(newHash)\n\t\t} else {\n\t\t\tnewDepth := gossiper.computeDepth(newHashHex)\n\t\t\tif newDepth > gossiper.CurrentBlock.GetDepth() {\n\t\t\t\tgossiper.ToPrint <- \"FORK-LONGER rewind \" + \" blocks\"\n\t\t\t\tgossiper.switchBranch(prevHashHex)\n\t\t\t\tgossiper.CurrentBlock.SetDepth(newDepth)\n\t\t\t} else {\n\t\t\t\tgossiper.ToPrint <- \"FORK-SHORTER \" + newHashHex\n\t\t\t}\n\t\t}\n\t}\n}", "func (bc *Blockchain) AddBlock() {\n newBlock := new(Block)\n newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork()\n //newBlock.Timestamp = time.Now().Unix()\n newBlock.Index = len(bc.Chain)\n newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1])\n newBlock.Difficulty = bc.AdjustDifficulty()\n\n bc.BlockMutex.Lock()\n bc.Chain = append(bc.Chain, *newBlock)\n bc.BlockMutex.Unlock()\n}", "func (c *Chain) Append(b Block) *Chain {\n\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\tc.Chain = append(c.Chain, b)\n\tc.Size = unsafe.Sizeof(c)\n\tc.LengthElements = len(c.Chain)\n\tl := c.LengthElements\n\tif l != 1 {\n\t\tc.Chain[l-2].NextBlock = &c.Chain[l-1]\n\t\tc.Chain[l-1].PrevBlock = &c.Chain[l-2]\n\t\tc.Chain[l-1].NextBlock = nil\n\t\t// update normalised time\n\t\tc.Chain[l-1].NormalizedTime = c.Chain[l-2].NormalizedTime + 1\n\t}\n\treturn c\n\n}", "func (honest *Honest) replaceChain(chain Blockchain) int {\n\t\n\t*honest.bc = chain\n\toutLog.Printf(\"Received chain length:%d\", len(chain.Blocks))\n\toutLog.Printf(\"Appended chain length:%d\", len(honest.bc.Blocks))\t\n\treturn chain.Blocks[len(chain.Blocks) - 1].Data.Iteration\n}", "func (c *Chain) PushBlock(newBlock *core.Block) {\n\tmaybeWarnMultipleProduction(c.fdb, b.Num)\n\n\t// forkdb.PushBlock will set the head pointing to longest chain in forkdb.\n\terr := c.fdb.AppendBlock(newBlock)\n\tif err != nil {\n\t\tfmt.Errorf(\"invalid block, ignoring...\")\n\t\treturn\n\t}\n\n\tif newBlock.PrevBlockId == c.Head().ID {\n\t\tc.startUndoSession()\n\t\tok := c.ApplyBlock(newBlock)\n\t\tif ok {\n\t\t\t// if everything goes right, then gpo's head block will be updated to new head\n\t\t\t// and all cached values will be reloaded\n\t\t\t// Chain's push undo session should leave the operation logs for future popblock,\n\t\t\t// only block becomes irriverible, then commit the block/session/revision\n\t\t\t// each block has exactly one session/revision\n\t\t\t// c.setHead(newBlock) - NOT NECESSARY, since head is reloaded from gpo in pushundosession\n\t\t\tc.pushUndoSession()\n\t\t} else {\n\t\t\t// undo all operations on statusdb during ApplyBlock()\n\t\t\t// also reload all cached values during undo\n\t\t\tc.undo()\n\t\t\t// usally undo operation hase nothing to do with forkdb\n\t\t\t// BUT here, the block is invalid, so we need to remove it\n\t\t\t// before remove block, the system will unpack the tx and store them in pending_tx_list\n\t\t\tc.fdb.RemoveBlock(newBlock)\n\t\t\t// c.setHead(previous head) -- NOT NECCESSARY\n\t\t}\n\t} else {\n\t\tif newBlock.Num > c.Head().Num {\n\t\t\t// if the new block is not build off from current chain's head block\n\t\t\t// and also has bigger number, means it just created a new longest branch\n\t\t\t// so we need to switch to the new longest branch\n\t\t\tc.switchBranch(newBlock)\n\t\t}\n\t}\n}", "func addToBlockChain(block Block) {\n\tmutex.Lock()\n\tblockChain[block.Hash] = block\n\tmutex.Unlock()\n\tsetParentsNewChild(block)\n\tupdateLeafBlocks(block)\n\thBlock := block.HashBlock\n\ttxid := hBlock.TxID\n\t// a Commit transaction\n\tif txid > 0 {\n\t\tmutex.Lock()\n\t\ttx := transactions[txid]\n\t\tmutex.Unlock()\n\t\tputSet := tx.PutSet\n\t\tfor k := range putSet {\n\t\t\tmutex.Lock()\n\t\t\tkeyValueStore[k] = putSet[k]\n\t\t\tmutex.Unlock()\n\t\t}\n\t\ttx.IsCommitted = true\n\t\ttx.CommitHash = block.Hash\n\t\thashList := tx.AllHashes\n\t\thashList = append(hashList, block.Hash)\n\t\ttx.AllHashes = hashList\n\t\tmutex.Lock()\n\t\ttransactions[txid] = tx\n\t\tmutex.Unlock()\n\t}\n}", "func AddBlock(b Block) error {\n\t// fmt.Println(\"******TODO: IMPLEMENT AddBlock!******\")\n\tspew.Dump(Blockchain)\n\t// Fill me in, brave wizard.\n\tprevBlock := Blockchain[len(Blockchain)-1]\n\t// fmt.Println(prevBlock)\n\t// fmt.Println(b)\n\tif bytes.Compare(b.PrevHash, prevBlock.Hash) != 0 {\n\t\t// return errors.New(\"Error block\")\n\t\treturn fmt.Errorf(\"New Block should have Hash: %x, but has Hash: %x\",\n\t\t\tprevBlock.Hash, b.PrevHash)\n\t}\n\tBlockchain = append(Blockchain, b)\n\treturn nil\n}", "func (s *BlockchainService) Add(payload int) (Block, error) {\n\ts.mutex.Lock()\n\n\tnewBlock := s.generateBlock(s.chain[len(s.chain)-1], payload)\n\n\tif isBlockValid(&newBlock, s.chain[len(s.chain)-1]) {\n\t\tnewBlockchain := append(s.chain, &newBlock)\n\t\ts.replaceChain(newBlockchain)\n\t\tspew.Dump(s.chain)\n\n\t\ts.mutex.Unlock()\n\n\t\treturn newBlock, nil\n\t}\n\n\ts.mutex.Unlock()\n\n\treturn Block{}, errors.New(\"Failed to add new block for payload\")\n}", "func (bc *Blockchain) AddRemoteBlocks() {\n for true {\n // listen for a block from the node goroutine\n newBlock := <-bc.AddBlockChannel\n bc.BlockMutex.Lock()\n bc.Chain = append(bc.Chain, newBlock)\n bc.BlockMutex.Unlock()\n fmt.Println(\"Another miner found block \" + strconv.Itoa(len(bc.Chain)))\n if !bc.ValidateChain() {\n // the new block is invalid, delete it\n bc.BlockMutex.Lock()\n bc.Chain = bc.Chain[:len(bc.Chain) - 1]\n bc.BlockMutex.Unlock()\n // let the node package know that the block was rejected\n bc.BlockValidateChannel <- false\n } else {\n bc.BlockValidateChannel <- true\n }\n }\n}", "func (bc *Blockchain) AddBlock(block Block) {\n\t*bc = append(*bc, block)\n}", "func (b *Blockchain) AddBlock(p *msg.Packet) error {\n\tb.chainLock.Lock()\n\tdefer b.chainLock.Unlock()\n\t// TODO: change the expected target\n\tdb := b.DB\n\t_, err := db.Get(p.Hash, nil)\n\tif err == leveldb.ErrNotFound && p.CurrentBlockNumber > b.Tip.CurrentBlockNumber {\n\t\traw, _ := proto.Marshal(p)\n\t\terr := db.Put(\n\t\t\tbytes.Join([][]byte{\n\t\t\t\t[]byte(\"b\"), p.Hash}, []byte{}), raw, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = db.Put([]byte(\"l\"), p.Hash, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tTransaction.OpenUTXO()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tTransaction.PutUTXO(p.GetBlockData().Coinbase, p.Addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trawPrev, err := b.Relation.Get(p.Prev, nil)\n\t\tif err == leveldb.ErrNotFound {\n\t\t\terr = nil\n\t\t\trawPrev = []byte{}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trawPrev, err = Utils.AppendMarshalSha3(rawPrev, p.Hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.Relation.Put(p.Prev, rawPrev, nil)\n\n\t\tb.Tip = p\n\t\treturn nil\n\t}\n\treturn Consts.ErrOldBlock\n}", "func (bc *Blockchain) AddBlock(_data string) {\n\n\t// prevBlock := bc.blocks[len(bc.blocks)-1]\n\t// newBlock := NewBlock(_data, prevBlock.Hash)\n\t// bc.blocks = append(bc.blocks, newBlock)\n\n\tvar lastHash []byte\n\n\t// View is read-only type of boltDb transaction\n\terr = bc.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\t\tlastHash = b.Get([]byte(\"l\"))\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tnewBlock := NewBlock(_data, lastHash)\n\n\terr = bc.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\t\terr := b.Put(newBlock.Hash, newBlock.Serialize())\n\t\terr = b.Put([]byte(\"l\"), newBlock.Hash)\n\t\tbc.tip = newBlock.Hash\n\n\t\treturn nil\n\t})\n}", "func main() {\n\tvar chainHead *Block\n\tgenesis := BlockData{Transactions: []string{\"S2E\", \"S2Z\"}}\n\t//fmt.Printf(\"helllooo\")\n\t//fmt.Println(genesis)\n\tchainHead = InsertBlock(genesis, chainHead)\n\t//var x string=CalculateHash(chainHead)\n\t//fmt.Printf(\"%x\\n\", x)\n\n\tsecondBlock := BlockData{Transactions: []string{\"E2Alice\", \"E2Bob\", \"S2John\"}}\n\tchainHead = InsertBlock(secondBlock, chainHead)\n\n\tListBlocks(chainHead)\n\n\t//ChangeBlock(\"S2E\", \"S2Trudy\", chainHead)\n\n\tListBlocks(chainHead)\n\n\tVerifyChain(chainHead)\n\n}", "func (bc *BlockChain) insert(block *types.Block) {\n\t// If the block is on a side chain or an unknown one, force other heads onto it too\n\tupdateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()\n\n\t// Add the block to the canonical chain number scheme and mark as the head\n\trawdb.WriteCanonicalHash(bc.db, block.Hash(), block.NumberU64())\n\trawdb.WriteHeadBlockHash(bc.db, block.Hash())\n\n\tbc.currentBlock.Store(block)\n\n\t// If the block is better than our head or is on a different chain, force update heads\n\tif updateHeads {\n\t\tbc.hc.SetCurrentHeader(block.Header())\n\t\trawdb.WriteHeadFastBlockHash(bc.db, block.Hash())\n\t}\n}", "func (c *Crawler) newBlock(block *wire.MsgBlock, hash *chainhash.Hash) {\t\n\tc.height += 1\n\tc.blockQueue.PushBack(*hash)\n\n\tif c.blockQueue.Len() > BlockQueueSize {\n\t\tc.blockQueue.PopFront()\n\t}\n}", "func (b *Block) Append(block *Block) {\n\tb.subelements = append(b.subelements, block)\n\tb.wire = []byte{}\n}", "func (s *service) ReplaceChain(newChain *Blockchain) error {\n\tif newChain == nil {\n\t\tlog.Printf(\"New chain is nil\")\n\t\treturn ErrInvalidChain\n\t}\n\tif uint32(len(newChain.Chain)) <= s.listing.GetBlockCount() {\n\t\treturn ErrShorterChain\n\t}\n\tvChain := toValidatingChain(newChain)\n\tif !s.validating.IsValidChain(vChain) {\n\t\treturn ErrInvalidChain\n\t}\n\tif valid, err := s.validating.ContainsValidTransactions(vChain); !valid || err != nil {\n\t\tlog.Printf(\"MiningService#ReplaceChain: Failed to replace chain %v\", err)\n\t\treturn ErrInvalidTransactions\n\t}\n\n\treturn s.blockchain.ReplaceChain(newChain)\n}", "func (c *Chain) Append(block *Block) int {\n\tc.Blocks = append(c.Blocks, *block)\n\tc.LatestHash = block.Hash\n\treturn len(c.Blocks)\n}", "func addBlockToBlockchain(t *testing.T, bc *Blockchain) (coin.Block, coin.UxOut) {\n\t// Split the genesis block into two transactions\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 1)\n\tux := bc.GetUnspent().Array()[0]\n\tassert.Equal(t, ux.Body.Address, genAddress)\n\tpub := cipher.PubKeyFromSecKey(genSecret)\n\tassert.Equal(t, genAddress, cipher.AddressFromPubKey(pub))\n\tsig := cipher.SignHash(ux.Hash(), genSecret)\n\tassert.Nil(t, cipher.ChkSig(ux.Body.Address, ux.Hash(), sig))\n\n\ttx, sec := makeTransactionForChainWithHoursFee(t, bc, ux, genSecret, 0, 0)\n\tb, err := bc.NewBlockFromTransactions(coin.Transactions{tx}, _incTime)\n\tassert.Nil(t, err)\n\tassertExecuteBlock(t, bc, b, tx)\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 2)\n\n\t// Spend one of them\n\t// The other will have hours now\n\tux = coin.UxOut{}\n\tfor _, u := range bc.GetUnspent().Pool {\n\t\tif u.Body.Address != genAddress {\n\t\t\tux = u\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.NotEqual(t, ux.Body.Address, cipher.Address{})\n\tassert.NotEqual(t, ux.Body.Address, genAddress)\n\tpub = cipher.PubKeyFromSecKey(sec)\n\taddr := cipher.AddressFromPubKey(pub)\n\tassert.Equal(t, ux.Body.Address, addr)\n\ttx, _ = makeTransactionForChainWithHoursFee(t, bc, ux, sec, 0, 0)\n\tb, err = bc.NewBlockFromTransactions(coin.Transactions{tx},\n\t\tbc.Time()+_incTime)\n\tassert.Nil(t, err)\n\tassertExecuteBlock(t, bc, b, tx)\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 2)\n\n\t// Check that the output in the 2nd block is owned by genesis,\n\t// and has coin hours\n\tfor _, u := range bc.GetUnspent().Pool {\n\t\tif u.Body.Address == genAddress {\n\t\t\tux = u\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Equal(t, ux.Body.Address, genAddress)\n\tassert.Equal(t, ux.Head.BkSeq, uint64(1))\n\tassert.True(t, ux.CoinHours(bc.Time()) > 0)\n\n\treturn b, ux\n}", "func (bc *Blockchain) replaceBlocks(blocks []*block.Block) {\n\tbc.blocks = blocks\n}", "func setParentsNewChild(block Block) {\n\tmutex.Lock()\n\tparentBlock, ok := blockChain[block.HashBlock.ParentHash]\n\tmutex.Unlock()\n\tif !ok {\n\t}\n\tchildren := parentBlock.ChildrenHashes\n\tchildren = append(children, block.Hash)\n\tparentBlock.ChildrenHashes = children\n\tmutex.Lock()\n\tblockChain[parentBlock.Hash] = parentBlock\n\tmutex.Unlock()\n}", "func (b *BlockChain) MineBlock(txns []*Transaction) {\n\t// construct new block and prev hash will be current tip of db\n\tblock := NewBlock(txns, b.tip)\n\n\terr := b.db.Update(func(tx *bolt.Tx) error {\n\t\tbckt := tx.Bucket([]byte(blocksBucket))\n\t\tif err := bckt.Put(block.Hash, block.Serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := bckt.Put([]byte(\"l\"), block.Hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.tip = block.Hash\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"AddBlock :\", err)\n\t}\n}", "func (bc *Blockchain) AddBlock(b Block) error {\n\tif bc.chain == nil {\n\t\tbc.chain = []Block{}\n\t}\n\n\terr := checkNewBlock(b, bc.LatestBlock())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbc.chain = append(bc.chain, b)\n\treturn nil\n}", "func (c *Cache) addBlock(blk *cacheBlock) *cacheBlock {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tif cblk := c.getBlock(blk.offset, true); cblk != nil {\n\t\treturn cblk\n\t}\n\n\tc.blocks[blk.offset] = blk\n\tblk.lru = c.lru.PushFront(blk)\n\tc.evictOld()\n\n\treturn blk\n}", "func (chain *BlockChain) AddBlock(txs []*Transaction) {\n\tvar lastHash []byte\n\n\t// get previous hash via database\n\terr := chain.Database.View(func(txn *badger.Txn) error {\n\t\titem, err := txn.Get([]byte(\"lasthash\"))\n\t\tHandle(err)\n\n\t\t// set lasthash as the value returned from db\n\t\tlastHash, err = item.Value()\n\n\t\treturn err\n\t})\n\n\t// create block with data and lasthash\n\tnewBlock := CreateBlock(txs, lastHash)\n\n\t// save new block to database\n\terr = chain.Database.Update(func(txn *badger.Txn) error {\n\t\t// save serialize block with hash as a key --> to disk\n\t\terr := txn.Set(newBlock.Hash, newBlock.Serialize())\n\t\tHandle(err)\n\n\t\t// save hash to database with lasthash key --> to disk\n\t\terr = txn.Set([]byte(\"lasthash\"), newBlock.Hash)\n\n\t\t// set chain lasthash in memory with hash\n\t\tchain.LastHash = newBlock.Hash\n\n\t\treturn err\n\t})\n\n\tHandle(err)\n\n\t// // get previous block\n\t// prevBlock := chain.Blocks[len(chain.Blocks)-1]\n\n\t// // get previous hash from previous chain\n\t// newBlock := CreateBlock(data, prevBlock.Hash)\n\n\t// chain.Blocks = append(chain.Blocks, newBlock)\n}", "func (bc *Blockchain) AddBlock(data string) {\n\n\tpreviousBlock := bc.blocks[len(bc.blocks)-1]\n\n\tnewBlock := NewBlock(data, previousBlock.Hash)\n\n\tbc.blocks = append(bc.blocks, newBlock)\n}", "func (ob *Observer) updateBlock(curHeight, nextHeight int64, curBlockHash string) error {\n\tblock, err := ob.deps.Recorder.Block(nextHeight)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[Observer.updateBlock]: failed to get block info, height=%d\", nextHeight)\n\t}\n\n\tif curHeight != 0 && block.ParentBlockHash != curBlockHash {\n\t\tif err := ob.DeleteBlock(curHeight); err != nil {\n\t\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to delete a forked block\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := ob.RecordBlockAndTxs(block); err != nil {\n\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to save and process block\")\n\t}\n\n\treturn nil\n}", "func (set *unconfirmedBlocks) Insert(index Uint64, hash bgmcommon.Hash) {\n\t// If a new block was mined locally, shift out any old enough blocks\n\tset.Shift(index)\n\n\t// Create the new item as its own ring\n\titem := ring.New(1)\n\titemPtr.Value = &unconfirmedBlock{\n\t\tindex: index,\n\t\thash: hash,\n\t}\n\t// Set as the initial ring or append to the end\n\tset.lock.Lock()\n\tdefer set.lock.Unlock()\n\n\tif set.blocks == nil {\n\t\tset.blocks = item\n\t} else {\n\t\tset.blocks.Move(-1).Link(item)\n\t}\n\t// Display a bgmlogs for the user to notify of a new mined block unconfirmed\n\tbgmlogs.Info(\"🔨 mined potential block\", \"number\", index, \"hash\", hash)\n}", "func (self *BlockChain) Mine() {\n\t//Get the last transactions proof\n\tprintln(\"Starting to mine...\")\n\tlast := self.LastBlock()\n\tlastProof := last.Proof\n\n\t//Work out the proof\n\tfmt.Printf(\"Last proof = %d \\n\", lastProof)\n\tnewProof := self.ProofOfWork(lastProof)\n\tself.NewTransaction(\"0\", \"dest\", 1)\n\n\t//Add to blockchain with Proof + HASH\n\t//TODO get hash of previous\n\tfmt.Printf(\"new proof = %d \\n\", newProof)\n\tself.NewBlock(newProof, \"xxx\")\n\n}", "func (c *Chain) GiveTxBackFromBlock() {\n\n}", "func testAddBlockVerbose(blockHash, prevHash *chainhash.Hash, confirmations int64, height uint32) *chainhash.Hash {\n\ttestChainMtx.Lock()\n\tdefer testChainMtx.Unlock()\n\tif blockHash == nil {\n\t\tblockHash = randomHash()\n\t}\n\tif height >= testBestBlock.height {\n\t\ttestBestBlock = testBlock{\n\t\t\thash: *blockHash,\n\t\t\theight: height,\n\t\t}\n\t}\n\tif prevHash == nil {\n\t\tif height == testBestBlock.height+1 {\n\t\t\tprevHash = &testBestBlock.hash\n\t\t} else {\n\t\t\tprevHash = &zeroHash\n\t\t}\n\t}\n\ttestChain.blocks[*blockHash] = testBlockVerbose(blockHash, prevHash, confirmations, int64(height))\n\treturn blockHash\n}", "func (cs *Service) AddBlock(block *Block) {\n\tcs.BlockPool <- block\n}", "func addFork(blockchain *BlockChain, block block1.Block, blockHeight int32) bool {\n\tblockList := blockchain.Chain[blockHeight]\n\n\tisBlockCorrect := true\n\tfor i := range blockList {\n\t\tif blockList[i].Header.Hash == block.Header.Hash {\n\t\t\tisBlockCorrect = false\n\t\t\tbreak\n\t\t}\n\t}\n\tif isBlockCorrect == false {\n\t\treturn false\n\t}\n\n\tblockList = append(blockList, block)\n\tblockchain.Chain[blockHeight] = blockList // replacing with new blocklist\n\treturn true\n\n}", "func (s *BlockchainService) generateBlock(oldBlock *Block, payload int) Block {\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Payload = payload\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(&newBlock)\n\n\treturn newBlock\n}", "func (b *BlockChain) AddBlock(tx *Transaction) {\n\t// construct new block and prev hash will be current tip of db\n\tblock := NewBlock([]*Transaction{tx}, b.tip)\n\n\terr := b.db.Update(func(tx *bolt.Tx) error {\n\t\tbckt := tx.Bucket([]byte(blocksBucket))\n\t\tif err := bckt.Put(block.Hash, block.Serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := bckt.Put([]byte(\"l\"), block.Hash); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.tip = block.Hash\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"AddBlock :\", err)\n\t}\n}", "func AddInsideBlock(gf genny.File, search string, expressions ...string) (genny.File, error) {\n\tname := gf.Name()\n\tgf, err := beforeParse(gf)\n\tif err != nil {\n\t\treturn gf, errors.WithStack(err)\n\t}\n\n\tsrc := gf.String()\n\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, gf.Name(), src, 0)\n\tif err != nil {\n\t\treturn gf, err\n\t}\n\n\tfileLines := strings.Split(src, \"\\n\")\n\n\tend := findClosingRouteBlockEnd(search, f, fset, fileLines)\n\tif end < 0 {\n\t\treturn gf, errors.Errorf(\"could not find desired block in %s\", name)\n\t}\n\n\tel := fileLines[end:]\n\tsl := []string{}\n\tsf := []string{}\n\tfor _, l := range fileLines[:end] {\n\t\t// if there's a app.ServeFiles(\"/\", foo) line it needs to be the last added to the router\n\t\tif strings.Contains(l, \"ServeFiles(\\\"/\\\"\") {\n\t\t\tsf = append(sf, l)\n\t\t\tcontinue\n\t\t}\n\t\tsl = append(sl, l)\n\t}\n\n\tfor i := 0; i < len(expressions); i++ {\n\t\texpressions[i] = fmt.Sprintf(\"\\t\\t%s\", expressions[i])\n\t}\n\n\tel = append(sf, el...)\n\tfileLines = append(sl, append(expressions, el...)...)\n\n\tfileContent := strings.Join(fileLines, \"\\n\")\n\treturn genny.NewFile(name, strings.NewReader(fileContent)), err\n}", "func (chain *Blockchain) AddBlock(transactions []*Transaction) (err error) {\n\tblock := NewBlock(transactions, chain.Tail)\n\tbytes, err := json.Marshal(block)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = chain.Database.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BucketName))\n\t\terr := bucket.Put(block.Hash, bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = bucket.Put([]byte(LastBlockKey), block.Hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tchain.Tail = block.Hash\n\treturn\n}", "func (bc *BlockChain) AddBlock(data string) {\n\tprevBlock := bc.Blocks[len(bc.Blocks)-1]\n\tnew := CreateBlock(data, prevBlock.Hash)\n\tbc.Blocks = append(bc.Blocks, new)\n}", "func (b *spanSet) push(s *mspan) {\n\t// Obtain our slot.\n\tcursor := uintptr(b.index.incTail().tail() - 1)\n\ttop, bottom := cursor/spanSetBlockEntries, cursor%spanSetBlockEntries\n\n\t// Do we need to add a block?\n\tspineLen := b.spineLen.Load()\n\tvar block *spanSetBlock\nretry:\n\tif top < spineLen {\n\t\tblock = b.spine.Load().lookup(top).Load()\n\t} else {\n\t\t// Add a new block to the spine, potentially growing\n\t\t// the spine.\n\t\tlock(&b.spineLock)\n\t\t// spineLen cannot change until we release the lock,\n\t\t// but may have changed while we were waiting.\n\t\tspineLen = b.spineLen.Load()\n\t\tif top < spineLen {\n\t\t\tunlock(&b.spineLock)\n\t\t\tgoto retry\n\t\t}\n\n\t\tspine := b.spine.Load()\n\t\tif spineLen == b.spineCap {\n\t\t\t// Grow the spine.\n\t\t\tnewCap := b.spineCap * 2\n\t\t\tif newCap == 0 {\n\t\t\t\tnewCap = spanSetInitSpineCap\n\t\t\t}\n\t\t\tnewSpine := persistentalloc(newCap*goarch.PtrSize, cpu.CacheLineSize, &memstats.gcMiscSys)\n\t\t\tif b.spineCap != 0 {\n\t\t\t\t// Blocks are allocated off-heap, so\n\t\t\t\t// no write barriers.\n\t\t\t\tmemmove(newSpine, spine.p, b.spineCap*goarch.PtrSize)\n\t\t\t}\n\t\t\tspine = spanSetSpinePointer{newSpine}\n\n\t\t\t// Spine is allocated off-heap, so no write barrier.\n\t\t\tb.spine.StoreNoWB(spine)\n\t\t\tb.spineCap = newCap\n\t\t\t// We can't immediately free the old spine\n\t\t\t// since a concurrent push with a lower index\n\t\t\t// could still be reading from it. We let it\n\t\t\t// leak because even a 1TB heap would waste\n\t\t\t// less than 2MB of memory on old spines. If\n\t\t\t// this is a problem, we could free old spines\n\t\t\t// during STW.\n\t\t}\n\n\t\t// Allocate a new block from the pool.\n\t\tblock = spanSetBlockPool.alloc()\n\n\t\t// Add it to the spine.\n\t\t// Blocks are allocated off-heap, so no write barrier.\n\t\tspine.lookup(top).StoreNoWB(block)\n\t\tb.spineLen.Store(spineLen + 1)\n\t\tunlock(&b.spineLock)\n\t}\n\n\t// We have a block. Insert the span atomically, since there may be\n\t// concurrent readers via the block API.\n\tblock.spans[bottom].StoreNoWB(s)\n}", "func (chain *Chain) append(cm Middleware) (newChain *Chain) {\n\tnewChain = NewChain(cm)\n\tnewChain.parent = chain\n\treturn newChain\n}", "func (blockchain *Blockchain) AddBlock(newBlock Block) {\n\tnewBlock.Mine()\n\tif len(*blockchain) > 0 {\n\t\tnewBlock.addPrevious((*blockchain)[len(*blockchain)-1].Hash)\n\t}\n\t*blockchain = append((*blockchain), newBlock)\n}", "func (sr *shardResult) AddBlock(id ident.ID, b block.DatabaseBlock) {\n\tcurSeries, exists := sr.blocks[id.Hash()]\n\tif !exists {\n\t\tcurSeries = sr.newBlocks(id)\n\t\tsr.blocks[id.Hash()] = curSeries\n\t}\n\tcurSeries.Blocks.AddBlock(b)\n}", "func genesis(blockchain *BlockChain, block block1.Block, blockHeight int32) bool {\n\n\tblockchain.Chain[blockHeight] = append(blockchain.Chain[blockHeight], block)\n\tblockchain.Length++\n\treturn true\n}", "func (sbc *SyncBlockChain) Insert(b Block) {\n\tlog.Println(\"Log: Insert: Begin insert attempt\")\n\tif b.Header.Height >= 1 {\n\t\tif sbc.GetParentBlock(&b) != nil {\n\t\t\tb.Header.Difficulty = int32(len(TARGET)) + sbc.GetParentBlock(&b).Header.Difficulty\n\t\t} else {\n\t\t\tlog.Println(\"Log: Insert: could not insert because not parent foudn\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tsbc.Mux.Lock()\n\tdefer sbc.Mux.Unlock()\n\tval, ok := sbc.BC.Chain[b.Header.Height]\n\tif ok {\n\t\tfor i := 0; i < len(val); i++ {\n\t\t\tif val[i] == b {\n\t\t\t\tlog.Println(\"Log: Insert: block was not inserted because duplicate\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tsbc.BC.Chain[b.Header.Height] = append(sbc.BC.Chain[b.Header.Height], b)\n\tlog.Println(\"Log: Insert: succesful insert for: \" + b.Header.Hash)\n\n\tif b.Header.Height > sbc.BC.Length {\n\t\tsbc.BC.Length = b.Header.Height\n\t}\n\n\t//.Println(\"LOG: post sbc.insert Show() below \")\n\t//fmt.Println(sbc.BC.Show())\n}", "func (chain *BlockChain) AddBlock(data string) error {\r\n\r\n\t// Get Last-Hash from DB\r\n\tlastHash, lastHashErr := database.GetLastHash()\r\n\tif lastHashErr != nil {\r\n\t\tmsg := fmt.Sprintf(\"Failed to retrieve Last-Hash from DB (Error = %s)\", lastHashErr.Error())\r\n\t\treturn errors.New(msg)\r\n\t}\r\n\r\n\t// Create New Block\r\n\tnewBlock, newBlockErr := CreateBlock(data, lastHash)\r\n\tif newBlockErr != nil {\r\n\t\tmsg := fmt.Sprintf(\"Failed to create new block (Error = %s)\", newBlockErr.Error())\r\n\t\treturn errors.New(msg)\r\n\t}\r\n\r\n\t// Serialize the New Block\r\n\tblockSerialized, serializedErr := newBlock.Serialize()\r\n\tif serializedErr != nil {\r\n\t\tmsg := fmt.Sprintf(\"Failed to serialize new block (Error = %s)\", serializedErr.Error())\r\n\t\treturn errors.New(msg)\r\n\t}\r\n\r\n\t// Store New Block in DB\r\n\tstoreBlockErr := database.SetBlock(newBlock.Hash, blockSerialized)\r\n\tif storeBlockErr != nil {\r\n\t\tmsg := fmt.Sprintf(\"Failed to store new block in DB (Error = %s)\", storeBlockErr.Error())\r\n\t\treturn errors.New(msg)\r\n\t}\r\n\r\n\t// Update the Last-Hash\r\n\tchain.LastHash = newBlock.Hash\r\n\r\n\treturn nil\r\n}", "func (c *BlockCache) Add(height int, block *walletrpc.CompactBlock) error {\n\t// Invariant: m[firstBlock..nextBlock) are valid.\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif height > c.nextBlock {\n\t\t// Cache has been reset (for example, checksum error)\n\t\treturn nil\n\t}\n\tif height < c.firstBlock {\n\t\t// Should never try to add a block before Sapling activation height\n\t\tLog.Fatal(\"cache.Add height below Sapling: \", height)\n\t\treturn nil\n\t}\n\tif height < c.nextBlock {\n\t\t// Should never try to \"backup\" (call Reorg() instead).\n\t\tLog.Fatal(\"cache.Add height going backwards: \", height)\n\t\treturn nil\n\t}\n\tbheight := int(block.Height)\n\n\tif bheight != height {\n\t\t// This could only happen if zcashd returned the wrong\n\t\t// block (not the height we requested).\n\t\tLog.Fatal(\"cache.Add wrong height: \", bheight, \" expecting: \", height)\n\t\treturn nil\n\t}\n\n\t// Add the new block and its length to the db files.\n\tdata, err := proto.Marshal(block)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := append(checksum(height, data), data...)\n\tn, err := c.blocksFile.Write(b)\n\tif err != nil {\n\t\tLog.Fatal(\"blocks write failed: \", err)\n\t}\n\tif n != len(b) {\n\t\tLog.Fatal(\"blocks write incorrect length: expected: \", len(b), \"written: \", n)\n\t}\n\tb = make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(b, uint32(len(data)))\n\tn, err = c.lengthsFile.Write(b)\n\tif err != nil {\n\t\tLog.Fatal(\"lengths write failed: \", err)\n\t}\n\tif n != len(b) {\n\t\tLog.Fatal(\"lengths write incorrect length: expected: \", len(b), \"written: \", n)\n\t}\n\n\t// update the in-memory variables\n\toffset := c.starts[len(c.starts)-1]\n\tc.starts = append(c.starts, offset+int64(len(data)+8))\n\n\tif c.latestHash == nil {\n\t\tc.latestHash = make([]byte, len(block.Hash))\n\t}\n\tcopy(c.latestHash, block.Hash)\n\tc.nextBlock++\n\t// Invariant: m[firstBlock..nextBlock) are valid.\n\treturn nil\n}", "func (l *blocksLRU) add(b block) {\n\tif _, ok := l.blocks[b.offset]; ok {\n\t\tpanic(fmt.Sprintf(\"block with offset %d is already in the LRU\", b.offset))\n\t}\n\tl.prepareForAdd()\n\tl.blocks[b.offset] = l.ll.PushFront(b)\n}", "func (s *BasevhdlListener) EnterBlock_declarative_part(ctx *Block_declarative_partContext) {}", "func (b *blockchain) addHeader(h *wire.BlockHeader) error {\n\tblock, err := b.createChainHeader(h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := b.Direct[block.Hash.String()]; ok {\n\t\treturn errors.New(\"We already have this block...\")\n\t}\n\n\t// Add the direct block mapping.\n\tb.Direct[block.Hash.String()] = block\n\n\t// Is the PreviousBlock Hash already in the Chain?\n\tif check, ok := b.Direct[h.PrevBlock.String()]; ok {\n\t\tblock.Height = check.Height + 1\n\t\tblock.Previous = check\n\n\t\tif block.Height > b.Height {\n\t\t\tb.Top = block\n\t\t\tb.Height = block.Height\n\t\t\t// fmt.Println(\"ACCEPTED New Top Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t\t} else {\n\t\t\t// fmt.Println(\"ACCEPTED Orphaned Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t\t}\n\n\t\tif b.SyncedTime.Before(h.Timestamp) {\n\t\t\tb.SyncedTime = h.Timestamp\n\t\t}\n\t} else if b.Top == nil && b.Base.IsEqual(&h.PrevBlock) {\n\t\t// This block is at the top of the chain.\n\t\tblock.IsBottom = true\n\t\tblock.Height = b.Base.Height + 1\n\n\t\tb.Height = block.Height\n\t\tb.Top = block\n\n\t\tb.SyncedTime = h.Timestamp\n\t\t// fmt.Println(\"ACCEPTED Base Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t} else {\n\t\t// This block is orphaned\n\t\tb.Orphaned[block.Hash.String()] = block\n\t\t// fmt.Println(\"ACCEPTED Orphaned Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t}\n\n\treturn nil\n}", "func UpdateBlockChain(block shared.Block) {\n\t// Updates the block chain\n\ttempBlockChain := blockChain\n\tnewBlockChain := shared.Node{Block: block, Prev: &tempBlockChain}\n\tblockChain = newBlockChain\n\t// Updates the previous hash here\n\tprevHash = block.Hash\n\t// Updates the block hashes that exist\n\texistingBlockHashes[block.Hash] = block\n\n\thash_val := block.PreviousBlockHash\n\n\tchildrenList, ok := childrenMap[hash_val]\n\tif ok {\n\t\t// update the map here\n\t\tnew_list := childrenList\n\t\tcontains := false\n\t\tfor _, value := range childrenList {\n\t\t\tif value == prevHash {\n\t\t\t\tcontains = true\n\t\t\t}\n\t\t}\n\n\t\tif !contains {\n\t\t\tnew_list = append(new_list, prevHash)\n\t\t}\n\t\tchildrenMap[hash_val] = new_list\n\t} else {\n\t\tnew_list := []string{prevHash}\n\t\tchildrenMap[hash_val] = new_list\n\t}\n}", "func (s *BasevhdlListener) EnterBlock_declarative_item(ctx *Block_declarative_itemContext) {}", "func contextBlockSplitterAddSymbol(self *contextBlockSplitter, symbol uint, context uint) {\n\thistogramAddLiteral(&self.histograms_[self.curr_histogram_ix_+context], symbol)\n\tself.block_size_++\n\tif self.block_size_ == self.target_block_size_ {\n\t\tcontextBlockSplitterFinishBlock(self, false) /* is_final = */\n\t}\n}", "func (blockChain *BlockChain) Insert(block Block) {\n\tif block.Header.Height > blockChain.Length {\n\t\tblockChain.Length = block.Header.Height\n\t}\n\theightBlocks := blockChain.Chain[block.Header.Height]\n\tif heightBlocks == nil { // return empty block if heght is zero\n\t\theightBlocks = []Block{}\n\t}\n\tfor _, heightBlock := range heightBlocks { // find simmilar hash in blockchain\n\t\tif heightBlock.Header.Hash == block.Header.Hash {\n\t\t\treturn\n\t\t}\n\t}\n\t// append to blockChain\n\tblockChain.Chain[block.Header.Height] = append(heightBlocks, block)\n}", "func addMatchToBlocks(blocks *[]Block, left, right int, value string) {\n\tif len(*blocks) > 0 && (*blocks)[len(*blocks)-1].IsEqual() {\n\t\tif len(*blocks) > 0 && (left-(*blocks)[len(*blocks)-1].(EqualBlock).Equals[len((*blocks)[len(*blocks)-1].(EqualBlock).Equals)-1].LeftLine > 1 ||\n\t\t\tright-(*blocks)[len(*blocks)-1].(EqualBlock).Equals[len((*blocks)[len(*blocks)-1].(EqualBlock).Equals)-1].RightLine > 1) {\n\t\t\t*blocks = append(*blocks, DiffBlock{}, EqualBlock{[]Equal{{\n\t\t\t\tLeftLine: left,\n\t\t\t\tRightLine: right,\n\t\t\t\tValue: value,\n\t\t\t}}})\n\t\t} else {\n\t\t\t(*blocks)[len(*blocks)-1] = EqualBlock{\n\t\t\t\tEquals: append((*blocks)[len(*blocks)-1].(EqualBlock).Equals, Equal{\n\t\t\t\t\tLeftLine: left,\n\t\t\t\t\tRightLine: right,\n\t\t\t\t\tValue: value,\n\t\t\t\t}),\n\t\t\t}\n\t\t}\n\t} else {\n\t\t*blocks = append(*blocks, EqualBlock{[]Equal{{\n\t\t\tLeftLine: left,\n\t\t\tRightLine: right,\n\t\t\tValue: value,\n\t\t}}})\n\t}\n}", "func (ts *Tipset) Block(miner Miner, winCount int64, msgs ...*ApplicableMessage) {\n\tblock := Block{\n\t\tMinerAddr: miner.MinerActorAddr.ID,\n\t\tWinCount: winCount,\n\t}\n\tfor _, am := range msgs {\n\t\tblock.Messages = append(block.Messages, MustSerialize(am.Message))\n\n\t\t// if we see this message for the first time, add it to the `msgIdx` map and to the `orderMsgs` slice.\n\t\tif _, ok := ts.tss.msgIdx[am.Message.Cid()]; !ok {\n\t\t\tts.tss.msgIdx[am.Message.Cid()] = am\n\t\t\tts.tss.orderedMsgs = append(ts.tss.orderedMsgs, am)\n\t\t}\n\t}\n\n\tts.Blocks = append(ts.Blocks, block)\n}", "func addLength(blockchain *BlockChain, block block1.Block, blockHeight int32) bool {\n\n\tblockchain.Chain[blockHeight] = append(blockchain.Chain[blockHeight], block)\n\tblockchain.Length = blockHeight\n\treturn true\n\n}", "func (e *engineImpl) Seal(chain engine.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error {\n\t// TODO: implement final block sealing\n\treturn nil\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Validator = address\n\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Data = makeSignature(newBlock.Hash)\n\n\treturn newBlock, nil\n}", "func AddBlock(block *types.Block, db *types.DB) {\n\ttxCheck := func(txs []*types.Tx) bool {\n\t\t// start = copy.deepcopy(txs)\n\t\tvar start = txs\n\t\tvar txsSource []*types.Tx\n\t\tvar startCopy []*types.Tx\n\n\t\tfor !reflect.DeepEqual(start, startCopy) {\n\t\t\t// Block passes this test\n\t\t\tif start == nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// startCopy = copy.deepcopy(start)\n\t\t\tstartCopy = start\n\t\t\tlast := start[len(start)-1]\n\n\t\t\t// transactions.tx_check[start[-1]['type']](start[-1], out, DB)\n\t\t\tfn := transactionVerify[last.Type]\n\t\t\tif fn(last, txsSource, db) {\n\t\t\t\t// start.pop()\n\t\t\t\tstart = start[:len(start)-1]\n\t\t\t\ttxsSource = append(txsSource, last)\n\t\t\t} else {\n\t\t\t\t// Block is invalid\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// Block is invalid\n\t\treturn true\n\t}\n\n\t// if \"error\" in block: return False\n\tif block.Error != nil {\n\t\treturn\n\t}\n\n\t// if \"length\" not in block: return False\n\t// NOTE: block.Length not being set means it takes its \"zero value\".\n\t// This shouldn't be a problem, check out next if stmt.\n\tif block.Length == 0 {\n\t\treturn\n\t}\n\n\tlength := db.Length\n\tif block.Length != length+1 {\n\t\treturn\n\t}\n\n\tif block.DiffLength != HexSum(db.DiffLength, HexInv(block.Target)) {\n\t\treturn\n\t}\n\n\tif length >= 0 && tools.DetHash(db.GetBlock(length)) != block.PrevHash {\n\t\treturn\n\t}\n\n\t// a = copy.deepcopy(block)\n\t// a.pop(\"nonce\")\n\tblockCopy := block\n\tblockCopy.Nonce = nil\n\n\t//if \"target\" not in block.keys(): return False\n\tif block.Target == \"\" {\n\t\treturn\n\t}\n\n\thalfWay := &types.HalfWay{\n\t\tNonce: block.Nonce,\n\t\tHalfHash: tools.DetHash(blockCopy),\n\t}\n\n\tif tools.DetHash(halfWay) > block.Target {\n\t\treturn\n\t}\n\n\tif block.Target != Target(db, block.Length) {\n\t\treturn\n\t}\n\n\t// TODO: Figure out why 8 (length)?\n\tearliestMedian := median(RecentBlockTimes(db, config.Get().Mmm, 8))\n\t// `float64` (unix epoch) back to `time.Time`\n\tsec, nsec := math.Modf(earliestMedian)\n\tearliest := time.Unix(int64(sec), int64(nsec*1e9))\n\n\t// if block.Time > time.time(): return false\n\t// if block.Time < earliest: return false\n\tif block.Time.After(time.Now()) || block.Time.Before(earliest) {\n\t\treturn\n\t}\n\n\tif txCheck(block.Txs) {\n\t\treturn\n\t}\n\n\t// block_check was unnecessary because it was only called once\n\t// and it only returned true at its end\n\n\t// if block_check(block, db):\n\tlog.Println(\"add_block:\", block)\n\tdb.Put(strconv.Itoa(block.Length), block)\n\n\tdb.Length = block.Length\n\tdb.DiffLength = block.DiffLength\n\n\torphans := db.Txs\n\tdb.Txs = nil\n\n\tfor _, tx := range block.Txs {\n\t\tdb.AddBlock = true\n\t\tfn := transactionUpdate[tx.Type]\n\t\tfn(tx, db)\n\t}\n\n\tfor _, tx := range orphans {\n\t\tAddTx(tx, db)\n\t}\n}", "func (honest *Honest) createBlock(iterationCount int, stakeMap map[int]int) (*Block,error) {\n\n\t// Has block already been appended from advertisements by other client?\n\tif(honest.bc.getBlock(iterationCount) != nil){\n\t\treturn nil, blockExistsError\n\t}\n\n\tpulledGradient := make([]float64, honest.ncol)\n\tpulledGradient = honest.bc.getLatestGradient()\n\tupdatedGradient := make([]float64, honest.ncol)\n\tdeltaM := mat.NewDense(1, honest.ncol, make([]float64, honest.ncol))\n\tpulledGradientM := mat.NewDense(1, honest.ncol, pulledGradient)\n\t// avgFactor := 1.0/float64(len(honest.blockUpdates))\n\n\t// Update Aggregation\n\tfor _, update := range honest.blockUpdates {\n\t\ttheirStake := stakeMap[update.SourceID] \n\t\tif update.Accepted {\n\t\t\tdeltaM = mat.NewDense(1, honest.ncol, update.Delta)\n\t\t\tpulledGradientM.Add(pulledGradientM, deltaM)\t\n\t\t\tstakeMap[update.SourceID] = theirStake + STAKE_UNIT\n\t\t} else {\n\t\t\toutLog.Printf(\"Skipping an update\")\n\t\t\tstakeMap[update.SourceID] = theirStake - STAKE_UNIT\n\t\t}\n\t}\n\n\t// pulledGradientM.Scale(avgFactor, pulledGradientM)\n\n\tmat.Row(updatedGradient, 0, pulledGradientM)\n\n\tupdatesGathered := make([]Update, len(honest.blockUpdates))\n\tcopy(updatesGathered, honest.blockUpdates)\n\n\tbData := BlockData{iterationCount, updatedGradient, updatesGathered}\n\thonest.bc.AddBlock(bData, stakeMap) \n\n\tnewBlock := honest.bc.Blocks[len(honest.bc.Blocks)-1]\n\n\treturn newBlock,nil\n\n\n}", "func (b *Builder) append(data []byte) {\n\tdst := b.allocate(len(data))\n\tutils.AssertTrue(len(data) == copy(dst, data))\n\n\t/*\n\t\tif b.currentBlock == nil {\n\t\t\tb.currentBlock = &pb.Block{\n\t\t\t\tData: make([]byte, 64*KB),\n\t\t\t\t//BlockLength: uint32(size),\n\t\t\t}\n\t\t\tb.blocks = append(b.blocks, b.currentBlock)\n\t\t}\n\t\t// Ensure we have enough spa\t to store new data.\n\t\tif uint32(len(b.currentBlock.Data)) < b.sz+uint32(len(data)) {\n\t\t\tblockGrow(b.currentBlock, uint32(len(data)))\n\t\t}\n\n\t\tcopy(b.currentBlock.Data[b.sz:], data)\n\t\tb.sz += uint32(len(data))\n\t*/\n}", "func (c *ChainPing) AppendPing(b BlockPing) *ChainPing {\n\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\tc.Chain = append(c.Chain, b)\n\tc.Size = unsafe.Sizeof(c)\n\tc.LengthElements = len(c.Chain)\n\tl := c.LengthElements\n\tif l != 1 {\n\t\tc.Chain[l-2].NextBlock = &c.Chain[l-1]\n\t\tc.Chain[l-1].PrevBlock = &c.Chain[l-2]\n\t\tc.Chain[l-1].NextBlock = nil\n\t\t// update normalised time\n\t\tc.Chain[l-1].NormalizedTime = c.Chain[l-2].NormalizedTime + 1\n\t}\n\treturn c\n\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func (s *BaseBundListener) EnterBlock(ctx *BlockContext) {}", "func (dc *Decompressor) Append(cb CompressedBlock) error {\n\torder := atomic.AddUint64(&dc.order, 1)\n\tselect {\n\tcase dc.workCh <- &blockDesc{\n\t\torder: order,\n\t\tCompressedBlock: cb,\n\t}:\n\tcase <-dc.ctx.Done():\n\t\treturn dc.ctx.Err()\n\t}\n\treturn nil\n}", "func placeCustomChainInChain(ipt *iptables.IPTables, table, chain string) error {\n\texists, err := ipt.Exists(table, chain, \"-j\", customchainname)\n\tif err != nil || !exists {\n\t\tif err := ipt.Insert(table, chain, 1, \"-j\", customchainname); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func generateBlock(oldBlock Block, Key int) Block {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.Key = Key\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateHash(newBlock)\n\n\tf, err := os.OpenFile(\"blocks.txt\",\n\t\tos.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tb, err := json.Marshal(newBlock)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer f.Close()\n\tif _, err := f.WriteString(string(b)); err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn newBlock\n}", "func (f *Builder) AppendBlockOn(ctx context.Context, parent *types.TipSet) *types.BlockHeader {\n\treturn f.Build(ctx, parent, 1, nil).At(0)\n}", "func (oc *Operachain) MakeBlock(name string) {\n\tvar newHeight int\n\tvar tip []byte\n\terr := oc.Db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\t\ttip = b.Get([]byte(\"l\"))\n\t\ttipData := b.Get(tip)\n\t\ttipBlock := DeserializeBlock(tipData)\n\t\tnewHeight = tipBlock.Height + 1\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tnewBlock := NewBlock(oc.MyName, tip, oc.KnownTips[name], newHeight)\n\n\toc.AddBlock(newBlock)\n\n\toc.MyGraph.Tip = oc.BuildGraph(newBlock.Hash, oc.MyGraph.ChkVertex, oc.MyGraph)\n\tfmt.Println(\"create new block\")\n\t//oc.UpdateChk = true\n}", "func (b *BlockDAG) attach(data *models.Block) (block *blockdag.Block, wasAttached bool, err error) {\n\tb.evictionMutex.RLock()\n\tdefer b.evictionMutex.RUnlock()\n\n\tif block, wasAttached, err = b.canAttach(data); !wasAttached {\n\t\treturn\n\t}\n\n\tif block, wasAttached = b.memStorage.Get(data.ID().SlotIndex, true).GetOrCreate(data.ID(), func() *blockdag.Block { return blockdag.NewBlock(data) }); !wasAttached {\n\t\tif wasAttached = block.Update(data); !wasAttached {\n\t\t\treturn\n\t\t}\n\n\t\tb.events.MissingBlockAttached.Trigger(block)\n\t}\n\n\tblock.ForEachParent(func(parent models.Parent) {\n\t\tb.registerChild(block, parent)\n\t})\n\n\treturn\n}", "func (b *BlockChain) maybeAcceptBlock(block *types.SerializedBlock, flags BehaviorFlags) error {\n\t// This function should never be called with orphan blocks or the\n\t// genesis block.\n\tb.ChainLock()\n\tdefer func() {\n\t\tb.ChainUnlock()\n\t\tb.flushNotifications()\n\t}()\n\n\tnewNode := NewBlockNode(block, block.Block().Parents)\n\tmainParent := b.bd.GetMainParentByHashs(block.Block().Parents)\n\tif mainParent == nil {\n\t\treturn fmt.Errorf(\"Can't find main parent\\n\")\n\t}\n\t// The block must pass all of the validation rules which depend on the\n\t// position of the block within the block chain.\n\terr := b.checkBlockContext(block, mainParent, flags)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Prune stake nodes which are no longer needed before creating a new\n\t// node.\n\tb.pruner.pruneChainIfNeeded()\n\n\t//dag\n\tnewOrders, oldOrders, ib, isMainChainTipChange := b.bd.AddBlock(newNode)\n\tif newOrders == nil || newOrders.Len() == 0 || ib == nil {\n\t\treturn fmt.Errorf(\"Irreparable error![%s]\\n\", newNode.GetHash().String())\n\t}\n\tblock.SetOrder(uint64(ib.GetOrder()))\n\tblock.SetHeight(ib.GetHeight())\n\n\t// Insert the block into the database if it's not already there. Even\n\t// though it is possible the block will ultimately fail to connect, it\n\t// has already passed all proof-of-work and validity tests which means\n\t// it would be prohibitively expensive for an attacker to fill up the\n\t// disk with a bunch of blocks that fail to connect. This is necessary\n\t// since it allows block download to be decoupled from the much more\n\t// expensive connection logic. It also has some other nice properties\n\t// such as making blocks that never become part of the main chain or\n\t// blocks that fail to connect available for further analysis.\n\t//\n\t// Also, store the associated block index entry.\n\terr = b.db.Update(func(dbTx database.Tx) error {\n\t\texists, err := dbTx.HasBlock(block.Hash())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif exists {\n\t\t\treturn nil\n\t\t}\n\t\terr = dbMaybeStoreBlock(dbTx, block)\n\t\tif err != nil {\n\t\t\tif database.IsError(err, database.ErrBlockExists) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// Connect the passed block to the chain while respecting proper chain\n\t// selection according to the chain with the most proof of work. This\n\t// also handles validation of the transaction scripts.\n\t_, err = b.connectDagChain(ib, block, newOrders, oldOrders)\n\tif err != nil {\n\t\tlog.Warn(fmt.Sprintf(\"%s\", err))\n\t}\n\n\terr = b.updateBestState(ib, block, newOrders)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tb.ChainUnlock()\n\t// Notify the caller that the new block was accepted into the block\n\t// chain. The caller would typically want to react by relaying the\n\t// inventory to other peers.\n\tb.sendNotification(BlockAccepted, &BlockAcceptedNotifyData{\n\t\tIsMainChainTipChange: isMainChainTipChange,\n\t\tBlock: block,\n\t\tFlags: flags,\n\t})\n\tb.ChainLock()\n\treturn nil\n}", "func (bc *Blockchain) chainNewBlock(nonce int, previousHash [32]byte) *Block {\n\tb := NewBlock(nonce, previousHash, bc.transactionPool)\n\tbc.chain = append(bc.chain, b)\n\tbc.transactionPool = []*Transaction{}\n\treturn b\n}", "func finalizeBlock(block *protocol.Block) error {\n\t//Check if we have a slashing proof that we can add to the block.\n\t//The slashingDict is updated when a new block is received and when a slashing proof is provided.\n\tlogger.Printf(\"-- Start Finalize\")\n\tif len(slashingDict) != 0 {\n\t\t//Get the first slashing proof.\n\t\tfor hash, slashingProof := range slashingDict {\n\t\t\tblock.SlashedAddress = hash\n\t\t\tblock.ConflictingBlockHash1 = slashingProof.ConflictingBlockHash1\n\t\t\tblock.ConflictingBlockHash2 = slashingProof.ConflictingBlockHash2\n\t\t\tblock.ConflictingBlockHashWithoutTx1 = slashingProof.ConflictingBlockHashWithoutTx1\n\t\t\tblock.ConflictingBlockHashWithoutTx2 = slashingProof.ConflictingBlockHashWithoutTx2\n\t\t\tbreak\n\t\t}\n\t}\n\n\t//Merkle tree includes the hashes of all txs in this block\n\tblock.MerkleRoot = protocol.BuildMerkleTree(block).MerkleRoot()\n\tvalidatorAcc, err := storage.GetAccount(protocol.SerializeHashContent(validatorAccAddress))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalidatorAccHash := validatorAcc.Hash()\n\tcopy(block.Beneficiary[:], validatorAccHash[:])\n\n\t// Cryptographic Sortition for PoS in Bazo\n\t// The commitment proof stores a signed message of the Height that this block was created at.\n\tcommitmentProof, err := crypto.SignMessageWithRSAKey(commPrivKey, fmt.Sprint(block.Height))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\n\t//Block hash with MerkleTree and therefore, including all transactions\n\tpartialHash := block.HashBlock()\n\n\t//Block hash without MerkleTree and therefore, without any transactions\n\tpartialHashWithoutMerkleRoot := block.HashBlockWithoutMerkleRoot()\n\n\tprevProofs := GetLatestProofs(activeParameters.num_included_prev_proofs, block)\n\tnonce, err := proofOfStake(getDifficulty(), block.PrevHash, prevProofs, block.Height, validatorAcc.Balance, commitmentProof)\n\tif err != nil {\n\t\t//Delete all partially added transactions.\n\t\tif nonce == -2 {\n\t\t\tfor _, tx := range storage.FundsTxBeforeAggregation {\n\t\t\t\tstorage.WriteOpenTx(tx)\n\t\t\t}\n\t\t\tstorage.DeleteAllFundsTxBeforeAggregation()\n\t\t}\n\t\treturn err\n\t}\n\n\tvar nonceBuf [8]byte\n\tbinary.BigEndian.PutUint64(nonceBuf[:], uint64(nonce))\n\tblock.Nonce = nonceBuf\n\tblock.Timestamp = nonce\n\n\t//Put pieces together to get the final hash.\n\tblock.Hash = sha3.Sum256(append(nonceBuf[:], partialHash[:]...))\n\tblock.HashWithoutTx = sha3.Sum256(append(nonceBuf[:], partialHashWithoutMerkleRoot[:]...))\n\n\t//This doesn't need to be hashed, because we already have the merkle tree taking care of consistency.\n\tblock.NrAccTx = uint16(len(block.AccTxData))\n\tblock.NrFundsTx = uint16(len(block.FundsTxData))\n\tblock.NrConfigTx = uint8(len(block.ConfigTxData))\n\tblock.NrStakeTx = uint16(len(block.StakeTxData))\n\tblock.NrAggTx = uint16(len(block.AggTxData))\n\n\tcopy(block.CommitmentProof[0:crypto.COMM_PROOF_LENGTH], commitmentProof[:])\n\tlogger.Printf(\"-- End Finalization\")\n\treturn nil\n}", "func (b *Builder) Add(key []byte, value y.ValueStruct) {\n\tif b.shouldFinishBlock(key, value) {\n\t\tb.FinishBlock()\n\t\t// Start a new block. Initialize the block.\n\t\tb.baseKey = []byte{}\n\t\tb.currentBlock = &pb.Block{Data: make([]byte, 64*KB)}\n\t\tb.sz = 0\n\t\tb.entryOffsets = b.entryOffsets[:0]\n\t}\n\tb.addHelper(key, value)\n}", "func (policy *ticketPolicy) OnAddBlockFinish(block *types.BlockDetail) {\n\tif policy.needFlush {\n\t\t// 新增区块,由于ticket具有锁定期,所以这里不需要刷新\n\t\t//policy.flushTicket()\n\t}\n\tpolicy.needFlush = false\n}", "func (f *Func) liftBlock(bb *x86.BasicBlock) {\n\tdbg.Printf(\"lifting basic block at %v\", bb.Addr)\n\tf.cur = f.blocks[bb.Addr]\n\tf.Blocks = append(f.Blocks, f.cur)\n\tfor _, inst := range bb.Insts {\n\t\tf.liftInst(inst)\n\t}\n\tf.liftTerm(bb.Term)\n}", "func (mpi *mempoolImpl) handleTrackNewChainHead(req *reqTrackNewChainHead) {\n\tdefer close(req.responseCh)\n\tmpi.log.Debugf(\"handleTrackNewChainHead, %v from %v, current=%v\", req.till, req.from, mpi.chainHeadAO)\n\tif len(req.removed) != 0 {\n\t\tmpi.log.Infof(\"Reorg detected, removing %v blocks, adding %v blocks\", len(req.removed), len(req.added))\n\t\t// TODO: For IOTA 2.0: Maybe re-read the state from L1 (when reorgs will become possible).\n\t}\n\t//\n\t// Re-add requests from the blocks that are reverted now.\n\tfor _, block := range req.removed {\n\t\tblockReceipts, err := blocklog.RequestReceiptsFromBlock(block)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot extract receipts from block: %w\", err))\n\t\t}\n\t\tfor _, receipt := range blockReceipts {\n\t\t\tif blocklog.HasUnprocessableRequestBeenRemovedInBlock(block, receipt.Request.ID()) {\n\t\t\t\tcontinue // do not add unprocessable requests that were successfully retried back into the mempool in case of a reorg\n\t\t\t}\n\t\t\tmpi.tryReAddRequest(receipt.Request)\n\t\t}\n\t}\n\t//\n\t// Cleanup the requests that were consumed in the added blocks.\n\tfor _, block := range req.added {\n\t\tblockReceipts, err := blocklog.RequestReceiptsFromBlock(block)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot extract receipts from block: %w\", err))\n\t\t}\n\t\tmpi.metrics.IncBlocksPerChain()\n\t\tmpi.listener.BlockApplied(mpi.chainID, block)\n\t\tfor _, receipt := range blockReceipts {\n\t\t\tmpi.metrics.IncRequestsProcessed()\n\t\t\tmpi.tryRemoveRequest(receipt.Request)\n\t\t}\n\t\tunprocessableRequests, err := blocklog.UnprocessableRequestsAddedInBlock(block)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot extract unprocessable requests from block: %w\", err))\n\t\t}\n\t\tfor _, req := range unprocessableRequests {\n\t\t\tmpi.metrics.IncRequestsProcessed()\n\t\t\tmpi.tryRemoveRequest(req)\n\t\t}\n\t}\n\t//\n\t// Cleanup processed requests, if that's the first time we received the state.\n\tif mpi.chainHeadState == nil {\n\t\tmpi.log.Debugf(\"Cleanup processed requests based on the received state...\")\n\t\tmpi.tryCleanupProcessed(req.st)\n\t\tmpi.log.Debugf(\"Cleanup processed requests based on the received state... Done\")\n\t}\n\t//\n\t// Record the head state.\n\tmpi.chainHeadState = req.st\n\tmpi.chainHeadAO = req.till\n\t//\n\t// Process the pending consensus proposal requests if any.\n\tif len(mpi.waitChainHead) != 0 {\n\t\tnewWaitChainHead := []*reqConsensusProposal{}\n\t\tfor i, waiting := range mpi.waitChainHead {\n\t\t\tif waiting.ctx.Err() != nil {\n\t\t\t\tcontinue // Drop it.\n\t\t\t}\n\t\t\tif waiting.aliasOutput.Equals(mpi.chainHeadAO) {\n\t\t\t\tmpi.handleConsensusProposalForChainHead(waiting)\n\t\t\t\tcontinue // Drop it from wait queue.\n\t\t\t}\n\t\t\tnewWaitChainHead = append(newWaitChainHead, mpi.waitChainHead[i])\n\t\t}\n\t\tmpi.waitChainHead = newWaitChainHead\n\t}\n}", "func (bc *Blockchain) ReplaceBlocks(blocks []Block, genesis Block) error {\n\terr := CheckBlocks(blocks, genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocks) <= len(bc.chain) {\n\t\treturn errors.New(\"new blocks length must be longer than current\")\n\t}\n\n\tbc.chain = blocks\n\treturn nil\n}", "func (bc *BlockChain)AddBlock(txs []*Transaction) {\n\tfor _, tx := range txs{\n\t\tif !bc.VerifyTransaction(tx) {\n\t\t\tfmt.Println(\"校验交易失败\")\n\t\t\treturn\n\t\t}\n\t}\n\n\n\t//found the last block's hash\n\tlastHash := bc.tail\n\tdb := bc.db\n\t//create a new block\n\t//send the new block into the blockchain\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BlockBucket))\n\t\tif bucket == nil{\n\t\t\tlog.Fatal(\"no bucket\")\n\t\t}else{\n\t\t\t//Write message into database\n\t\t\tblock := NewBlock(txs, lastHash)\n\t\t\tbucket.Put(block.Hash,block.Serialize())\n\t\t\tbucket.Put([]byte(\"LastHashKey\"),block.Hash)\n\n\t\t\t//update the last hash\n\t\t\tbc.tail = block.Hash\n\n\t\t}\n\t\treturn nil\n\t})\n}", "func (bc *Blockchain) AddBlock(b *block.Block) error {\n\tif !b.Verify() {\n\t\treturn errors.New(\"error: failed in block verification\")\n\t}\n\n\tif err := bc.r.Block.Insert(b); err != nil {\n\t\treturn fmt.Errorf(\"error: failed to insert block to db. err=%v\", err)\n\t}\n\n\tbc.c.PropagateBlock(context.Background(), b)\n\tbc.blocks = append(bc.blocks, b)\n\n\tlog.Printf(\"info: Adding new block: %x\\n\", b.Hash)\n\tlog.Printf(\"debug: block=%+v\\n\", b)\n\tlog.Printf(\"info: Now the length of the chain is %d:\\n\", bc.LatestBlock().Height)\n\treturn nil\n}", "func makeBlock(txns []map[string]int, chain []map[string]interface{}) map[string]interface{} {\n\tparentBlock := chain[len(chain)-1]\n\tparentHash := parentBlock[\"hash\"]\n\tcontents := parentBlock[\"contents\"].(map[string]interface{})\n\tblockNumber := contents[\"blockNumber\"].(int)\n\ttxnCount := len(txns)\n\tblockContents := map[string]interface{}{\"blockNumber\": blockNumber + 1, \"parentHash\": parentHash, \"txnCount\": txnCount, \"txns\": txns}\n\tblockhash := hashme(blockContents)\n\tblock := map[string]interface{}{\"hash\": blockhash, \"contents\": blockContents}\n\treturn block\n}", "func PrepareBlock(nodes []RealtimeNode, prevBlock Block, txs Transactions, appHash Digest) Block {\n var lastBlockHash = TmMerkleHash(packMulti(prevBlock.Header))\n var lastCommit = make([]Seal, 0, len(nodes))\n for i, node := range nodes {\n lastCommit[i] = node.SignBlockHash(lastBlockHash)\n }\n\n return Block{\n Header: Header{\n LastBlockHash: lastBlockHash,\n LastCommitHash: TmMerkleHash(packMulti(lastCommit)),\n TxsHash: TmMerkleHash(packMulti(txs)),\n AppHash: appHash,\n },\n LastCommit: lastCommit,\n Txs: txs,\n }\n}", "func (sp *Spectre) newVoter(vh hash.Hash, votedPast *BlockDAG) IBlock {\n\tsb := SpectreBlockData{hash: vh}\n\tsb.parents = []*hash.Hash{}\n\tvhChildren := sp.bd.getBlock(&vh).GetChildren()\n\tfor _, ib := range vhChildren.GetMap() {\n\t\thash := *ib.(IBlock).GetHash()\n\t\tif votedPast.hasBlockById(ib.(IBlock).GetID()) {\n\t\t\tsb.parents = append(sb.parents, &hash)\n\t\t}\n\t}\n\tif votedPast.hasBlockById(votedPast.getBlock(&vh).GetID()) {\n\t\tlog.Error(\"has already voter \", vh)\n\t}\n\t//votedPast.AddBlock(&sb)\n\tblock := Block{hash: *sb.GetHash(), weight: 1}\n\tif sb.parents != nil {\n\t\tblock.parents = NewIdSet()\n\t\tfor _, h := range sb.parents {\n\t\t\thash := *h\n\t\t\tblock.parents.Add(votedPast.getBlock(&hash).GetID())\n\t\t\tparent := votedPast.getBlock(&hash)\n\t\t\tparent.AddChild(&block)\n\t\t}\n\t}\n\tif votedPast.blocks == nil {\n\t\tvotedPast.blocks = map[uint]IBlock{}\n\t}\n\tvotedPast.blocks[block.id] = &block\n\tif votedPast.blockTotal == 0 {\n\t\tvotedPast.genesis = *block.GetHash()\n\t}\n\tvotedPast.blockTotal++\n\tvotedPast.updateTips(&block)\n\tvotedPast.instance.AddBlock(&block)\n\treturn &block\n}", "func Mine(chanLB chan Block, chanT chan Transaction, chanB chan Block, log util.Logger) {\n\tvar t Transaction // incoming transaction\n\tvar lb Block // current last block on the chain\n\tvar block Block // block to mine\n\n\tvar counterInt32 uint32\n\tcounter := []byte{0, 0, 0, 0}\n\tsuccess := false\n\tfor {\n\t\tselect {\n\t\tcase t = <-chanT:\n\t\t\tblock.Transactions.AddTransaction(t)\n\t\t\tlog.Infof(\"MINER RECEIVED TRANSACTION: %v\", t)\n\t\tcase lb = <-chanLB:\n\t\t\tblock = lb.NewBlock()\n\t\t\tlog.Infof(\"MINER RECEIVED BLOCK: %v\", lb)\n\t\tdefault:\n\t\t\tif block.Transactions == nil || &lb == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// increment counter\n\t\t\tcounterInt32 = binary.LittleEndian.Uint32(counter)\n\t\t\tcounterInt32++\n\t\t\tbinary.LittleEndian.PutUint32(counter, counterInt32)\n\n\t\t\tsuccess = ProofOfWork(lb.Hash(), counter)\n\t\t\tif success == true {\n\t\t\t\tblock.Proof = append([]byte(nil), counter...)\n\t\t\t\tchanB <- block\n\t\t\t\tlog.Infof(\"MINED NEW BLOCK: %v\", block)\n\t\t\t\tlb = block\n\t\t\t\tblock = lb.NewBlock()\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *BaseCymbolListener) EnterBlock(ctx *BlockContext) {}", "func (bc *BlockChain) AddBlock(b *Block) {\n\tbc.Blocks = append(bc.Blocks, b)\n}", "func (n *Node) insert(block Block) {\n\tif block.LastHash == n.BlockNode.Hash {\n\t\tn.Children = append(n.Children, &Node{Children: nil, BlockNode: block})\n\t} else if n.Children != nil {\n\t\tfor _, child := range n.Children {\n\t\t\tchild.insert(block)\n\t\t}\n\t}\n}", "func (b *BlockChain) SafeUpdateChain(newB *messages.Block) {\n\tb.mux.Lock()\n\thash := newB.Hash()\n\tb.chain[hash] = newB\n\tif bytes.Equal(newB.PrevHash[:], b.leafHash[:]) {\n\t\tb.leafHash = hash\n\t}\n\tb.mux.Unlock()\n}", "func TestAddBlock(t *testing.T) {\n\tblockchain := Blockchain{}\n\tblockchain.AddBlock(\"hello\")\n\tlastBlock := blockchain[len(blockchain)-1]\n\n\tassertEq(t, lastBlock.Data, \"hello\")\n}", "func ProduceBlock(prevBlockHash string, prevBlock *Block) *Block {\n // This function creates a new block.\n //\n // The implementation is fairly straightforward matter of creating a Block instance and filling in the fields.\n //\n // This function's API is slightly weird, it requires the caller to compute `prevBlockHash = HashBlock(prevBlock)`.\n // Why we don't simplify the API by computing `prevBlockHash` ourselves, reducing the number of arguments\n // from two to one? Two reasons:\n //\n // - Immediately, it makes the placement of the `HashBlock()` debugging output less confusing.\n // - Eventually, we will have more data with the same data flow as `prevBlockHash`, so writing code to route this data\n // now will be useful later.\n\n newBlock := new(Block)\n\n if prevBlock == nil {\n newBlock.PrevHash = prevBlockHash\n newBlock.Height = 1\n } else {\n newBlock.PrevHash = prevBlockHash\n newBlock.Height = prevBlock.Height + 1\n }\n\n return newBlock\n}", "func (d *AddressCacheItem) setBlock(block BlockID) {\n\tif block.Hash == d.hash {\n\t\treturn\n\t}\n\td.hash = block.Hash\n\td.height = block.Height\n\td.utxos = nil\n\td.history.Clear()\n\td.balance = nil\n\td.rows = nil\n}", "func (self *BlockChain) NewBlock(proof int, previous_hash string) {\n\n\t// check if previous hash matches self.hash(self.chain[-1])\n\tt := time.Now()\n\n\tblock := Block{\n\t\tIndex: len(self.Chain) + 1,\n\t\tTimestamp: t.UnixNano(),\n\t\tTransactions: self.CurrentTransactions,\n\t\tProof: proof,\n\t\tPreviousHash: previous_hash}\n\n\t// Reset the current list of transactions\n\tself.CurrentTransactions = nil\n\tself.Chain = append(self.Chain, block)\n}", "func (w *Wallet) connectBlock(b wtxmgr.BlockMeta) {\n\tif !w.ChainSynced() {\n\t\treturn\n\t}\n\n\tbs := waddrmgr.BlockStamp{\n\t\tHeight: b.Height,\n\t\tHash: b.Hash,\n\t}\n\tif err := w.Manager.SetSyncedTo(&bs); err != nil {\n\t\tlog.Errorf(\"Failed to update address manager sync state in \"+\n\t\t\t\"connect block for hash %v (height %d): %v\", b.Hash,\n\t\t\tb.Height, err)\n\t}\n\tw.notifyConnectedBlock(b)\n\tlog.Infof(\"Connecting block %v, height %v\", bs.Hash, bs.Height)\n\n\tw.notifyBalances(bs.Height, wtxmgr.BFBalanceSpendable)\n\n\tisReorganizing, topHash := w.chainSvr.GetReorganizing()\n\n\t// If we've made it to the height where the reorganization is finished,\n\t// revert our reorganization state.\n\tif isReorganizing {\n\t\tif bs.Hash.IsEqual(&topHash) {\n\t\t\tlog.Infof(\"Wallet reorganization to block %v complete\",\n\t\t\t\ttopHash)\n\t\t\tw.chainSvr.SetReorganizingState(false, chainhash.Hash{})\n\t\t}\n\t}\n\n\tif bs.Height >= int32(w.chainParams.CoinbaseMaturity) &&\n\t\tw.StakeMiningEnabled &&\n\t\t!isReorganizing {\n\t\tw.handleTicketPurchases()\n\t}\n\n\t// Insert the block if we haven't already through a relevant tx.\n\terr := w.TxStore.InsertBlock(&b)\n\tif err != nil {\n\t\tlog.Errorf(\"Couldn't insert block %v into database: %v\",\n\t\t\tb.Hash, err)\n\t}\n\n\t// Rollback testing for simulation network, if enabled.\n\tif b.Height < rollbackTestHeight && w.rollbackTesting {\n\t\tdbd, err := w.TxStore.DatabaseDump(b.Height, nil)\n\t\tif err != nil {\n\t\t\tpanicStr := fmt.Sprintf(\"Failed to dump database at connection \"+\n\t\t\t\t\"of block %v (height %v): %v\",\n\t\t\t\tb.Hash,\n\t\t\t\tb.Height,\n\t\t\t\terr.Error())\n\t\t\tpanic(panicStr)\n\t\t}\n\n\t\tif dbd.OneConfBalance != dbd.OneConfCalcBalance {\n\t\t\tlog.Warnf(\"Balance calculations incongruent. The spendable \"+\n\t\t\t\t\"balance was %v, but the recalculated spendable balance \"+\n\t\t\t\t\"was %v\",\n\t\t\t\tdbd.OneConfBalance,\n\t\t\t\tdbd.OneConfCalcBalance)\n\t\t}\n\n\t\tw.rollbackBlockDB[uint32(b.Height)] = dbd\n\t}\n\n\t// We've reached the height to begin the rollback testing from.\n\tif b.Height == rollbackTestHeight && w.rollbackTesting {\n\t\tlog.Infof(\"Height for rollback testing reached, beginning \" +\n\t\t\t\"database evaluations.\")\n\t\tfinalHeight := rollbackTestHeight - rollbackTestDepth\n\t\tfor i := rollbackTestHeight; i >= finalHeight; i-- {\n\t\t\terr := w.TxStore.Rollback(int32(i))\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error rolling back block at height %v: %v\",\n\t\t\t\t\ti, err)\n\t\t\t}\n\n\t\t\trolledbackDb, err := w.TxStore.DatabaseDump(int32(i-1),\n\t\t\t\tw.rollbackBlockDB[uint32(i-1)].BucketUnminedInputs)\n\t\t\tif err != nil {\n\t\t\t\tpanicStr := fmt.Sprintf(\"Failed to dump database at \"+\n\t\t\t\t\t\"disconnection of block height %v: %v\",\n\t\t\t\t\ti,\n\t\t\t\t\terr.Error())\n\t\t\t\tpanic(panicStr)\n\t\t\t}\n\t\t\tis, errStr := w.rollbackBlockDB[uint32(i-1)].Equals(rolledbackDb,\n\t\t\t\ttrue)\n\t\t\tif !is {\n\t\t\t\tlog.Errorf(\"Database incongruencies detected after rolling \"+\n\t\t\t\t\t\"back to block %v!\\n\"+\n\t\t\t\t\t\"%v\",\n\t\t\t\t\ti-1,\n\t\t\t\t\terrStr)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"Rollback to height %v proceeded without error.\",\n\t\t\t\t\ti-1)\n\t\t\t}\n\t\t}\n\n\t\tw.Stop()\n\t}\n}", "func (bc *BlockChain) AddBlock(transactions []*Transaction) {\n\tvar lHash []byte\n\n\t// need get last block's hash\n\terr := bc.db.View(func(tx *bolt.Tx) error {\n\t\t_bkt := tx.Bucket([]byte(blocksBucketName))\n\t\tlHash = _bkt.Get([]byte(lastBlockKey))\n\t\treturn nil\n\t})\n\n\t_newBlock := NewBlock(transactions, lHash)\n\n\terr = bc.db.Update(func(tx *bolt.Tx) error {\n\t\t_bkt := tx.Bucket([]byte(blocksBucketName))\n\n\t\tif err := _bkt.Put(_newBlock.Hash, _newBlock.serialize()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = _bkt.Put([]byte(lastBlockKey), _newBlock.Hash); err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tbc.tip = _newBlock.Hash\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (b *blockEnc) initNewEncode() {\n\tb.recentOffsets = [3]uint32{1, 4, 8}\n\tb.litEnc.Reuse = huff0.ReusePolicyNone\n\tb.coders.setPrev(nil, nil, nil)\n}", "func LoadChain(bc *BlockChain) error {\n\n\tf, err := os.OpenFile(chainOldFilename, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\n\tfor scanner.Scan() {\n\t\tblockLine := scanner.Text()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnewBl, err := BlockFromString(string(blockLine))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// submit block to handler routine\n\t\tbc.bchan <- newBl\n\t}\n\treturn nil\n}" ]
[ "0.70676774", "0.6995445", "0.68848646", "0.68397206", "0.67871076", "0.6565399", "0.63590604", "0.6292728", "0.6123014", "0.60018307", "0.594084", "0.5887955", "0.58096766", "0.58064395", "0.5777828", "0.5749241", "0.56876445", "0.56867546", "0.5637102", "0.56358117", "0.56325454", "0.5612536", "0.5565763", "0.5524517", "0.54845357", "0.54814327", "0.54765433", "0.54670703", "0.5452203", "0.5446106", "0.54107326", "0.54087883", "0.53965884", "0.5392481", "0.53886044", "0.5383055", "0.53618747", "0.5333587", "0.5329613", "0.53151184", "0.5307231", "0.53054947", "0.52921385", "0.5274972", "0.527016", "0.5247053", "0.5244236", "0.5241581", "0.5229069", "0.5218671", "0.5203396", "0.5202073", "0.5200793", "0.519029", "0.5189917", "0.5186201", "0.5177135", "0.5169315", "0.5167922", "0.5161559", "0.5159317", "0.5158207", "0.51568896", "0.51472443", "0.5135973", "0.5129702", "0.51276165", "0.5111125", "0.5109512", "0.5109458", "0.5097924", "0.50805503", "0.5068351", "0.50594", "0.5057605", "0.50566846", "0.50537", "0.50242347", "0.5023415", "0.50229865", "0.50138426", "0.5012041", "0.5008085", "0.5007057", "0.5005267", "0.49968767", "0.49965787", "0.49959543", "0.49850363", "0.4977053", "0.49743316", "0.49609032", "0.49386463", "0.49319315", "0.49213606", "0.4918354", "0.49082175", "0.49073103", "0.49062696", "0.4906188" ]
0.66153383
5
ServerStart starts the web server on the specified TCP port. Blank will default to 8000.
func ServerStart(port string) (string, error) { // List of view handlers handlerStrings = append(handlerStrings, "/", "/blockchain/view/<ID>", "/garage/view/<ID>", "serviceevent/add/", "/vehicle/view/<ID>") http.HandleFunc("/", defaultHandler) // Each call to "/" will invoke defaultHandler http.HandleFunc("/blockchain/view/", blockchainViewHandler) http.HandleFunc("/garage/view/", garageViewHandler) http.HandleFunc("/serviceevent/add/", writeServiceEventHandler) http.HandleFunc("/vehicle/view/", vehicleViewHandler) //log.Fatal(http.ListenAndServe("localhost:"+port, nil)) return "Started on: " + port, http.ListenAndServe("localhost:"+port, nil) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func StartServer() {\n\tif server == nil {\n\t\tGetInstance()\n\t}\n\n\tlog.Println(\"starting server on http://localhost\" + defaultPort)\n\tserver.Run(defaultPort)\n}", "func (o *HttpServer) Start() error {\n\turi := fmt.Sprintf(\"%s:%d\", o.Host, o.Port)\n\tlog.Printf(\"[HTTP] Server listen on %s\\n\", uri)\n\treturn o.Server.ListenAndServe()\n}", "func (s *Server) Start() error {\n\treturn http.ListenAndServe(\":8000\", s.router())\n}", "func StartServer(port int) {\n\thttp.Handle(\"/\", http.FileServer(http.Dir(\"./static\")))\n\terr := http.ListenAndServe(fmt.Sprintf(\":%v\", port), nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (s *Server) Start() error {\n\taddress := s.Address\n\tif address == \"\" {\n\t\taddress = \"0.0.0.0\"\n\t}\n\taddr := fmt.Sprintf(\"%s:%d\", address, s.Port)\n\ts.httpServer = &http.Server{\n\t\tAddr: addr,\n\t\tHandler: s.Routes(),\n\t}\n\treturn s.httpServer.ListenAndServe()\n}", "func Start(port string) {\n\tgo startHTTPServer(port)\n}", "func (self *Server) Start(port int) {\n\tif self.ln != nil {\n\t\tpanic(\"Server already started\")\n\t}\n\tln, err := net.ListenTCP(\n\t\t\"tcp\",\n\t\t&net.TCPAddr{IP: net.ParseIP(\"0.0.0.0\"), Port: port},\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tself.ln = ln\n\tself.listen()\n}", "func (s *Server) Start() error {\n\tlog.Printf(\"Hey there! I'm up and running, and can be accessed at: http://localhost:%d\\n\", s.config.AppPort)\n\treturn s.httpServer.ListenAndServe()\n}", "func (cfg *ConfigServer) Start(port int) {\n\tportString := fmt.Sprintf(\":%d\", port)\n\thttp.ListenAndServe(portString, nil)\n}", "func StartServer(port int) error {\n\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer ln.Close()\n\tutil.ColorPrinter.Cyan(\"[%s]: server side start listening @%d\\n\", util.NowTime(), port)\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo HandleClientConn(conn)\n\t}\n\treturn nil\n}", "func (ts *Server) Start() error {\n\tvar err error\n\tif ts.Handler == nil {\n\t\treturn fmt.Errorf(\"server cannot start; no handler provided\")\n\t}\n\tif ts.Listener == nil && ts.Addr != \"\" {\n\t\tts.Listener, err = net.Listen(\"tcp\", ts.Addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif ts.Listener == nil {\n\t\treturn fmt.Errorf(\"server cannot start; no listener or addr provided\")\n\t}\n\n\tts.logf(\"trace server listening: %s\", ts.Listener.Addr().String())\n\tts.Server = &http.Server{\n\t\tHandler: ts,\n\t}\n\treturn ts.Server.Serve(ts.Listener)\n}", "func Start() {\n\twebServer.Engine.Run(\":\" + strconv.Itoa(cfg.Read().App.WebServerPort))\n}", "func StartWebServer(port int) {\n\tsetuphandlers()\n\tportstring := fmt.Sprintf(\":%d\", port)\n\tfmt.Println(\"Running on \", portstring)\n\tlog.Fatal(http.ListenAndServe(portstring, nil))\n}", "func Start(port string) {\n\ts := &http.Server{\n\t\tAddr: \":\" + port,\n\t\tHandler: &handler{},\n\t\tReadTimeout: 10 * time.Second,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tlog.Fatal(s.ListenAndServe())\n}", "func StartServer() {\n\thandlePesquisa()\n\n\tlog.Info.Println(\"WebServer started...\")\n\thttp.ListenAndServe(\":8080\", httpLogger.WriteLog(http.DefaultServeMux, os.Stdout))\n}", "func (s *Server) Start(ctx context.Context) error {\n\tif s.ln != nil {\n\t\treturn errors.Reason(\"cannot call Start twice\").Err()\n\t}\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", s.cfg.Port))\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.ln = ln\n\n\t_, port, err := net.SplitHostPort(s.ln.Addr().String())\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.cfg.Port, err = strconv.Atoi(port)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, s.cancel = context.WithCancel(ctx)\n\tgo s.serveLoop(ctx)\n\treturn nil\n}", "func (hs *HttpServer) Start() (err error) {\n\tpanic(\"todo - StartServer\")\n\n\t// Start listening to the server port\n\n\t// Accept connection from client\n\n\t// Spawn a go routine to handle request\n\n}", "func (w *Webserver) Start() error {\n\n\t// listenAndServe the server\n\tgo func() {\n\t\tw.logger.Infof(\"Http server listening at %d!\", w.config.Port)\n\t\terr := w.listenAndServe()\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\tw.logger.Errorw(fmt.Sprintf(\"webserver listening at port [%v] stopped\", w.config.Port), \"error\", err.Error())\n\t\t}\n\t}()\n\n\treturn nil\n}", "func Start(port int32) {\n\tvar (\n\t\taddress string\n\t\t//\tclientFS = http.Dir(\"/webclient\")\n\t\terr error\n\t)\n\taddress = fmt.Sprintf(\":%d\", port)\n\thttp.Handle(\"/client\", http.StripPrefix(\"/client\", http.FileServer(http.Dir(\"./client\"))))\n\tlog.Infof(\"Starting webserver on port %d\", port)\n\terr = http.ListenAndServe(address, nil)\n\tlog.Fatal(err)\n}", "func startServer(port string, handler http.Handler) {\n\terr := http.ListenAndServe(port, handler)\n\tif err != nil {\n\t\tlogger.Fatal(\"ListenAndServe: \", err)\n\t}\n}", "func (srv *Server) Start() error {\n\treturn srv.app.Listen(srv.config.BindIP + \":\" + strconv.Itoa(srv.config.Port))\n}", "func (ser *Server) Start() error {\n\tlog.Printf(\"System webapp start at %s\", ser.addr)\n\treturn manners.ListenAndServe(ser.addr, ser.m)\n}", "func StartWebServer(port string) {\n\tlogrus.Infof(\"Starting Web Server Port[%v] \\n\", port)\n\n\t// init routes\n\tr := NewRouter()\n\thttp.Handle(\"/\", r)\n\n\terr := http.ListenAndServe(\":\" + port, nil)\n\tif err != nil {\n\t\tlogrus.Printf(\"Error starting server %v\", err.Error())\n\t}\n\n}", "func (s *Server) Start(ctx context.Context, listenPort uint) error {\n\tif err := s.prepare(ctx, listenPort); err != nil {\n\t\treturn err\n\t}\n\n\tif s.enableAPI {\n\t\treturn s.srv.ListenAndServe()\n\t}\n\n\treturn nil\n}", "func StartServer() {\n\tfmt.Println(\"Server is started at 8082\")\n\thttp.ListenAndServe(\":8082\", r)\n}", "func (s *Server) Start() error {\n\taddress := fmt.Sprintf(\"%s:%v\", s.config.IP, s.config.Port)\n\tlog.Println(\"Server starting at: \", address)\n\n\treturn http.ListenAndServe(address, s.env.Middleware.Then(s.env.Router.InternalRouter()))\n}", "func (s *Server) Start(host string, port string) error {\n\treturn s.router.Start(fmt.Sprintf(\"%s:%s\", host, port))\n}", "func (s *Server) Start() {\n\tlog.Infof(\"Starting http server on port %d...\", s.port)\n\n\tgo s.server.ListenAndServe()\n}", "func (s *TodoServer) StartServer() error {\n\treturn s.httpServer.ListenAndServe()\n}", "func Start(port string) {\n\tif port == \"\" {\n\t\tport = portDefault\n\t}\n\tlog.Printf(\"Starting new server on port %v.\\n\", port)\n\n\tport = fmt.Sprintf(\":%v\", port)\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\ts := grpc.NewServer()\n\tproto.RegisterSumServiceServer(s, &server{})\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}", "func DummyServerStart(t *testing.T) {\n\thttp.HandleFunc(\"/\", dummyServerResponse)\n\tgo func() {\n\t\thttp.ListenAndServe(\":8000\", nil)\n\t}()\n}", "func (s *Server) Start() {\n\tif s.URL != \"\" {\n\t\tpanic(\"Server already started\")\n\t}\n\ts.URL = s.Listener.Addr().String()\n\ts.goServe()\n\tif *serve != \"\" {\n\t\tfmt.Fprintln(os.Stderr, \"grpctest: serving on\", s.URL) // nolint: gas\n\t\tselect {}\n\t}\n}", "func (hs *HttpServer) Start() (err error) {\n\t//panic(\"todo - StartServer\")\n\n\t// Start listening to the server port\n\n\t// Accept connection from client\n\n\t// Spawn a go routine to handle request\n\tport := hs.ServerPort\n\thost := \"0.0.0.0\"\n\t//delim := \"/r/n\"\n\tln, err := net.Listen(\"tcp\", host+port)\n\tdefer ln.Close()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tlog.Println(\"Listening to connections at '\"+host+\"' on port\", port)\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil{\n\t\t\tlog.Panicln(err)\n\t\t}\n\t\t\n\t\tgo hs.handleConnection(conn)\n\t}\n\n\treturn err\n\n\n}", "func (s *Server) Start() error {\n\ts.configureRouter()\n\n\t// Another stuff\n\n\ts.logger.Logf(\"INFO Server is starting at port %v...\\n\", s.config.BindAddr)\n\n\treturn http.ListenAndServe(s.config.BindAddr, s.router)\n}", "func (s *Server) Start() error {\n\treturn s.e.StartServer(s.httpServer)\n}", "func StartServer() {\n\t// Get server config\n\taddress := os.Getenv(\"SERVER_ADDR\")\n\tport := os.Getenv(\"SERVER_PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\n\t// Open ports and start listening for connections.\n\taddr, err := net.ResolveTCPAddr(\"tcp\", fmt.Sprintf(\"%s:%s\", address, port))\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"failed\")\n\t}\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"failed\")\n\t}\n\tlog.Info(\"server started\")\n\n\t// Loop to make sure we can keep accepting connections\n\tfor {\n\t\tconn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Fatal(\"failed\")\n\t\t}\n\n\t\t// Register method listeners\n\t\tif err := methods.Register(conn); err != nil {\n\t\t\tlog.WithError(err).Fatal(\"failed\")\n\t\t}\n\t}\n}", "func (s *Server) Start() error {\n\tif len(s.srv.Addr) == 0 {\n\t\treturn errors.New(\"server missing address\")\n\t}\n\n\tif s.srv.Handler == nil {\n\t\treturn errors.New(\"server missing handler\")\n\t}\n\n\treturn s.srv.ListenAndServe()\n}", "func (s *Server) Start() error {\n\treturn http.ListenAndServe(s.listenAddr, s.router)\n}", "func Start() error {\r\n\tconfig := DefaultServer.Options()\r\n\tlog.Logf(\"Starting server %s id %s\", config.Name, config.Id)\r\n\treturn DefaultServer.Start()\r\n}", "func (s *Server) Start() error {\n\tif len(s.srv.Addr) == 0 {\n\t\treturn errors.New(\"Server missing address\")\n\t}\n\n\tif s.srv.Handler == nil {\n\t\treturn errors.New(\"Server missing handler\")\n\t}\n\n\treturn s.srv.ListenAndServe()\n}", "func (s *HttpServer) Start() error {\n\n\tif err := http.ListenAndServe(s.Config.Host+\":\"+s.Config.HTTPPort, s.ServeMux); err != nil {\n\t\tlog.Error().Err(err).Msg(\"Unable to start http server\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func StartServer(port int) {\n\twsHandler := clientWebsocketHandler{upgrader: defaultUpgrader}\n\n\trouter := mux.NewRouter()\n\trouter.Handle(\"/client_ws\", wsHandler)\n\trouter.Handle(\"/d/{downloadId}\", downloadHandler{})\n\n\taddr := fmt.Sprintf(\":%d\", port)\n\thttp.ListenAndServe(addr, router)\n}", "func Start() error {\n\tconfig := DefaultServer.Options()\n\tconfig.Logger.Logf(log.InfoLevel, \"Starting server %s id %s\", config.Name, config.Id)\n\treturn DefaultServer.Start()\n}", "func (s *Server) Start(port string, wTimeout, rTimeout, idleTimeout time.Duration) error {\n\thttp.Handle(\"/\", applyMiddlewares(http.HandlerFunc(s.Router), noPanicMiddleware(s.Log), corsMiddleware(\"*\")))\n\n\tsrv := http.Server{\n\t\tAddr: fmt.Sprintf(\":%s\", port),\n\t\tWriteTimeout: wTimeout,\n\t\tReadTimeout: rTimeout,\n\t\tIdleTimeout: idleTimeout,\n\t}\n\n\treturn srv.ListenAndServe()\n}", "func StartServer(s *server.ScrapeServer) {\n\thttp.HandleFunc(\"/\", s.Handle())\n\thttp.ListenAndServe(\":8080\", nil)\n}", "func (s *Server) Start() {\n\tserver := http.Server{\n\t\tAddr: s.Port,\n\t\tHandler: handlers.LoggingHandler(s.Logger, s.Router),\n\t}\n\n\tfmt.Println(\"Running\")\n\tserver.ListenAndServe()\n}", "func (s *Server) Start() {\n\tlog.Println(\"Web server started at \" + s.configurationService.Address())\n\tlog.Fatal(http.ListenAndServe(s.configurationService.Address(), s.router()))\n}", "func (s *Server) Start() error {\n\ts.router = configureRouter(s.Config.StaticDir)\n\ts.Logger.Printf(\"serving %v at /static/\", s.Config.StaticDir)\n\ts.httpListener = s.configureHTTPListener()\n\n\tgo func() {\n\t\terr := s.httpListener.ListenAndServe()\n\t\tif err != nil {\n\t\t\t//Normal graceful shutdown error\n\t\t\tif err.Error() == \"http: Server closed\" {\n\t\t\t\ts.Logger.Info(err)\n\t\t\t} else {\n\t\t\t\ts.Logger.Fatal(err)\n\t\t\t}\n\t\t}\n\t}()\n\ts.Logger.Printf(\"listening on %v\", s.Config.Address)\n\treturn nil\n}", "func Start(port int) {\n\tlog.Printf(\"Listening on port %v\", port)\n\n\tportStr := fmt.Sprintf(\":%v\", port)\n\tlog.Fatal(http.ListenAndServe(portStr, router))\n}", "func (s *WebServer) Start() error {\n\treturn s.ListenAndServe()\n}", "func (s *server) Start() error {\n\treturn s.server.ListenAndServe()\n}", "func StartServer(listenAddr *string, server *http.Server) {\n\tlog.Println(\"Server is ready to handle requests at\", *listenAddr)\n\tif err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\tlog.Fatalf(\"Could not listen on %s: %v\\n\", *listenAddr, err)\n\t}\n}", "func Start(address string) error {\n\terr := applicationServer.Start(address)\n\treturn err\n}", "func (s *Server) Start() error {\n\ts.logger = s.configureLogger(s.config.LogDebug)\n\n\ts.configureRouter()\n\n\tif err := s.configureStore(); err != nil {\n\t\treturn err\n\t}\n\n\ts.logger.Logf(\"[INFO] Server is starting at %v...\\n\", s.config.BindAddr)\n\n\treturn http.ListenAndServe(s.config.BindAddr, s.router)\n}", "func (hSvr *HTTPServer) Start(_ context.Context) error {\n\tgo func() {\n\t\tif err := hSvr.svr.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.L().Fatal(\"Node failed to serve.\", zap.Error(err))\n\t\t}\n\t}()\n\treturn nil\n}", "func StartWebserver(port string) {\n\tlog.Info(\"Starting service at port: \" + port)\n\tr := routes.NewRouter()\n\tsrv := &http.Server{\n\t\tAddr: \":\" + port,\n\t\tHandler: r,\n\t\t// Good practice: enforce timeouts for servers you create!\n\t\tWriteTimeout: 15 * time.Second,\n\t\tReadTimeout: 15 * time.Second,\n\t}\n\n\tgo func() {\n\t\t// service connections\n\t\tif err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Fatalf(\"listen: %s\\n\", err)\n\t\t}\n\t}()\n\n\t// gracefule shutdown\n\t// Wait for interrupt signal to gracefully shutdown the server with\n\t// a timeout of 5 seconds.\n\tquit := make(chan os.Signal)\n\tsignal.Notify(quit, os.Interrupt)\n\t<-quit\n\tlog.Info(\"Shutdown Server ...\")\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\tif err := srv.Shutdown(ctx); err != nil {\n\t\tlog.Fatal(\"Server Shutdown:\", err)\n\t}\n\tlog.Info(\"Server exiting\")\n}", "func StartWebserver() {\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}", "func (s *Server) Start() error {\n\tif s.Handler == nil {\n\t\treturn errors.New(\"No server handler set\")\n\t}\n\n\tif s.listener != nil {\n\t\treturn errors.New(\"Server already started\")\n\t}\n\n\taddr := s.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thostname, _ := os.Hostname()\n\ts.serverInstanceID = fmt.Sprintf(\"%x\", md5.Sum([]byte(hostname+addr)))\n\n\ts.listener = listener\n\ts.serverGroup = &sync.WaitGroup{}\n\ts.clientsGroup = make(chan bool, 50000)\n\ts.Handler = &serverHandler{s.Handler, s.clientsGroup, s.serverInstanceID}\n\n\ts.serverGroup.Add(1)\n\tgo func() {\n\t\tdefer s.serverGroup.Done()\n\n\t\terr := s.Serve(listener)\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.lastError = err\n\t\t}\n\t}()\n\n\treturn nil\n}", "func (s *server) Start() {\n\ts.httpServer = &http.Server{Addr: s.listenAddr}\n\n\tgo func() {\n\t\ts.logger.Printf(\"listening on \\\"%s\\\"\\n\", s.httpServer.Addr)\n\n\t\terr := s.httpServer.ListenAndServe()\n\t\tif err != nil && err != http.ErrServerClosed {\n\t\t\ts.logger.Fatalf(\"could not listen on \\\"%s\\\": %v\\n\", s.httpServer.Addr, err)\n\t\t}\n\n\t\ts.done <- true\n\t}()\n}", "func (n *Server) Start() error {\n\tlog.Infof(\"Attach server listening on %s:%d\", n.ip, n.port)\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", fmt.Sprintf(\"%s:%d\", n.ip, n.port))\n\n\tn.l, err = net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Attach server error %s: %s\", addr, errors.ErrorStack(err))\n\t\tlog.Errorf(\"%s\", err)\n\t\treturn err\n\t}\n\n\t// starts serving requests immediately\n\tn.connServer = NewConnector(n.l)\n\n\treturn nil\n}", "func (srv *Server) StartServer() {\n\thttp.HandleFunc(\"/\", srv.rpcHandler)\n\tlog.Fatal(http.ListenAndServe(srv.addr, nil))\n}", "func (server *HTTPRouterServer) Start(port int) error {\n\tif server.srv != nil {\n\t\tserver.Stop()\n\t}\n\terr := server.startREST()\n\tif err != nil {\n\t\treturn err\n\t}\n\tserver.srv = &http.Server{Addr: \":\" + strconv.Itoa(port), Handler: server.router}\n\treturn server.srv.ListenAndServe()\n}", "func (srv *Server) StartListen() {\n\tvar err error\n\tsrv.Listener, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", srv.Host, srv.Port))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"🔓 Listening on %s:%s\", srv.Host, srv.Port)\n\thttp.Serve(srv.Listener, nil)\n}", "func (s *Server) Start() {\n\tlog.Printf(\"Listening and serving HTTP on %d\\n\", s.c.Port)\n\tgo func() {\n\t\tif err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Fatalf(\"ListenAndServe, err: %s\", err.Error())\n\t\t}\n\t}()\n\ts.register()\n}", "func (c *CartServer) Start() error {\n\trouter := c.InitializeHandler()\n\thttp.Handle(\"/\", router)\n\tc.printStartMsg()\n\n\treturn http.ListenAndServe(fmt.Sprintf(\":%d\", c.config.Port), nil)\n}", "func Start(port int) {\n\tlog := new(model.Log)\n\n\tserver := rpc.NewServer()\n\tregisterLog(server, log)\n\n\tlisten, err := net.Listen(\"tcp\", \":\"+toolbox.IntToString(port))\n\ttoolbox.CheckError(err, 1)\n\n\tserver.Accept(listen)\n}", "func (s *Server) Start() {\n\tlog.Println(\"Starting webhook receiver on port 8080...\")\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't start server: %s\", err)\n\t}\n}", "func (s *Server) Start() error {\n\taddress := fmt.Sprintf(\"%s:%d\", s.Config.Host, s.Config.Port)\n\tlog.Infof(\"Listening on %s\", address)\n\treturn s.Router.Start(address)\n}", "func (web *WebServer) Start() {\n\tlog.Println(http.ListenAndServe(web.listen, web.router))\n}", "func (s *Server) Start() error {\n\t// Check if the server is running\n\tif s.IsRunning() {\n\t\treturn errors.New(\"Attempted to start a server that is already running at address: \" + s.instance.Addr)\n\t}\n\n\t// Set routes and middleware\n\ts.SetRoutes()\n\ts.GetInstance().Handler = middleware.NewMiddleware().Then(s.GetInstance().Handler)\n\n\tm := \"Listening for requests...\"\n\tlog.Info(m)\n\n\tgo s.GetInstance().ListenAndServe()\n\n\ts.running = true\n\n\treturn nil\n}", "func StartServer(s *http.Server, log *logrus.Logger) {\n\tlog.Infof(\"Starting Server on %s\\n\", s.Addr)\n\tif err := s.ListenAndServe(); err != nil {\n\t\tlog.Warnf(\"Server shutted down [%s]\", err)\n\t\tpanic(err)\n\t}\n}", "func StartServer() {\n\tr := gin.Default()\n\n\tcorsCfg := cors.DefaultConfig()\n\tcorsCfg.AllowOrigins = []string{\"http://localhost:1234\"}\n\tr.Use(cors.New(corsCfg))\n\n\tapi := r.Group(\"/api\")\n\t{\n\t\tapi.Any(\"/graphql\", graphQL)\n\t\tapi.GET(\"/players\", players)\n\t\tapi.GET(\"/player_datas\", playerDatas)\n\t}\n\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tport = \"8080\"\n\t}\n\tr.Run(fmt.Sprintf(\":%s\", port))\n}", "func (srv *MonitorServer) Start() {\n\terr := srv.ListenAndServe()\n\tif err != nil {\n\t\tlog.Logger.Error(\"MonitorServer.Start():err in http.ListenAndServe():%s\", err.Error())\n\t\tabnormalExit()\n\t}\n}", "func (server *Server) Start() {\n\tmux := http.NewServeMux()\n\n\tfileServer := server.attachStaticFileServer(mux)\n\tserver.attachSystemJSRewriteHandler(mux)\n\tserver.attachCustomHandlers(mux)\n\n\tif server.hub != nil {\n\t\t// add HMR support\n\t\tserver.attachIndexInjectionListener(mux, fileServer)\n\t\tserver.attachWebSocketListeners(mux, server.hub)\n\t\tgo server.hub.run()\n\t}\n\n\tserver.srv = &http.Server{\n\t\tAddr: makeServerAddress(server.port),\n\t\tHandler: mux,\n\t}\n\n\tif err := server.srv.ListenAndServe(); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (srv Web) Start() error {\n\tfmt.Printf(\"Starting service on port %s\\n\", srv.Settings.Port)\n\treturn http.ListenAndServe(srv.Settings.Port, srv.Router())\n}", "func (s *server) Start(stop <-chan struct{}) error {\n\tlistener, err := newListener(s.bindAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tserver := http.Server{\n\t\tHandler: s.mux,\n\t}\n\t// Run the server\n\tgo func() {\n\t\tlog.Info(\"starting http server\")\n\t\tif err := server.Serve(listener); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Error(err, \"http server error\")\n\t\t}\n\t}()\n\n\t// Shutdown the server when stop is close\n\t<-stop\n\treturn server.Shutdown(context.Background())\n}", "func StartServer(bindAddress string) {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/\", HomeHandler)\n\tr.HandleFunc(\"/read\", ReadAllPostsHandler)\n\tr.HandleFunc(\"/read/{id:[a-z0-9]+}\", ReadPostHandler)\n\tr.HandleFunc(\"/write\", WritePostHandler)\n\thttp.Handle(\"/\", r)\n\n\tfmt.Printf(\"listening on %s...\", bindAddress)\n\terr := http.ListenAndServe(bindAddress, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"Error listening to the port: \" + err.Error())\n\t}\n}", "func StartHttpServer() {\n\thttp.HandleFunc(\"/\", HandleFuncRoot)\n\taddr := \":5000\"\n\tDEBUG(\"开始启动http:[%v]\", addr)\n\terr := http.ListenAndServe(addr, nil)\n\tif err != nil {\n\t\tERROR(\"http启动失败:%v\", err)\n\t\tpanic(err)\n\t}\n}", "func (server *testHTTPServerImpl) Start() {\n\tbinding := fmt.Sprintf(\":%d\", server.GetPort())\n\tsrv := &http.Server{\n\t\tAddr: binding,\n\t\tHandler: server.router,\n\t\tReadHeaderTimeout: 5 * time.Second,\n\t}\n\tgo func() {\n\t\trootFolder, err := GetRootFolder()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to get root folder of project: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tcertFile := fmt.Sprintf(\"%s/testutils/test-server.pem\", rootFolder)\n\t\tkeyFile := fmt.Sprintf(\"%s/testutils/test-server.key\", rootFolder)\n\t\tif err = srv.ListenAndServeTLS(certFile, keyFile); !errors.Is(err, http.ErrServerClosed) {\n\t\t\tlog.Fatalf(\"Failed to start http server using binding %s: %s\", binding, err)\n\t\t}\n\n\t}()\n\tserver.httpServer = srv\n\n\tserver.waitForServerAlive()\n}", "func Start(ip string, port int) {\n\t// Start the TCP server\n\taddress := fmt.Sprintf(\"%s:%d\", ip, port)\n\tserver, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Infof(\"TCP Server Listening on %v\", address)\n\tdefer server.Close()\n\n\thandleConnections(server)\n}", "func StartServer(port string) {\n\tr := gin.New()\n\tr.GET(\"/:p1\", middleWare)\n\tr.GET(\"/:p1/:p2\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7\", middleWare)\n\tr.GET(\"/:p1/:p2/:p3/:p4/:p5/:p6/:p7/:p8\", middleWare)\n\tr.Run(\":\" + port)\n}", "func (s *Server) Start() error {\n\ts.RegisterHTTPHandlers()\n\tlog.Print(fmt.Sprintf(\"Listening HTTP on: %s\", s.url))\n\n\thandler := CORSWrap(s.router)\n\treturn http.ListenAndServe(s.url, handler)\n}", "func (s *SimpleServer) Start() {\n\ts.WaitGroup.Add(1)\n\tgo func() {\n\t\tgo s.waitShutdown()\n\t\tlogging.Info(fmt.Sprintf(\"Server is starting on: %s\", fmt.Sprintf(\"http://%s:%d\", config.Host, config.Port)))\n\t\terr := s.ListenAndServe()\n\t\tif err != nil {\n\t\t\tlogging.Errors(fmt.Sprintf(\"Listen and serve: %v\", err))\n\t\t}\n\t}()\n}", "func (s *Service) Start() error {\n\tl, err := net.Listen(\"tcp\", s.addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.s.Serve(l)\n}", "func (f *Frontend) Start() error {\n\n\tlistenAddr := fmt.Sprintf(\"%s:%d\", f.cfg.Host, f.cfg.Port)\n\toriginalListener, err := net.Listen(\"tcp\", listenAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsl, err := stoppableListener.New(originalListener)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver := http.Server{Handler: context.ClearHandler(f.router)}\n\n\tstop := make(chan os.Signal)\n\tsignal.Notify(stop, syscall.SIGINT)\n\tvar wg sync.WaitGroup\n\tgo func() {\n\t\twg.Add(1)\n\t\tdefer wg.Done()\n\t\tserver.Serve(sl)\n\t}()\n\n\tf.log.Println(\"Start serving HTTP requests at \", listenAddr)\n\tselect {\n\tcase signal := <-stop:\n\t\tf.log.Println(\"Got signal: \", signal)\n\t}\n\tf.log.Println(\"Stopping listener\")\n\tsl.Stop()\n\tf.log.Println(\"Waiting on server\")\n\twg.Wait()\n\n\treturn nil\n}", "func (s *Server) Start() (err error) {\n\tlog.Infof(\"Starting server in home directory: %s\", s.HomeDir)\n\n\ts.serveError = nil\n\n\tif s.listener != nil {\n\t\treturn errors.New(\"server is already started\")\n\t}\n\n\t// Initialize the server\n\terr = s.init(false)\n\tif err != nil {\n\t\terr2 := s.closeDB()\n\t\tif err2 != nil {\n\t\t\tlog.Errorf(\"Close DB failed: %s\", err2)\n\t\t}\n\t\treturn err\n\t}\n\n\t// Register http handlers\n\ts.registerHandlers()\n\n\tlog.Debugf(\"%d CA instance(s) running on server\", len(s.caMap))\n\n\t// Start operations server\n\terr = s.startOperationsServer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.Operations.RegisterChecker(\"server\", s)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tfor _, ca := range s.caMap {\n\t\tstartNonceSweeper(ca)\n\t}\n\n\t// Start listening and serving\n\terr = s.listenAndServe()\n\tif err != nil {\n\t\terr2 := s.closeDB()\n\t\tif err2 != nil {\n\t\t\tlog.Errorf(\"Close DB failed: %s\", err2)\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (this *Client) StartServer() error {\n\tif this.server {\n\t\tIP := fmt.Sprintf(\":%d\", PORT)\n\t\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", IP)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlistener, err := net.ListenTCP(\"tcp\", tcpAddr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo this.receive(conn)\n\t\t}\n\t} else {\n\t\treturn errors.New(\"Cannot start server as client.\")\n\t}\n}", "func Start(portNumber int, configFile string) {\n\tconfig := GetConfigFromJSON(configFile)\n\thttp.HandleFunc(\"/\", MainHandler(config))\n\thttp.ListenAndServe(\":\"+strconv.Itoa(portNumber), nil)\n}", "func (m *Server) Start() error {\n\tgo func() {\n\t\tif err := http.Serve(m.Listener, m); err != http.ErrServerClosed {\n\t\t\tlog.Printf(\"Unable to listen and serve: %v\", err)\n\t\t}\n\t}()\n\treturn nil\n}", "func Start(ls *lockservice.SimpleLockService, scfg lockservice.SimpleConfig) error {\n\n\tIP := scfg.IP()\n\tIP = strings.TrimPrefix(IP, \"http://\")\n\tport := scfg.Port()\n\n\tif err := checkValidPort(port); err != nil {\n\t\treturn err\n\t}\n\n\trouter := mux.NewRouter()\n\n\trouter = routing.SetupRouting(ls, router)\n\n\tserver := &http.Server{\n\t\tHandler: router,\n\t\tAddr: IP + \":\" + port,\n\t}\n\n\tgo gracefulShutdown(server)\n\n\tlog.Println(\"Starting Server on \" + IP + \":\" + port)\n\treturn server.ListenAndServe()\n}", "func startServer(port int, url string) {\n\t/*\n\t\tChecks the port and url variables values\n\t*/\n\tif port <= 0 || len(url) == 0 {\n\t\tpanic(\"invalid port or url\")\n\t}\n\n\t/*\n\t\tDefines and prints the variable fullURL\n\t*/\n\tfullURL := fmt.Sprintf(\"%s:%d\", url, port)\n\tfmt.Printf(\"starting server on %s\\n\", fullURL)\n\n\t/*\n\t\tDefines a Router\n\t*/\n\trm := mux.NewRouter()\n\n\t/*\n\t\tinitial splash screen\n\t*/\n\n\t/*\n\t\tDefines routes in the API\n\t*/\n\trm.HandleFunc(\"/\", Root).Methods(\"GET\")\n\trm.HandleFunc(\"/getjson\", GetJSONResponse).Methods(\"GET\")\n\n\t/*\n\t\tStarts the API\n\t\tSet the port\n\t*/\n\thttp.ListenAndServe(fullURL, &MyServer{rm})\n\n}", "func Start() {\n\taddr := fmt.Sprintf(\"%v:%v\", webConfig.Ip4address, webConfig.Ip4port)\n\tserver := &http.Server{\n\t\tAddr: addr,\n\t\tHandler: nil,\n\t\tReadTimeout: 60 * time.Second,\n\t\tWriteTimeout: 60 * time.Second,\n\t}\n\n\t// We don't use ListenAndServe because it lacks a way to close the listener\n\tlog.LogInfo(\"HTTP listening on TCP4 %v\", addr)\n\tvar err error\n\tlistener, err = net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.LogError(\"HTTP failed to start TCP4 listener: %v\", err)\n\t\t// TODO More graceful early-shutdown procedure\n\t\tpanic(err)\n\t}\n\n\terr = server.Serve(listener)\n\tif shutdown {\n\t\tlog.LogTrace(\"HTTP server shutting down on request\")\n\t} else if err != nil {\n\t\tlog.LogError(\"HTTP server failed: %v\", err)\n\t}\n}", "func (server *Server) Start() {\n\trouter := mux.NewRouter()\n\n\trouter.HandleFunc(\"/\", errorHandler(server.root)).Methods(\"GET\")\n\trouter.HandleFunc(\"/stock\", errorHandler(server.listInventorySupplyHandlerFunc)).Methods(\"GET\")\n\trouter.HandleFunc(\"/sentViaAmazon\", errorHandler(server.createFulfillmentHandlerFunc)).Methods(\"POST\")\n\n\thttp.Handle(\"/\", router)\n\n\tfmt.Println(\"listening on\", server.Port)\n\thttp.ListenAndServe(fmt.Sprintf(\":%d\", server.Port), nil)\n}", "func (srv *server) Start() {\n\tgo srv.Serve()\n}", "func (s *server) StartServer(address string) {\n\tzap.L().Info(\"started running server\",\n\t\tzap.String(\"address\", address))\n\t_ = http.ListenAndServe(address, s.Router)\n}", "func (self *Proxy) Start() error {\n\n\tself.srv = http.Server{\n\t\tAddr: self.Bind,\n\t\tHandler: self,\n\t}\n\n\tlog.Printf(\"Listening for HTTP client requests at %s.\\n\", self.Bind)\n\n\treturn self.srv.ListenAndServe()\n}", "func StartServer() {\n\tvar wait time.Duration\n\tflag.DurationVar(&wait, \"graceful-timeout\", time.Second*15, \"the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m\")\n\tflag.Parse()\n\n\tr := mux.NewRouter()\n\troutes.RegisterRouter(r)\n\t//check db before staring web\n\tdb.STRG.Migrator()\n\tport := os.Getenv(\"PORT\")\n\taddress := \":\" + port\n\tsrv := &http.Server{\n\t\tAddr: address,\n\t\tWriteTimeout: time.Second * 15,\n\t\tReadTimeout: time.Second * 15,\n\t\tIdleTimeout: time.Second * 60,\n\t\tHandler: r, // Pass our instance of gorilla/mux in.\n\t}\n\n\tfmt.Println(\"Starting Server\")\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\t<-c\n\tctx, cancel := context.WithTimeout(context.Background(), wait)\n\tdefer cancel()\n\tsrv.Shutdown(ctx)\n\tlog.Println(\"shutting down\")\n\tos.Exit(0)\n}", "func (server *HelloServer) StartHelloServer() error {\n\thttp.HandleFunc(\"/\", webHandler)\n\tlogger.Logger.Info(\"Server listening on port 7100\")\n\treturn server.HTTPServer.ListenAndServe()\n}", "func (server *Server) Start() {\n\tr := mux.NewRouter()\n\tserver.registerRoutes(r)\n\n\thttp.Handle(\"/\", r)\n\tlogger.Info(\"HTTP server is starting using port: %v\", server.Config.Port)\n\thttp.ListenAndServe(server.port(), nil)\n}", "func HttpServerStart(addr string, apiUrl string) {\n\tproblems.InitAPIServer(apiUrl)\n\thttp.HandleFunc(\"/\", RequestHandler)\n\tlog.Fatal(http.ListenAndServe(addr, nil))\n}" ]
[ "0.7371509", "0.73683625", "0.7337591", "0.73110557", "0.7226168", "0.7212318", "0.7199945", "0.71704507", "0.7159049", "0.7156385", "0.7153561", "0.7147691", "0.7074961", "0.7063656", "0.7048088", "0.70398515", "0.7033529", "0.70296556", "0.70292014", "0.7026401", "0.6990443", "0.6989921", "0.696811", "0.6966138", "0.6965518", "0.69644386", "0.6959781", "0.6941537", "0.6889215", "0.6870619", "0.6836664", "0.68362164", "0.68355125", "0.68353194", "0.6832284", "0.68247193", "0.68246585", "0.6821894", "0.6796414", "0.67866963", "0.67843276", "0.67742455", "0.6761826", "0.67577946", "0.67567205", "0.6754573", "0.67527395", "0.6743056", "0.67185485", "0.6713443", "0.66962034", "0.6694019", "0.6673398", "0.6672012", "0.6670502", "0.6660672", "0.6658581", "0.6657374", "0.665544", "0.664512", "0.6644695", "0.66392165", "0.6629129", "0.66181076", "0.6614428", "0.6608155", "0.66039515", "0.660383", "0.6600899", "0.65957123", "0.6588896", "0.6571217", "0.65703773", "0.6567468", "0.6547291", "0.65454483", "0.65350354", "0.6531342", "0.6531268", "0.651251", "0.648644", "0.6477848", "0.6469072", "0.64668465", "0.64666283", "0.6462573", "0.6457961", "0.6452779", "0.644678", "0.6442236", "0.6440931", "0.64340836", "0.64309967", "0.6422865", "0.6417132", "0.6413669", "0.6404198", "0.63884926", "0.63762414", "0.6373388" ]
0.79115456
0
Default handler to catchall
func defaultHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "INFO: Default Handler called from %s. Please try alternative methods such as \n %s", r.RemoteAddr, handlerStrings) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CatchAllHandler(w http.ResponseWriter, r *http.Request) {\n\t// 1. Get the redirect URL out of the config\n\tif !viper.IsSet(\"default_url\") {\n\t\t// The reason for using StatusNotFound here instead of StatusInternalServerError\n\t\t// is because this is a catch-all function. You could come here via various\n\t\t// ways, so showing a StatusNotFound is friendlier than saying there's an\n\t\t// error (i.e. the configuration is missing)\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\t// 2. If it exists, redirect the user to it\n\thttp.Redirect(w, r, viper.GetString(\"default_url\"), http.StatusMovedPermanently)\n}", "func catchAllHandler(w http.ResponseWriter, r *http.Request) {\n\tp := path.Clean(\"/\" + r.URL.Path)\n\tif p == \"/\" {\n\t\tp += \"index\"\n\t}\n\tp = filepath.Join(config.Dir, filepath.FromSlash(p))\n\n\tif _, err := os.Stat(p); os.IsNotExist(err) {\n\t\tserveTemplate(w, r)\n\t\treturn\n\t}\n\n\thttp.ServeFile(w, r, p)\n}", "func NewCatchAllHandler(base HandlerBase) CatchAllHandler {\n\treturn CatchAllHandler{HandlerBase: base}\n}", "func defaulthandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Hello surfer!\")\n}", "func defaultHandler(w http.ResponseWriter, req *http.Request) {\n\tif req.URL.String() == \"/favicon.ico\" {\n\t\thttp.NotFound(w, req)\n\t\treturn\n\t}\n\tparts := strings.Split(strings.Trim(req.URL.Path, \"/\"), \"/\")\n\tquery := req.URL.Query()\n\tswitch parts[0] {\n\tcase \"all\":\n\t\t{\n\t\t\thandleAll(query.Get(\"bucket\"), w)\n\t\t}\n\tcase \"prefix\":\n\t\t{\n\t\t\thandlePrefix(query.Get(\"bucket\"), query.Get(\"prefix\"), w)\n\t\t}\n\tcase \"range\":\n\t\t{\n\t\t\thandleRange(query.Get(\"bucket\"), query.Get(\"start\"), query.Get(\"end\"), w)\n\t\t}\n\tcase \"find\":\n\t\t{\n\t\t\thandleFind(query.Get(\"bucket\"), query.Get(\"filter\"), w)\n\t\t}\n\tcase \"findPrefix\":\n\t\t{\n\t\t\thandleFindPrefix(query.Get(\"bucket\"), query.Get(\"prefix\"), query.Get(\"filter\"), w)\n\t\t}\n\tcase \"findRange\":\n\t\t{\n\t\t\thandleFindRange(query.Get(\"bucket\"), query.Get(\"start\"), query.Get(\"end\"), query.Get(\"filter\"), w)\n\t\t}\n\tcase \"backup\":\n\t\t{\n\t\t\thandleBackup(w)\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tif len(parts) < 2 {\n\t\t\t\thttp.Error(w, \"malformed request\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thandleDefaultRequest(strings.Join(parts[0:len(parts)-1], \".\"), parts[len(parts)-1], req, w)\n\t\t}\n\t}\n}", "func AllHandler(c *gin.Context) {\n\tl.Info(\"ii\")\n\tl.Warn(\"ww\")\n\tl.Error(\"ee\")\n\tc.JSON(200, gin.H{\n\t\t\"message\": \"ok\",\n\t})\n}", "func catchAllHandler(w http.ResponseWriter, r *http.Request) {\n http.Redirect(w, r, \"http://www.crunchydata.com\", 303)\n}", "func (w *Web) defaultHandler(wr http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(wr, \"No site configured on %s\", r.Host)\n}", "func defaultHandler(w http.ResponseWriter, r *http.Request) {\r\n\tfmt.Fprintf(w, \"OK\")\r\n}", "func (wa *webapi) defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusNotFound)\n}", "func (af *AF) defaultSignalHandle() {\n\taf.HandleSignal(func(af *AF) {\n\t\tlog.Println(fmt.Sprintf(\"AF server is shutdown pid:%d\", os.Getpid()))\n\t\taf.Stop()\n\t}, syscall.SIGINT, syscall.SIGTERM)\n\taf.HandleSignal(func(af *AF) {\n\t\tlog.Println(fmt.Sprintf(\"AF server is reload pid:%d err:%v\", os.Getpid(), af.Reload()))\n\t}, syscall.SIGUSR2)\n}", "func defaultHandle(writer http.ResponseWriter, request *http.Request) {\n\tlog.Println(\"Not valid route\")\n\thttp.Error(writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n}", "func DefaultHandler(w http.ResponseWriter, req *http.Request) {\n\t// Do nothing and close connection.\n\treturn\n}", "func (s *HTTPRouter) HandlerAny(path string, handler http.Handler) {\n\tfor _, method := range anyMethods {\n\t\ts.Handler(method, path, handler)\n\t}\n}", "func defaultHandler(ctx context.Context, input *HandlerInput) {\n\tinput.logger.doPrint(ctx, input)\n}", "func defaultHandler(w http.ResponseWriter, r *http.Request) {\n fmt.Fprint(w, \"Hello!\");\n}", "func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }", "func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }", "func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }", "func (s *Server) handleWhatever() {}", "func DefaultHTTPHandler(hndl http.Handler) Detector {\n\tif hndl == nil {\n\t\thndl = http.DefaultServeMux\n\t}\n\thandler := ListenServerHandler(&http.Server{\n\t\tHandler: hndl,\n\t})\n\treturn FallthroughDetector(handler)\n}", "func Default() Handler {\n\treturn &defaultHandler{}\n}", "func (s *HTTPRouter) HandleAny(path string, handle gcore.Handle) {\n\tfor _, method := range anyMethods {\n\t\ts.Handle(method, path, handle)\n\t}\n}", "func defaultHandler(w http.ResponseWriter, r *http.Request) {\n // this is the default handler that program defaults to\n http.Redirect(w, r, \"/login/\", http.StatusSeeOther)\n}", "func rootHandler(w http.ResponseWriter, r *http.Request) {\n\tparts := strings.Split(r.URL.Path, \"/\")\n\tif r.URL.Path == \"/igcinfo/api/\" {\n\t\tinfoHandler(w, r)\n\t\treturn\n\t} else if r.URL.Path == \"/igcinfo/api/igc/\" {\n\t\tigcHandler(w, r)\n\t\treturn\n\t} else if id, err := uuid.Parse(parts[4]); strings.HasPrefix(r.URL.Path, \"/igcinfo/api/igc/\") && err == nil && len(parts) < 6 {\n\t\ttrackHandler(w, r, id)\n\t\treturn\n\t} else if id, err := uuid.Parse(parts[4]); strings.HasPrefix(r.URL.Path, \"/igcinfo/api/igc/\") && err == nil && len(parts[5]) > 0 {\n\t\ttrackFieldHandler(w, r, id, parts[5])\n\t\treturn\n\t}\n\n\thttp.NotFound(w, r)\n}", "func defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"govtil/net/server %s!\", r.URL.Path[1:])\n}", "func (serv *Server) ANY(url string, handlers ...Handler) {\n\tserv.Handle(\"ANY\", url, handlers...)\n}", "func (r RegexRouter) HandleAny(regex string, handler http.Handler) {\n\tr.Handle(regex, map[string]http.Handler{\n\t\tanyHTTPMethod: handler,\n\t})\n}", "func emptyHandler(w http.ResponseWriter, req *http.Request) {}", "func (r *Router) handle(c *Ctx) {\n\tvar handler HandlerFunc\n\treq := c.Request()\n\tw := c.Writer()\n\tpath := req.URL.Path\n\tmethod := req.Method\n\tres := r.trie.Match(path)\n\n\tif res.Node == nil {\n\t\t// FixedPathRedirect or TrailingSlashRedirect\n\t\tif res.TSR != \"\" || res.FPR != \"\" {\n\t\t\treq.URL.Path = res.TSR\n\t\t\tif res.FPR != \"\" {\n\t\t\t\treq.URL.Path = res.FPR\n\t\t\t}\n\t\t\tcode := 301\n\t\t\tif method != \"GET\" {\n\t\t\t\tcode = 307\n\t\t\t}\n\t\t\thttp.Redirect(w, req, req.URL.String(), code)\n\t\t\treturn\n\t\t}\n\t\tif r.noRoute == nil {\n\t\t\thttp.Error(w, fmt.Sprintf(`\"%s\" not implemented`, path), 501)\n\t\t\treturn\n\t\t}\n\t\thandler = r.noRoute\n\t} else {\n\t\t// ok := false\n\t\thd := res.Node.GetHandler(method)\n\t\thandler, _ = hd.(HandlerFunc)\n\t\t// handler = r.wrapHandler(hd)\n\t\t// if !ok {\n\t\t// \tpanic(\"handler error\")\n\t\t// }\n\t\tif handler == nil {\n\t\t\t// OPTIONS support\n\t\t\tif method == http.MethodOptions {\n\t\t\t\tw.Header().Set(\"Allow\", res.Node.GetAllow())\n\t\t\t\tw.WriteHeader(204)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif r.noMethod == nil {\n\t\t\t\t// If no route handler is returned, it's a 405 error\n\t\t\t\tw.Header().Set(\"Allow\", res.Node.GetAllow())\n\t\t\t\thttp.Error(w, fmt.Sprintf(`\"%s\" not allowed in \"%s\"`, method, path), 405)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thandler = r.noMethod\n\t\t}\n\t}\n\n\tif len(res.Params) != 0 {\n\t\tc.params = res.Params\n\t}\n\tc.handlers = append(c.handlers, handler)\n\tc.Next()\n}", "func (hr *HttpRequest) SetToDefaultResponseHandler() {\n\thr.handlers = []ResponseStatusHandler{handler()}\n}", "func (r *Route) Any(handler http.Handler) *Route {\n\tr.handlers[methodAny] = handler\n\treturn r\n}", "func handleDefault(w http.ResponseWriter, req *http.Request) {\n\tw.WriteHeader(http.StatusNotFound)\n\tfmt.Fprintf(w, \"No such page: %s\\n\", req.URL)\n}", "func (rm *RouterMux) HandleDefault(handler HandlerFunction, description ...string) {\n\trm.defaultHandler = NewHandler(handler, \"\", description...)\n}", "func (h CatchAllHandler) Handle() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\th.WriteErrorResponse(r.Context(), w, &apperrors.UnknownRouteError{Path: r.URL.Path})\n\t}\n}", "func rootHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Image Server\", http.StatusNotImplemented)\n}", "func (r *Router) Any(path string, handle HandleFunc) {\n\tr.register(path, http.MethodDelete, handle)\n\tr.register(path, http.MethodGet, handle)\n\tr.register(path, http.MethodHead, handle)\n\tr.register(path, http.MethodOptions, handle)\n\tr.register(path, http.MethodPatch, handle)\n\tr.register(path, http.MethodPost, handle)\n\tr.register(path, http.MethodPut, handle)\n\tr.register(path, http.MethodTrace, handle)\n}", "func (h AppServer) Handler (w http.ResponseWriter, r *http.Request) {\n\twasHandled := false\n\turlPath := r.URL.Path\n\tl := len(urlPath)\n\tif l > 0 {\n\t\tif urlPath[l-1:l] != \"/\" {\n\t\t\t// tack on a trailing slash\n\t\t\turlPath = urlPath + \"/\"\n\t\t}\n\t\tfmt.Println(\"appServer handler path=\", urlPath)\n\t\t\n\t\tfor p := range h.Handlers {\n\t\t\tif len(urlPath) >= len(p) &&\turlPath[:len(p)] == p {\n\t\t\t\twasHandled = true\n\t\t\t\tphf := h.Handlers[p]\n\t\t\t\tDispatchMethod(phf, w, r)\n\t\t\t} \n\t\t}\n\t}\n\tif !wasHandled {\n\t\t// not specific handler, assume it's a file\n\t\tif h.FileServerInst != nil {\n\t\t\tDispatchMethod(h.FileServerInst, w, r)\n\t\t} else {\n\t\t\thttp.Error(w, \"File not Found\", http.StatusNotFound)\n\t\t}\n\t}\n\n}", "func all(w http.ResponseWriter, r *http.Request) {\n\t// URL not supported\n\thttp.NotFound(w, r)\n}", "func (handlers *Handlers) rootHandler(w http.ResponseWriter, r *http.Request) {\n\t_, err := w.Write([]byte(\"OK!!\\n\"))\n\tif err != nil {\n\t\tlog.Println(err.Error() + \" Failed to write response bytes in root handler\")\n\t}\n}", "func (r *router) handle(c *Context){\n\tn, params := r.getRoute(c.Method, c.Path)\n\tif n != nil {\n\t\tc.Params = params\n\t\t// connection between Context and Router!\n\t\t// it's important\n\t\tkey := c.Method + \"-\" + n.pattern\n\t\t// 两种函数都放到一起了\n\t\tc.handlers = append(c.handlers, r.handlers[key])\n\t\t//r.handlers[key](c)\n\t}else{\n\t\tc.handlers = append(c.handlers, func(c *Context){\n\t\t\tc.String(http.StatusNotFound, \"404 NOT FOUND%s\\n\", c.Path)\n\t\t})\n\t}\n\t//放在这里一起执行, 中间执行, 其逻辑导致\"并行\"效果\n\tc.Next()\n}", "func init() {\n\thttp.HandleFunc(\"/\", errorAdapter(rootHandler))\n}", "func DefaultHandler(w http.ResponseWriter, _ *http.Request) {\r\n\tlog.Print(\"In DefaultHandler\")\r\n\r\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\r\n\tw.WriteHeader(http.StatusNotFound)\r\n\tw.Write( []byte (\"This is the tech_test service\"))\r\n}", "func BindAllBasicHandlers(app *app.App) {\n\tBindAuth(app)\n\tBindSelect(app)\n\tBindEcho(app)\n\tBindPing(app)\n\tBindShutdown(app)\n\tBindCommand(app)\n\tBindKeys(app)\n\tBindExists(app)\n\tBindExpire(app)\n\n\tBindNotFound(app)\n\tBindError(app)\n}", "func handler(w http.ResponseWriter, r *http.Request) {\n\thandlerReal(false, w, r)\n}", "func HandleAll(api *api.API) {\n\n\twrapperLogOn := alice.New(api.ParseHandler)\n\thttp.Handle(\"/logon\", wrapperLogOn.ThenFunc(api.LogOn))\n\n\twrapper := alice.New(api.ParseHandler, api.LogonHandler)\n\n\thttp.Handle(\"/getBooks\", wrapper.ThenFunc(api.GetBooks))\n\thttp.Handle(\"/getRoles\", wrapper.ThenFunc(api.GetRoles))\n\thttp.Handle(\"/getUsers\", wrapper.ThenFunc(api.GetUsers))\n\n\thttp.Handle(\"/updateUsers\", wrapper.ThenFunc(api.UpdateUsers))\n\thttp.Handle(\"/updateRoles\", wrapper.ThenFunc(api.UpdateRoles))\n\thttp.Handle(\"/updateBooks\", wrapper.ThenFunc(api.UpdateBooks))\n\n\thttp.Handle(\"/insertBooks\", wrapper.ThenFunc(api.InsertBooks))\n\thttp.Handle(\"/insertUsers\", wrapper.ThenFunc(api.InsertUsers))\n\thttp.Handle(\"/insertRoles\", wrapper.ThenFunc(api.InsertRoles))\n\n\thttp.Handle(\"/deleteRoles\", wrapper.ThenFunc(api.DeleteRoles))\n\thttp.Handle(\"/deleteBooks\", wrapper.ThenFunc(api.DeleteBooks))\n\thttp.Handle(\"/deleteUsers\", wrapper.ThenFunc(api.DeleteUsers))\n}", "func (s *Server) handler(req *http.Request) http.Handler {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\tfor _, r := range s.rules {\n\t\tif r.Match(req) {\n\t\t\treturn r.Handler()\n\t\t}\n\t}\n\treturn nil\n}", "func DefaultHandler() log15.Handler {\n\treturn defaultHandler\n}", "func homeHandler(w http.ResponseWriter, req *http.Request){\n\terrorHandler(w, req, http.StatusNotFound)\n}", "func (f *Fastglue) Any(path string, h FastRequestHandler) {\n\tf.Router.GET(path, f.handler(h))\n\tf.Router.POST(path, f.handler(h))\n\tf.Router.PUT(path, f.handler(h))\n\tf.Router.DELETE(path, f.handler(h))\n}", "func defaultPanicHandler() {\n\tdefer defaultNotifier.dontPanic()\n\n\terr := panicwrap.BasicMonitor(func(output string) {\n\t\ttoNotify, err := errors.ParsePanic(output)\n\n\t\tif err != nil {\n\t\t\tdefaultNotifier.Config.log(\"bugsnag.handleUncaughtPanic: %v\", err)\n\t\t}\n\t\tNotify(toNotify, SeverityError, Configuration{Synchronous: true})\n\t})\n\n\tif err != nil {\n\t\tdefaultNotifier.Config.log(\"bugsnag.handleUncaughtPanic: %v\", err)\n\t}\n}", "func Handler(w http.ResponseWriter, r *http.Request) {\n\n\tdefer catchPanic(w, r)\n\n\tif basePath := \"/Foogazi\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"GET\" {\n\n\t\ttools.ShortenPath(basePath, r)\n\n\t\tw.Write([]byte(\"Hello\"))\n\t\treturn\n\t}\n\tif basePath := \"/Foo\"; strings.Contains(r.URL.Path, basePath) {\n\n\t\tif basePath := \"/Foo/Bar\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"GET\" {\n\n\t\t\ttools.ShortenPath(basePath, r)\n\n\t\t\tw.Write([]byte(r.URL.Path))\n\t\t\treturn\n\t\t}\n\n\t\ttools.ShortenPath(basePath, r)\n\n\t\tw.Write([]byte(\"Hello world\"))\n\t\treturn\n\t}\n\tif basePath := \"/hello\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"GET\" {\n\n\t\ttools.ShortenPath(basePath, r)\n\n\t\tw.Write([]byte(\"Hello World\"))\n\t\treturn\n\t}\n\tif basePath := \"/hello_POST\"; strings.Contains(r.URL.Path, basePath) && r.Method == \"POST\" {\n\n\t\ttools.ShortenPath(basePath, r)\n\t\tprintln(\"Request to Hello_post\")\n\t\tw.Write([]byte(\"Hello World\"))\n\t\treturn\n\t}\n}", "func setuphandlers() {\n\thttp.HandleFunc(\"/\", rootHandler)\n\thttp.HandleFunc(\"/status\", statusHandler)\n\thttp.HandleFunc(\"/stats\", statsHandler)\n\thttp.HandleFunc(\"/request\", requestHandler)\n}", "func FourOhFourHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"404\")\n\thttp.Error(w, `Y u do this`, http.StatusNotFound)\n}", "func (g *RouterGroup) ANY(url string, handler ...Handler) *RouterGroup {\n\tg.app.routeANY = true\n\tg.AppendReqAndResp(url, \"post\", handler)\n\tg.AppendReqAndResp(url, \"get\", handler)\n\tg.AppendReqAndResp(url, \"delete\", handler)\n\tg.AppendReqAndResp(url, \"put\", handler)\n\tg.AppendReqAndResp(url, \"options\", handler)\n\tg.AppendReqAndResp(url, \"head\", handler)\n\treturn g\n}", "func (s *HTTPRouter) HandlerFuncAny(path string, handler http.HandlerFunc) {\n\tfor _, method := range anyMethods {\n\t\ts.HandlerFunc(method, path, handler)\n\t}\n}", "func init() {\n\thttp.HandleFunc(\"/notify\", errorAdapter(notifyHandler))\n\thttp.HandleFunc(\"/processnotification\", notifyProcessorHandler)\n}", "func indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\tfmt.Fprint(w, \"Hello, World!\")\n}", "func logAllRequestsMiddleware(next http.Handler) http.Handler {\r\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\tlogger.Info(\"%s %s\", r.Method, r.URL.Path)\r\n\r\n\t\tnext.ServeHTTP(w, r)\r\n\t})\r\n}", "func DefaultOptionsHandler(route *Route) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tmethods := []string{}\n\t\tfor key, _ := range route.handlers {\n\t\t\tmethods = append(methods, key)\n\t\t}\n\t\tw.Header().Add(\"Allow\", strings.Join(methods, \", \"))\n\t})\n}", "func (rm *RouterMux) DefaultHandler() *Handler {\n\treturn rm.defaultHandler\n}", "func (h *Handler) Accept() {\n}", "func (s *Server) handleRootRequest(w http.ResponseWriter, req *http.Request) {\n if req.URL.Path != \"/\" {\n http.NotFound(w, req)\n return\n }\n\n http.Redirect(w, req, \"/ui/\", http.StatusFound)\n}", "func (engine *Engine) Any(relativePath string, handlers ...HandlerFunc) IRoutes {\n\tengine.handle(http.MethodGet, relativePath, handlers)\n\tengine.handle(http.MethodPost, relativePath, handlers)\n\tengine.handle(http.MethodPut, relativePath, handlers)\n\tengine.handle(http.MethodPatch, relativePath, handlers)\n\tengine.handle(http.MethodHead, relativePath, handlers)\n\tengine.handle(http.MethodOptions, relativePath, handlers)\n\tengine.handle(http.MethodDelete, relativePath, handlers)\n\tengine.handle(http.MethodConnect, relativePath, handlers)\n\tengine.handle(http.MethodTrace, relativePath, handlers)\n\treturn engine\n}", "func (srv *Server) ApplyHandlers() {\n\tsrv.router.Handle(\"/*\", http.FileServer(http.Dir(\"./web\")))\n\tsrv.router.Get(\"/socket\", srv.socketHandler)\n}", "func main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Printf(\"Runtime error caught: %v\", r)\n\t\t}\n\t}()\n\n\thttp.HandleFunc(\"/\", sonMode.Welcome)\n\thttp.HandleFunc(\"/signIn\", sonMode.SignInHandle)\n\thttp.HandleFunc(\"/managerSignIn\", sonMode.ManagerSignInHandle)\n\thttp.HandleFunc(\"/superManagerSignIn\", sonMode.SuperManagerSignInHandle)\n\thttp.HandleFunc(\"/signOut\", sonMode.SignOutHandle)\n\thttp.HandleFunc(\"/signUp\", sonMode.SignUpHandle)\n\thttp.HandleFunc(\"/homepage\", sonMode.HomepageHandle)\n\thttp.HandleFunc(\"/profile\", sonMode.ProfileHandle)\n\thttp.HandleFunc(\"/transfer\", sonMode.TransferHandle)\n\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}", "func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)", "func defaultHandler(w http.ResponseWriter, r *http.Request) {\n\tnode := node.GetNodeName()\n\tw.Write([]byte(\"Hello bubble tea server !! Node name: \" + node))\n}", "func (r *router) handle(c *Context) {\n\tn, params := r.getRoute(c.Method, c.Path) //if request method and path exist, return pattern of node and params\n\tif n != nil {\n\t\tc.Params = params\n\t\tc.handlers = append(c.handlers, n.handler) //insert handler after middleware\n\t} else {\n\t\tc.handlers = append(c.handlers, func(c *Context) {\n\t\t\tc.String(http.StatusNotFound, \"404 NOT FOUND: %s\\n\", c.Path)\n\t\t})\n\t}\n\tc.Next()\n}", "func (mux *ServeMux) handler(host, path string) (h http.Handler, pattern string) {\n\tmux.mu.RLock()\n\tdefer mux.mu.RUnlock()\n\n\t// Host-specific pattern takes precedence over generic ones\n\tif mux.hosts {\n\t\th, pattern = mux.match(host + path)\n\t}\n\tif h == nil {\n\t\th, pattern = mux.match(path)\n\t}\n\tif h == nil {\n\t\th, pattern = http.NotFoundHandler(), \"\"\n\t}\n\treturn\n}", "func NewAllowallHandler() *AllowAllHandler {\n\thandler := &AllowAllHandler{logger: log.WithField(\"handler\", \"allowall\")}\n\treturn handler\n}", "func (app *App) ANY(url string, handler ...Handler) *App {\n\tapp.routeANY = true\n\tapp.AppendReqAndResp(url, \"post\", handler)\n\tapp.AppendReqAndResp(url, \"get\", handler)\n\tapp.AppendReqAndResp(url, \"delete\", handler)\n\tapp.AppendReqAndResp(url, \"put\", handler)\n\tapp.AppendReqAndResp(url, \"options\", handler)\n\tapp.AppendReqAndResp(url, \"head\", handler)\n\treturn app\n}", "func (sim *SimService) handle_all_the_things(w http.ResponseWriter, r *http.Request) {\n\twat := r.URL.Path[1:]\n\tfmt.Println(\"Handling\", wat)\n\n\tmethod, exists := sim.methods[wat]\n\n\t// check some stuff\n\tif !exists {\n\t\thttp.Error(w, \"Method does not exist: \"+wat, http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif method.method_type != r.Method {\n\t\thttp.Error(w, \"Method type should be \"+method.method_type, http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// check params\n\tr.ParseMultipartForm(10 * 1024) // implicitly does ParseForm() in case there are some url params\n\n\tfor _, param := range method.required_parameters {\n\t\tif _, present := r.Form[param]; !present {\n\t\t\thttp.Error(w, \"Missing required parameter: \"+param, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// we're ok to handle it\n\tmethod.function(sim, w, r.Form)\n}", "func (h *MxHandler) Handler(pattern *checkSelection, handler http.Handler) {\n\th.routes = append(h.routes, &route{pattern, handler})\n}", "func otherwiseHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/\" {\n\t\tnotFoundHandler(w, r)\n\t} else {\n\t\twellcomeHandler(w, r)\n\t}\n}", "func DefaultTraceHandler(route *Route) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdump, _ := httputil.DumpRequest(r, false)\n\t\tw.Write(dump)\n\t})\n}", "func PanicHandler() http.Handler { return panicHandler{} }", "func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {\n\tmux.mu.RLock()\n\tdefer mux.mu.RUnlock()\n\n\t// Host-specific pattern takes precedence over generic ones\n\tif mux.hosts {\n\t\th, pattern = mux.match(host + path)\n\t}\n\tif h == nil {\n\t\th, pattern = mux.match(path)\n\t}\n\tif h == nil {\n\t\th, pattern = NotFoundHandler(), \"\"\n\t}\n\treturn\n}", "func (m *Minion) defaultForbiddenHandler(w http.ResponseWriter, r *http.Request) {\n\tm.HTML(w, r, http.StatusForbidden, m.ForbiddenTemplate, V{})\n}", "func (this *Route) All(handlers ...HTTPHandler) *Route {\n\n\tfor _, handler := range handlers {\n\t\tvar l = newLayer(\"/\", handler, true)\n\t\tl.method = \"\"\n\t\tthis.stack = append(this.stack, l)\n\t}\n\n\tthis.allMethods = true\n\treturn this\n}", "func notFoundHandler(w http.ResponseWriter, r *http.Request) {\n\tglog.V(0).Infof(\"unsupported %s %s\", r.Method, r.RequestURI)\n\twriteErrorResponse(w, s3err.ErrMethodNotAllowed, r.URL)\n}", "func (r *Router) handler(h Handler) http.Handler {\n\treturn &handler{h}\n}", "func (r *Router) handler(h Handler) http.Handler {\n\treturn &handler{h}\n}", "func Exe(handler Handler) {\n\thandler.ServeHTTP(\"test response\", \"test request\")\n}", "func main() {\n\tlog.Fatal(listenAndServeFunc(\":3003\", handler.GetMux()))\n}", "func (h *Handler) UnknownHandler(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(http.StatusNotFound)\n}", "func (router *Router) Any(relativePath string, handler Handler, decorators ...Decorator) {\n\trouter.createRouter(\"any\", relativePath, handler, \"\", decorators...)\n}", "func MuxServe(w http.ResponseWriter, r *http.Request) {\n\tfor _, rule := range rules {\n\t\tif rule.patternReg.MatchString(r.URL.Path) {\n\t\t\trule.handler(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// if we get here, there is no matching handler, so its a 404\n\thttp.Error(w, \"No handler for this URL\", http.StatusNotFound)\n}", "func (ctx *Context) handle() {\n\thandlers := append(ctx.g.handlers, ctx.g.defaultHandler)\n\tfor _, h := range handlers {\n\t\tvals, err := ctx.Call(h, ctx.g.Injector)\n\n\t\t// If a Handler returns values, and if the first value is a glue.AfterHandler\n\t\t// defer it to allow post-request logic\n\t\tif len(vals) > 0 {\n\t\t\tif vals[0].Type() == reflect.TypeOf(AfterHandler(nil)) {\n\t\t\t\tafterFn := vals[0].Interface().(AfterHandler)\n\t\t\t\tdefer afterFn(*ctx)\n\t\t\t} else if len(vals) == 1 {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It is instead of type: %+v\\n\", AfterHandler(nil), vals[0].Type())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It instead returned %d values: %+v\", AfterHandler(nil), len(vals), vals)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif ctx.rw.WroteHeader() {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func registerAllHandlers(mux *http.ServeMux) {\n\tmux.HandleFunc(\"/\", handleRoot)\n\tpodnodesselector.Register(mux)\n}", "func main() {\n\n\t// use custom handler\n\n\txhandler := routes.RegexpHandler{}\n\n\txhandler.HandleRegexp(\"/abc\\\\=.+\", handleAbc)\n\n\txhandler.HandleRegexp(\"/\", handleRoot)\n\n\thttp.Handle(\"/\", xhandler)\n\n\t// use net/http handler\n\n\thttp.HandleFunc(\"/zzz/\", handleSpec)\n\n\thttp.HandleFunc(\"/sublvl\", func(w http.ResponseWriter, rq *http.Request) {\n\t\thandleRoot(w, rq)\n\t})\n\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}", "func (h *Handler) handleRequests() {\n\thttp.HandleFunc(\"/\", homePage)\n\thttp.HandleFunc(\"/customers\", h.returnAllCustomers)\n\tlog.Fatal(http.ListenAndServe(frontendPort, nil))\n}", "func handlerICon(w http.ResponseWriter, r *http.Request) {}", "func SetRootHandler(path string) {\n\troothandlerpath = path\n}", "func (e *Engine) setupFallback() {\n\te.srv.HTTPErrorHandler = func(err error, c echo.Context) {\n\t\tif err != echo.ErrNotFound {\n\t\t\treturn\n\t\t}\n\t\turi := genericPath(c.Request().RequestURI)\n\t\tfs, err := os.Stat(uri)\n\t\tif err != nil {\n\t\t\tc.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\tif fs.IsDir() {\n\t\t\t// if working at pwd, capture all dirs\n\t\t\tif len(e.dirs) == 1 && e.dirs[0] == \".\" {\n\t\t\t\t// check if file excluded\n\t\t\t\tif isExclude(uri) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := e.doDispatch(c, fs); err != nil {\n\t\t\t\t\tc.Error(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// only capture missing dir when serving pwd\n\t\t\t// return for any other dirs\n\t\t\treturn\n\t\t}\n\n\t\t// capture any files here\n\t\terr = e.doServeFile(uri)(c)\n\t\tif err != nil {\n\t\t\tc.Error(err)\n\t\t}\n\t}\n}", "func defaultHandle(ctx context.Context, channel *amqp.Channel) error {\n\tlog.Logger.Info(\n\t\t\"default rabbitmq consume handler\",\n\t\tzap.String(\"service\", serviceName),\n\t)\n\n\t<-ctx.Done()\n\treturn errors.New(\"service ends\")\n}", "func DefaultHandlerFunc(info Info) bool {\n\tfmt.Fprintf(os.Stderr, \"Panic: %v\\n%s\", info.Info, info.StackTrace)\n\treturn true\n}", "func FirstHandler(r *http.Request, w http.ResponseWriter) {\n\n}", "func index_handler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Whoa go is cool\")\n}", "func (handler MetricsHandler) Any(c echo.Context) error {\n\tswitch c.Get(\"Method\").(string) {\n\tcase http.MethodPost:\n\t\treturn handler.Create(c)\n\t}\n\treturn RawResponse(c, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n}" ]
[ "0.74647164", "0.71886647", "0.67791533", "0.65686786", "0.65400976", "0.64790803", "0.63966566", "0.62958306", "0.6246133", "0.623425", "0.62189925", "0.621134", "0.6204758", "0.61410385", "0.61060303", "0.60277355", "0.60198945", "0.60198945", "0.60198945", "0.5942256", "0.59254307", "0.59197193", "0.59077483", "0.58979875", "0.5887674", "0.5886398", "0.58772814", "0.5859761", "0.5850582", "0.58492047", "0.58286166", "0.5817487", "0.58173704", "0.58117586", "0.5806589", "0.5794238", "0.5774084", "0.5737365", "0.57332855", "0.5721477", "0.57059354", "0.57053655", "0.57038844", "0.5698092", "0.56577903", "0.56503326", "0.5646113", "0.5640133", "0.5604046", "0.5590138", "0.5580919", "0.5577176", "0.5563933", "0.5560194", "0.5538174", "0.553683", "0.5535729", "0.5526889", "0.5523667", "0.5521364", "0.5517038", "0.5497107", "0.5496137", "0.5491954", "0.54906327", "0.54872125", "0.54824144", "0.54809374", "0.5469346", "0.54657704", "0.5447131", "0.5445206", "0.5434202", "0.5429277", "0.54254365", "0.5425302", "0.5412554", "0.54096705", "0.54056764", "0.54019547", "0.5400992", "0.5397053", "0.5397053", "0.53914964", "0.53866327", "0.53864294", "0.5381603", "0.5377641", "0.5373646", "0.5371798", "0.5367849", "0.5366357", "0.53568786", "0.53556466", "0.53501886", "0.53479475", "0.53433233", "0.5340886", "0.5329956", "0.53234065" ]
0.6887508
2
Handler to manage requests to /blockchain/ subchain
func blockchainViewHandler(w http.ResponseWriter, r *http.Request) { // Take the URL beyond /blockchain/ and split into request and value strings requestAction := strings.Split(r.URL.String(), "/") requestItem, err := strconv.Atoi(requestAction[3]) requestItem = requestItem - 1 if err != nil { log.Println("INFO: Unable to convert argument to integer, assume this is a request for entire chain") } if requestItem == -1 { //Request item is invalid so display that blockID only blockString, err := json.MarshalIndent(Blockchain, "", "\t") if err != nil { log.Println("ERROR: blockchainViewHandler(): Cannot print Blockchain") } fmt.Fprintf(w, "\n %s", blockString) } else { blockItemString, _ := json.MarshalIndent(Blockchain[requestItem], "", "\t") // Do nothing if index too high fmt.Fprintf(w, "\n %s.", blockItemString) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func handleGetBlockchain(w http.ResponseWriter, r *http.Request) {\n\n\t// create a json representation of the current blockchain with indentations\n\tbytes, err := json.MarshalIndent(model.Blockchain, \"\", \" \")\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tio.WriteString(w, string(bytes))\n}", "func (s *Service) chainStateHandler(w http.ResponseWriter, _ *http.Request) {\n\tjsonhttp.OK(w, s.batchStore.GetChainState())\n}", "func handleRequests() {\n r := mux.NewRouter()\n\n // Paths\n r.HandleFunc(\"/mine\", mineBlockHandler).Methods(\"POST\")\n r.HandleFunc(\"/{index}\", getBlockHandler)\n r.HandleFunc(\"/\", getBlockchainHandler)\n\n // Run the server\n port := \":10000\"\n fmt.Println(\"\\nListening on port \" + port[1:])\n log.Fatal(http.ListenAndServe(port, r))\n}", "func (srv *Server) consensusHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tcbid := srv.cs.CurrentBlock().ID()\n\tcurrentTarget, _ := srv.cs.ChildTarget(cbid)\n\twriteJSON(w, ConsensusGET{\n\t\tHeight: srv.cs.Height(),\n\t\tCurrentBlock: cbid,\n\t\tTarget: currentTarget,\n\t})\n}", "func (h HTTPHandler) HandleMerklePath(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\t// find the index to operate on\n\tvars := mux.Vars(r)\n\tblockID, err := hex.DecodeString(vars[\"blockId\"])\n\ttxID, err := hex.DecodeString(vars[\"txId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"invalid block transaction ID\\\"}\", 400)\n\t\treturn\n\t}\n\n\tblockchainPeer, err := getBlockchainById(h.bf, vars[\"blockchainId\"])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\tif blockchainPeer == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"blockchain doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tvar block *blockchain.Block\n\n\terr = blockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\tb := dbtx.Bucket([]byte(blockchain.BlocksBucket))\n\n\t\tif b == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleMerklePath\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Warn(\"block bucket doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\n\t\tencodedBlock := b.Get(blockID)\n\n\t\tif encodedBlock == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleMerklePath\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Error(\"block doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\t\tblock = blockchain.DeserializeBlock(encodedBlock)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"block doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tblockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\t// Assume bucket exists and has keys\n\t\tc := dbtx.Bucket([]byte(blockchain.TransactionsBucket)).Cursor()\n\n\t\tprefix := block.Hash\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tblock.Transactions = append(block.Transactions, blockchain.DeserializeTransaction(v))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tverificationPath := block.GetMerkleTree().GetVerificationPath(txID)\n\tif verificationPath == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"couldn't create the merkle tree for this transation\\\"}\", 400)\n\t\treturn\n\t}\n\n\tverificationPathString := make(map[int]string)\n\tfor index, hash := range verificationPath {\n\t\tverificationPathString[index] = fmt.Sprintf(\"%x\", hash)\n\t}\n\n\trv := struct {\n\t\tStatus string `json:\"status\"`\n\t\tMerklePath map[int]string `json:\"verificationPath\"`\n\t}{\n\t\tStatus: \"ok\",\n\t\tMerklePath: verificationPathString,\n\t}\n\n\tmustEncode(w, rv)\n}", "func (api *API) consensusHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tcbid := api.cs.CurrentBlock().ID()\n\tcurrentTarget, _ := api.cs.ChildTarget(cbid)\n\tWriteJSON(w, ConsensusGET{\n\t\tSynced: api.cs.Synced(),\n\t\tHeight: api.cs.Height(),\n\t\tCurrentBlock: cbid,\n\t\tTarget: currentTarget,\n\t\tDifficulty: currentTarget.Difficulty(),\n\t})\n}", "func (api *API) consensusHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tcbid := api.cs.CurrentBlock().ID()\n\tcurrentTarget, _ := api.cs.ChildTarget(cbid)\n\tWriteJSON(w, ConsensusGET{\n\t\tSynced: api.cs.Synced(),\n\t\tHeight: api.cs.Height(),\n\t\tCurrentBlock: cbid,\n\t\tTarget: currentTarget,\n\t})\n}", "func (pb *PutBlock) SubChainAddress() string { return pb.subChainAddress }", "func handleGetData(request []byte, bc *Blockchain) {\n\tvar buff bytes.Buffer\n\tvar payload getdata\n\n\tbuff.Write(request[commandLength:])\n\tdec := gob.NewDecoder(&buff)\n\terr := dec.Decode(&payload)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif payload.Type == \"block\" {\n\t\tblock, err := bc.GetBlock([]byte(payload.ID))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tsendBlock(payload.AddrFrom, &block)\n\t}\n\n\tif payload.Type == \"tx\" {\n\t\ttxID := hex.EncodeToString(payload.ID)\n\t\ttx := mempool[txID]\n\n\t\tsendTx(payload.AddrFrom, &tx)\n\t\t// delete(mempool, txID)\n\t}\n}", "func innerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\n\t//group := e.Group(\"/openplatform/internal/anti/fraud\",idfSvc.Verify)\n\tgroup := e.Group(\"/openplatform/internal/antifraud\")\n\t{\n\n\t\tgroup.GET(\"/qusb/info\", qusBankInfo) //题库单条信息\n\t\tgroup.GET(\"/qusb/list\", qusBankList) //题库列表\n\t\tgroup.POST(\"/qusb/add\", qusBankAdd) //题库添加\n\t\tgroup.POST(\"/qusb/del\", qusBankDel) //题库删除\n\t\tgroup.POST(\"/qusb/update\", qusBankEdit) //题库修改\n\t\tgroup.POST(\"/qusb/check\", qusBankCheck) // 答题\n\n\t\tgroup.GET(\"/qs/info\", qusInfo) //题目信息\n\t\tgroup.GET(\"/qs/list\", qusList) //题目列表\n\t\tgroup.POST(\"/qs/add\", qusAdd) //题目添加\n\t\tgroup.POST(\"/qs/update\", qusUpdate) //题目更新\n\t\tgroup.POST(\"/qs/del\", qusDel) //题目删除\n\t\tgroup.GET(\"/qs/get\", getQuestion) //题目获取\n\t\tgroup.POST(\"/qs/answer\", answerQuestion) // 答题\n\n\t\tgroup.POST(\"/bind\", questionBankBind) // 绑定题库\n\t\tgroup.POST(\"/unbind\", questionBankUnbind) // 解绑题库\n\t\tgroup.POST(\"/bind/bank\", getBankBind) // 查询已绑定的题库\n\t\tgroup.GET(\"/bind/items\", getBindItems) // 查询绑定到题库的 items\n\n\t\tgroup.GET(\"/risk/check\", riskCheck) //风险检验\n\t\tgroup.POST(\"/risk/check/v2\", riskCheckV2) //风险检验v2\n\t\tgroup.GET(\"/graph/prepare\", graphPrepare) //拉起图形验证\n\t\tgroup.POST(\"/graph/check\", graphCheck) //图形验证\n\t}\n\n\tgroup2 := e.Group(\"/openplatform/admin/antifraud/shield\")\n\t{\n\t\tgroup2.GET(\"/risk/ip/list\", ipList) //ip列表\n\t\tgroup2.GET(\"/risk/ip/detail\", ipDetail) //ip详情列表\n\t\tgroup2.GET(\"/risk/uid/list\", uidList) //uid列表\n\t\tgroup2.GET(\"/risk/uid/detail\", uidDetail) //uid详情列表\n\t\tgroup2.POST(\"/risk/ip/black\", ipBlack) //设置ip黑名单\n\t\tgroup2.POST(\"/risk/uid/black\", uidBlack) //设置uid黑名单\n\n\t}\n}", "func getBlockHandler(w http.ResponseWriter, r *http.Request) {\n vars := mux.Vars(r)\n i, _ := strconv.Atoi(vars[\"index\"])\n if (i < 0 || len(blockChain) <= i) {\n w.WriteHeader(http.StatusBadRequest)\n w.Write([]byte(\"HTTP 400: Bad Request - Index out of range\"))\n return\n } \n\n w.WriteHeader(http.StatusOK)\n json.NewEncoder(w).Encode(blockChain[i])\n}", "func BobUnDepositETHAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_UNDEPOSIT\n\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\tAliceAddr := r.FormValue(\"address\")\n\tLog.Infof(\"start undeposit eth from Alice in contract. Alice address=%v\", AliceAddr)\n\n\tif AliceAddr == \"\" {\n\t\tLog.Warnf(\"incomplete parameter. Alice address=%v\", AliceAddr)\n\t\tfmt.Fprintf(w, RESPONSE_UNDEPOSIT_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tplog.Detail = fmt.Sprintf(\"Alice address=%v\", AliceAddr)\n\n\tLog.Debugf(\"start send transaction to undeposit eth to Alice in contract...Alice address=%v\", AliceAddr)\n\tt := time.Now()\n\ttxid, err := BobUnDeposit(AliceAddr)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to undeposit eth to contract. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_UNDEPOSIT_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tLog.Infof(\"success to send transaction to undeposit eth...txid=%v, Alice address=%v, time cost=%v\", txid, AliceAddr, time.Since(t))\n\n\tplog.Result = LOG_RESULT_SUCCESS\n\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_SUCCESS, \"undepositing eth from contract...\"))\n\treturn\n}", "func (s *Server) handleGetData(request []byte) {\n\tvar payload serverutil.MsgGetData\n\tif err := getPayload(request, &payload); err != nil {\n\t\tlog.Panic(err)\n\t}\n\taddr := payload.AddrSender.String()\n\tp, _ := s.GetPeer(addr)\n\tp.IncreaseBytesReceived(uint64(len(request)))\n\ts.AddPeer(p)\n\ts.Log(true, fmt.Sprintf(\"GetData kind: %s, with ID:%s received from %s\", payload.Kind, hex.EncodeToString(payload.ID), addr))\n\n\tif payload.Kind == \"block\" {\n\t\t//block\n\t\t//on recupère le block si il existe\n\t\tblock, _ := s.chain.GetBlockByHash(payload.ID)\n\t\tif block != nil {\n\t\t\t//envoie le block au noeud créateur de la requete\n\t\t\ts.sendBlock(payload.AddrSender, block)\n\t\t} else {\n\t\t\tfmt.Println(\"block is nil :( handleGetData\")\n\t\t\tgo func() {\n\t\t\t\tfor {\n\t\t\t\t\ttime.Sleep(time.Millisecond * 50)\n\t\t\t\t\tblock, _ := s.chain.GetBlockByHash(payload.ID)\n\t\t\t\t\tif block != nil {\n\t\t\t\t\t\ts.sendBlock(payload.AddrSender, block)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t} else {\n\t\ttx := mempool.Mempool.GetTx(hex.EncodeToString(payload.ID))\n\t\tif tx != nil {\n\t\t\ts.SendTx(payload.AddrSender, tx)\n\t\t}\n\t}\n}", "func Create (w http.ResponseWriter, r *http.Request) {\n\t/* This is an SBC */\n\tif CREATED == false {\n\t\t/* Move the checking of ID up first to confirm this is allowed */\n\t\t/* Do most of start. Just don't download because that would be downloading from self */\n\t\t/* Get address and ID */\n\t\t/* Get port number and set that to ID */\n\t\t/* Save localhost as Addr */\n\t\tsplitHostPort := strings.Split(r.Host, \":\")\n\t\ti, err := strconv.ParseInt(splitHostPort[1], 10, 32)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\tpanic(err)\n\t\t}\n\t\t/* ID is now port number. Address is now correct Address */\n\t\tID = int32(i)\n\t\tSELF_ADDR = r.Host\n\t\t/* Check if ID is allowed in ALLOWED_IDs */\n\t\tif _, ok := ALLOWED_IDS[ID]; ok {\n\t\t\tnewBlockChain := data.NewBlockChain()\n\n\t\t\tmpt1 := p1.MerklePatriciaTrie{}\n\t\t\tmpt1.Initial()\n\t\t\tmpt1.Insert(\"1\", \"Origin\")\n\n\t\t\tmpt2 := p1.MerklePatriciaTrie{}\n\t\t\tmpt2.Initial()\n\t\t\tmpt2.Insert(\"1\", \"Decoy1\")\n\n\t\t\tmpt3 := p1.MerklePatriciaTrie{}\n\t\t\tmpt3.Initial()\n\t\t\tmpt3.Insert(\"1\", \"Decoy2\")\n\n\t\t\tmpt4 := p1.MerklePatriciaTrie{}\n\t\t\tmpt4.Initial()\n\t\t\tmpt4.Insert(\"1\", \"Decoy3\")\n\n\t\t\thexPubKey := hexutil.Encode(signature_p.PUBLIC_KEY)\n\t\t\tnewBlockChain.GenBlock(mpt1, hexPubKey)\n\t\t\tnewBlockChain.GenBlock(mpt2, hexPubKey)\n\t\t\tnewBlockChain.GenBlock(mpt3, hexPubKey)\n\t\t\tnewBlockChain.GenBlock(mpt4, hexPubKey)\n\t\t\t/* Set Global variable SBC to be this new blockchain */\n\t\t\tSBC = newBlockChain\n\t\t\t/* Generate Multiple Blocks Initially */\n\t\t\t\t\n\t\t\tblockChainJson, _ := SBC.BlockChainToJson()\n\t\t\t/* Write this to the server */\n\t\t\tw.Write([]byte(blockChainJson))\n\n\t\t\t/* Need to instantiate the peer list */\n\t\t\tPeers = data.NewPeerList(ID, 32)\n\t\t\tBALLOT = ReadDataFromBallot()\n\t\t\tCREATED = true\n\t\t}\n\t}\n}", "func BobDepositETHAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_DEPOSIT\n\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\tvalue := r.FormValue(\"value\")\n\tAliceAddr := r.FormValue(\"address\")\n\tLog.Infof(\"start deposit eth to Alice. value=%v, Alice address=%v\", value, AliceAddr)\n\tplog.Detail = fmt.Sprintf(\"undeposit value=%v, Alice address=%v\", value, AliceAddr)\n\n\tvalueInt, err := strconv.ParseInt(value, 10, 64)\n\tif err != nil {\n\t\tLog.Warnf(\"parse value parameter failed. value=%v, err=%v\", value, err)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\n\tif AliceAddr == \"\" {\n\t\tLog.Warnf(\"incomplete parameter. Alice address=%v\", AliceAddr)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"read parameters. value=%v, Alice address=%v\", value, AliceAddr)\n\n\tLog.Debugf(\"start send transaction to deposit eth to Alice in contract...value=%v, Alice address=%v\", value, AliceAddr)\n\tt := time.Now()\n\ttxid, err := BobDeposit(valueInt, AliceAddr)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to deposit eth to contract. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_DEPOSIT_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tLog.Infof(\"success to send transaction to deposit eth...txid=%v, value=%v, Alice address=%v, time cost=%v\", txid, value, AliceAddr, time.Since(t))\n\n\tplog.Result = LOG_RESULT_SUCCESS\n\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_SUCCESS, \"depositing eth to contract...\"))\n\treturn\n\n}", "func init() {\n//\tvar _r = net.GetRouter()\n//\tvar r = _r.PathPrefix(\"/v1\").Subrouter()\n\n var r = net.GetRouter()\n\t//route for test\n\t log.Print(\"cz init net_v1\")\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBGettokenizedcards, nil)).Methods(\"GET\") //logicbusiness.go\n r.Handle(\"/v3/processpayment\", netHandle(v4handleDBProcesspayment, nil)).Methods(\"GET\") //logicbusiness.go \n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBGeneratetokenized, nil)).Methods(\"GET\") //logicbusiness.go\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBPostGettokenizedcards, nil)).Methods(\"POST\") //logicbusiness.go\n\tr.Handle(\"/v3/processpayment\", netHandle(v4handleDBPostProcesspayment, nil)).Methods(\"POST\") //logicbusiness.go \t \n\n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBPostGeneratetokenized, nil)).Methods(\"POST\") //logicbusiness.go\n\n\t \n}", "func (srv *Server) walletHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tsiacoinBal, siafundBal, siaclaimBal := srv.wallet.ConfirmedBalance()\n\tsiacoinsOut, siacoinsIn := srv.wallet.UnconfirmedBalance()\n\twriteJSON(w, WalletGET{\n\t\tEncrypted: srv.wallet.Encrypted(),\n\t\tUnlocked: srv.wallet.Unlocked(),\n\n\t\tConfirmedSiacoinBalance: siacoinBal,\n\t\tUnconfirmedOutgoingSiacoins: siacoinsOut,\n\t\tUnconfirmedIncomingSiacoins: siacoinsIn,\n\n\t\tSiafundBalance: siafundBal,\n\t\tSiacoinClaimBalance: siaclaimBal,\n\t})\n}", "func (d *Daemon) routeHandler(w *rest.ResponseWriter, r *rest.Request) {\n\t//id := strings.Split(r.URL.Path, \"/\")[2]\n\t//route := strings.Split(r.URL.Path, \"/\")[3]\n\n\tid, ok := r.PathParams[\"id\"]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"MISSING_BLOCK_ID\")\n\t\treturn\n\t}\n\n\troute, ok := r.PathParams[\"route\"]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"MISSING_ROUTE\")\n\t\treturn\n\t}\n\n\t_, ok = d.blockMap[id]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"BLOCK_ID_NOT_FOUND\")\n\t\treturn\n\t}\n\n\t_, ok = d.blockMap[id].Routes[route]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"ROUTE_NOT_FOUND\")\n\t\treturn\n\t}\n\n\tmsg, err := ioutil.ReadAll(io.LimitReader(r.Body, READ_MAX))\n\n\tif err != nil {\n\t\tApiResponse(w, 500, \"BAD_REQUEST\")\n\t\treturn\n\t}\n\n\tvar outMsg interface{}\n\n\tif len(msg) > 0 {\n\t\terr = json.Unmarshal(msg, &outMsg)\n\t\tif err != nil {\n\t\t\tlog.Println(msg)\n\t\t\tApiResponse(w, 500, \"BAD_JSON\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tResponseChan := make(chan interface{})\n\tblockRouteChan := d.blockMap[id].Routes[route]\n\tblockRouteChan <- &blocks.BMsg{\n\t\tMsg: outMsg,\n\t\tResponseChan: ResponseChan,\n\t}\n\trespMsg := <-ResponseChan\n\n\trespJson, err := json.Marshal(respMsg)\n\tif err != nil {\n\t\tApiResponse(w, 500, \"BAD_RESPONSE_FROM_BLOCK\")\n\t\treturn\n\t}\n\n\tDataResponse(w, respJson)\n}", "func innerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\te.Register(register)\n\tg := e.Group(\"/x/job/creative\")\n\t{\n\t\tg.GET(\"/test\", sendMsg)\n\t}\n}", "func (mh *RootHandler) Handler(w http.ResponseWriter, r *http.Request) {\n ref := DatasetRefFromCtx(r.Context())\n if ref == nil {\n WebappHandler(w, r)\n return\n }\n if ref.IsPeerRef() {\n p := &core.PeerInfoParams{\n Peername: ref.Peername,\n }\n res := &profile.Profile{}\n err := mh.ph.Info(p, res)\n if err != nil {\n util.WriteErrResponse(w, http.StatusInternalServerError, err)\n return\n }\n if res.ID == \"\" {\n util.WriteErrResponse(w, http.StatusNotFound, errors.New(\"cannot find peer\"))\n return\n }\n util.WriteResponse(w, res)\n return\n }\n res := &repo.DatasetRef{}\n err := mh.dsh.Get(ref, res)\n if err != nil {\n util.WriteErrResponse(w, http.StatusInternalServerError, err)\n return\n }\n if res.Name == \"\" {\n util.WriteErrResponse(w, http.StatusNotFound, errors.New(\"cannot find peer dataset\"))\n return\n }\n if res == nil {\n util.WriteErrResponse(w, http.StatusNotFound, errors.New(\"cannot find peer dataset\"))\n return\n }\n util.WriteResponse(w, res)\n return\n}", "func (rh *RegionHandler) NodeChangeHandler() {\n\t// log.Println(\"NodeChangeHandler started\")\n\tfor {\n\t\tncInfo := <-rh.RegionChange\n\n\t\tif ncInfo.PrevConn == nil && ncInfo.CurrConn == nil {\n\n\t\t\t// one node edge case: dump everything into primary\n\t\t\t// log.Println(\"one node edge case\")\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.BackupRegions {\n\t\t\t\trh.Regions[rid] = r \n\t\t\t\tr.SetReady()\n\t\t\t\tgo r.MaintainRegion()\n\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t}\n\t\t\t// log.Println(\"Number of reg handling: \")\n\t\t\trh.mux.Unlock()\n\n\n\t\t} else if ncInfo.Successor && ncInfo.Join {\n\n\t\t\t// onSuccessorJoin:\n\t\t\t// move regions on curr node that hash to curr region to joined node\n\t\t\t// log.Println(\"onSuccessorJoin\", ncInfo.Curr, ncInfo.Prev)\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trh.mux.RLock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id:rid, Foods:r.GetFood()}) \n\t\t\t}\n\t\t\trh.mux.RUnlock()\n\n\t\t\tconn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(conn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(conn)\n\t\t\t// \t_, err := regionClient.AddRegions(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// \t// conn := ncInfo.PrevConn\n\t\t\t// \t// _, err = regionClient.RemoveRegion(context.Background(), &region_pb.IdRegionRequest{Id: rid})\n\t\t\t// \t// if err != nil {\n\t\t\t// \t// \tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t// }\n\t\t\t// }\n\n\t\t} else if ncInfo.Successor && !ncInfo.Join {\n\n\t\t\t// onSuccessorLeave:\n\t\t\t// move regions on curr node that hash to curr region to new successor\n\t\t\t// log.Println(\"onSuccessorLeave\", ncInfo.Curr, ncInfo.Prev)\n\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trh.mux.RLock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id:rid, Foods:r.GetFood()}) \n\t\t\t}\n\t\t\trh.mux.RUnlock()\n\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\t\t\t// rh.mux.RLock()\n\t\t\t// for rid, r := range rh.Regions {\n\t\t\t// \tregionsCopy[rid] = r \n\t\t\t// }\n\t\t\t// rh.mux.RUnlock()\n\n\t\t\tconn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(conn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(conn)\n\t\t\t// \t_, err := regionClient.AddRegion(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t} else if !ncInfo.Successor && ncInfo.Join {\n\n\t\t\t// on predecessor join:\n\t\t\t// remove regions on curr node that hash to prepredecessor\n\t\t\t// log.Println(\"on predecessor join\", ncInfo.Curr, ncInfo.Prev)\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, _ := range rh.BackupRegions {\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) != ncInfo.Curr {\n\t\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\t// remove region on successor for which now I'm backup\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trmRegions := []*IdRegionRequest{}\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tlog.Println(\"Checking\", rid, rh.RegionHash[rid], rh.Router.Successor(rh.RegionHash[rid]), ncInfo.Curr, rh.Router.Hash)\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) == ncInfo.Curr {\n\t\t\t\t\t// regionsCopy[rid] = r\n\t\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id: rid, Foods:r.GetFood()}) \n\t\t\t\t\trmRegions = append(rmRegions, &IdRegionRequest{Id: rid})\n\t\t\t\t\tr.Quit <- true\n\t\t\t\t\tr.ClearAllBlobCache()\n\t\t\t\t\trh.BackupRegions[rid] = r\n\t\t\t\t\tdelete(rh.Regions, rid)\n\t\t\t\t\t// r.UnsetReady()\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\t// move regions that hash to joining node from curr node to joining node\n\t\t\t// remove regions on successor that hash to joining node\n\t\t\tsuccessorConn := rh.Router.GetSuccessor()\n\t\t\tPredcessorConn := rh.Router.GetPredecessor()\n\t\t\tregionClient := NewRegionClient(successorConn)\n\t\t\t_, err := regionClient.RemoveRegions(context.Background(), &RemoveRegionsRequest{Regions: rmRegions})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t}\n\t\t\tregionClient = NewRegionClient(PredcessorConn)\n\t\t\t_, err = regionClient.TransferPrimary(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t}\n\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(successorConn)\n\t\t\t// \t_, err := regionClient.RemoveRegion(context.Background(), &IdRegionRequest{Id: rid})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t// \t}\n\n\t\t\t// \tregionClient = NewRegionClient(PredcessorConn)\n\t\t\t// \t_, err = regionClient.TransferPrimary(context.Background(), &FoodRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// \tr.UnsetReady()\n\t\t\t// }\n\n\t\t} else {\n\n\t\t\t// move regions that hashed to node that left to successor\n\t\t\t// log.Println(\"on predecessor leave\", ncInfo.Curr, ncInfo.Prev)\n\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.BackupRegions {\n\t\t\t\t// log.Println(\"Checking\", rid, rh.RegionHash[rid])\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) == rh.Router.Hash {\n\t\t\t\t\t// log.Println(\"Moving\", rid, \"from bkup to prim\")\n\t\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id: rid, Foods:r.GetFood()})\n\t\t\t\t\t//regionsCopy[rid] = r\n\t\t\t\t\trh.Regions[rid] = r\n\t\t\t\t\tr.SetReady()\n\t\t\t\t\tgo r.MaintainRegion()\n\t\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\tsuccessorConn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(successorConn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor leave big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(successorConn)\n\t\t\t// \t_, err := regionClient.AddRegions(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor leave big no no: \", err)\n\t\t\t// \t}\n\t\t\t// }\n\t\t}\n\t\t\n\t}\n}", "func (t *SimpleChaincode) subscribe(stub shim.ChaincodeStubInterface, args []string, name string) pb.Response {\n\tvar a string // Entities\n\tvar aSub string // Security to Subscribe\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of hjuh args. Expecting 1\")\n\t}\n\t\n\t//a = args[0]\n\ta = name\n\taSub = args[0]\n\t// Get the state from the ledger\n\taBytes, err := stub.GetState(a+\"subscriptions\")\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tif aBytes == nil {\n\t\t//return shim.Error(\"Entity not found\")\n\t}\n\t\n\tsecurityBytes, err := stub.GetState(\"security\")\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tif securityBytes == nil {\n\t\treturn shim.Error(\" security Entity not found\")\n\t}\n\taSubString := string(aBytes)\n\tsecurityString :=string(securityBytes)\n\t\n\tif(strings.Contains(aSubString,aSub+\",\")){\n\t\treturn shim.Error(\"Already Subscribed\")\n\t}\n\tif(!strings.Contains(securityString,aSub+\",\")){\n\t\treturn shim.Error(\"Invalid Security\")\n\t}\n\tlogger.Debug(\"aSub = %s\", aSub)\n\n\t// Write the state back to the ledger\n\terr = stub.PutState(a+\"subscriptions\",append(append([]byte(aSub),[]byte(\",\")...),aBytes...))\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\t// add subs to security\n\tsecuritySubBytes, err := stub.GetState(aSub)\n\t\tif err != nil {\n\t\t\terr1 := stub.PutState(aSub,[]byte(a))\n\tif err1 != nil {\n\t\treturn shim.Error(err1.Error())\n\t}\n\t} else {\n\t\t//securitySubString :=string(securitySubBytes)\n\t\terr2 := stub.PutState(aSub,append(append([]byte(a),[]byte(\",\")...),securitySubBytes...))\n\t\t\tif err2 != nil {\n\t\treturn shim.Error(err2.Error())\n\t}\n\t}\n\treturn shim.Success(nil)\n}", "func TransactionHandler(w http.ResponseWriter, r *http.Request) {\n\taction := r.URL.Path[len(\"/api/transactions\"):]\n\n\tlog.Println(\"Handling method\", r.Method, \"with action\", action)\n\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tswitch action {\n\t\tcase \"\": // Create new transaction\n\t\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\t\tif err != nil {\n\t\t\t\tcreateJsonErrorResponse(w, r, http.StatusInternalServerError, ErrorForm, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar t TransactionResponse\n\n\t\t\terr = json.Unmarshal(body, &t)\n\t\t\tif err != nil {\n\t\t\t\tcreateJsonErrorResponse(w, r, http.StatusInternalServerError, ErrorJson, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpass := []byte(t.Password)\n\n\t\t\ttx, e := createAndBroadcastTx(t.Recipient, *big.NewInt(t.Amount), pass)\n\n\t\t\tvar jsonResponse TransactionResponse\n\t\t\tif e == nil {\n\t\t\t\tjsonResponse = TransactionResponse{Amount: t.Amount, Recipient: t.Recipient, Status: ResponseOk, Hash: hex.EncodeToString(tx.Hash())}\n\t\t\t} else {\n\t\t\t\tjsonResponse = TransactionResponse{Amount: t.Amount, Recipient: t.Recipient, Status: ResponseFailed, ErrorText: e.Error()}\n\t\t\t}\n\n\t\t\tres, err := json.Marshal(jsonResponse)\n\t\t\tif err != nil {\n\t\t\t\tcreateJsonErrorResponse(w, r, http.StatusInternalServerError, ErrorJson, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintf(w, string(res))\n\t\tdefault:\n\t\t\tcreateJsonErrorResponse(w, r, http.StatusNotFound, Error404, fmt.Sprint(\"No action: \", r.Method, action))\n\t\t}\n\tcase \"GET\":\n\t\tswitch action {\n\t\tcase \"\":\n\t\t\tvar txs []TransactionJson\n\t\t\tfor _, tx := range Config.DeserializedTxs {\n\t\t\t\ttxs = append(txs, EncodeToFriendlyStruct(tx))\n\n\t\t\t}\n\n\t\t\tif len(txs) == 0 {\n\t\t\t\tfmt.Fprintf(w, string(\"[]\"))\n\t\t\t} else {\n\n\t\t\t\tres, err := json.Marshal(txs)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Nope\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(w, string(res))\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\tdefault:\n\t\tcreateJsonErrorResponse(w, r, http.StatusNotFound, Error404, fmt.Sprint(\"No action: \", r.Method, action))\n\n\t}\n}", "func (as *AddrServer) HandleGetTransactions(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tquery := r.URL.Query()\n\n\tvar (\n\t\tpage int\n\t\taddress string\n\t\tblock string\n\t)\n\n\tif len(query[\"page\"]) > 0 {\n\t\tpg, err := strconv.ParseInt(query[\"page\"][0], 10, 64)\n\t\tif err != nil {\n\t\t\tpage = 0\n\t\t} else {\n\t\t\tpage = int(pg)\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\tif len(query[\"address\"]) > 0 {\n\t\taddress = query[\"address\"][0]\n\t}\n\n\tif len(query[\"block\"]) > 0 {\n\t\tblock = query[\"block\"][0]\n\t} else if len(query[\"block\"]) > 1 {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"only one block accepted in query\", fmt.Errorf(\"\")))\n\t\treturn\n\t}\n\n\tif address != \"\" {\n\t\t// Fetch Block Height\n\t\tinfo, err := as.Client.GetInfo()\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"failed to getInfo\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// paginate through transactions\n\t\ttxns, err := as.GetAddressTxIDs([]string{address}, BlockstackStartBlock, int(info.Blocks))\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"error fetching page of transactions for address\", err))\n\t\t\treturn\n\t\t}\n\n\t\tvar retTxns []string\n\t\tvar out []TransactionIns\n\n\t\t// Pull off a page of transactions\n\t\tif len(txns.Result) < 10 {\n\t\t\tretTxns = txns.Result\n\t\t} else if len(txns.Result) > ((page + 1) * 10) {\n\t\t\tretTxns = []string{}\n\t\t} else if len(txns.Result) > (page*10) && len(txns.Result) < ((page+1)*10) {\n\t\t\tretTxns = txns.Result[page*10:]\n\t\t} else {\n\t\t\tretTxns = txns.Result[page*10 : (page+1)*10]\n\t\t}\n\n\t\tfor _, txid := range retTxns {\n\t\t\ttx, err := as.GetRawTransaction(txid)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\tw.Write(NewPostError(\"error fetching page of transactions for address\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tout = append(out, tx.Result)\n\t\t}\n\n\t\to, _ := json.Marshal(out)\n\t\tw.Write(o)\n\t\treturn\n\t}\n\n\tif block != \"\" {\n\t\t// Make the chainhash for fetching data\n\t\tblockhash, err := chainhash.NewHashFromStr(block)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"error parsing blockhash\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Fetch block data\n\t\tblockData, err := as.Client.GetBlockVerbose(blockhash)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"failed to fetch block transactions\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Initialize output\n\t\tvar txns = []*btcjson.TxRawResult{}\n\n\t\t// fetch proper slice of transactions\n\t\tvar txs []string\n\n\t\t// Pick the proper slice from the txs array\n\t\tif len(blockData.Tx) < ((page) * 10) {\n\t\t\t// If there is no data left to fetch, return error\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"Out of bounds\", fmt.Errorf(\"page %v doesn't exist\", page)))\n\t\t\treturn\n\t\t\t// If it's the last page, just return the last few transactions\n\t\t} else if len(blockData.Tx)-((page+1)*10) <= 0 {\n\t\t\ttxs = blockData.Tx[int(page)*10:]\n\t\t\t// Otherwise return a full page\n\t\t} else {\n\t\t\ttxs = blockData.Tx[int(page)*10 : int(page+1)*10]\n\t\t}\n\n\t\t// Fetch individual transaction data and append it to the txns array\n\t\tfor _, tx := range txs {\n\t\t\ttxhash, err := chainhash.NewHashFromStr(tx)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\tw.Write(NewPostError(fmt.Sprintf(\"error parsing transaction %v\", tx), err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttxData, err := as.Client.GetRawTransactionVerbose(txhash)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\tw.Write(NewPostError(fmt.Sprintf(\"error fetching transaction details: %v\", tx), err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttxns = append(txns, txData)\n\t\t}\n\n\t\t// Return the JSON\n\t\tout, _ := json.Marshal(txns)\n\t\tw.Write(out)\n\t\treturn\n\t}\n\tw.WriteHeader(400)\n\tw.Write(NewPostError(\"Need to pass ?block=BLOCKHASH or ?address=ADDR\", fmt.Errorf(\"\")))\n}", "func (h HTTPHandler) HandleInfo(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\tvar peerBlockchains []BlockchainInfo\n\n\tpeerBlockchains = append(peerBlockchains, getBlockchainInfo(h.bf.Local))\n\tfor _, peerChain := range h.bf.Peers {\n\t\tpeerBlockchains = append(peerBlockchains, getBlockchainInfo(peerChain))\n\t}\n\n\tblockchainInfoJSON, err := json.Marshal(peerBlockchains)\n\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"route\": \"HandleInfo\",\n\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t}).Error(err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(blockchainInfoJSON)\n}", "func processTxHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"/processTx/\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif r.Method != \"POST\" { // expecting POST method\n\t\thttp.Error(w, \"Invalid request method.\", 405)\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar txIn TxInput\n\n\terr := decoder.Decode(&txIn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer r.Body.Close()\n\n\t// fmt.Printf(\"\\nTX input:\\n%+v\\n\", txIn)\n\n\ttxResultStr := processTx(&txIn)\n\n\tfmt.Fprintf(w, \"%s\", txResultStr)\n}", "func main() {\n\tlog.UseLog(&zapimpl.Logger{}) // use zap log\n\tlog.SetLevel(log.DevDebugLevel)\n\tlog.Info(\"start up bitcoin rpc client\")\n\t//cfg := &client.Config{\n\t//\tHost: \"172.16.2.35:3333\",\n\t//\tUser: \"et\",\n\t//\tPass: \"www.et.com\",\n\t//}\n\tcfg := &client.Config{\n\t\tHost: \"172.16.2.27:8332\",\n\t\tUser: \"btc\",\n\t\tPass: \"btcpwd\",\n\t}\n\tdemos.Initialize(cfg)\n\tdefer demos.Shutdown()\n\t//common rpc method\n\t//demos.SendTest() cli.Send(\"command\", args...)\n\n\t//Blockchain rpc methods\n\t//demos.GetBestBlockHashTest()\n\t//demos.GetBlockBytesTest()\n\t//demos.GetBlockTest()\n\t//demos.GetBlockVerboseTXTest()\n\tdemos.GetBlockVerboseTXTest()\n\t//demos.GetBlockChainInfoTest()\n\t//demos.GetBlockCountTest()\n\t//demos.GetBlockHashTest()\n\t//demos.GetBlockHeaderTest()\n\t//demos.GetBlockStatsTest()\n\t//demos.GetChainTipsTest()\n\t//demos.GetChainTXStatsTest()\n\t//demos.GetChainTXStatsEntireTest()\n\t//demos.GetDifficultyTest()\n\t//demos.GetMempoolAncestorsTest()\n\t//demos.GetMempoolAncestorsVerboseTest()\n\t//demos.GetMempoolDescendantsTest()\n\t//demos.GetMempoolDescendantsVerboseTest()\n\t//demos.GetMempoolEntryTest()\n\t//demos.GetMempoolInfoTest()\n\t//demos.GetRawMempoolTest()\n\t//demos.GetRawMempoolVerboseTest()\n\t//demos.GetTXOutTest()\n\t//demos.GetTXOutProofTest()\n\t//demos.GetTXOutSetInfoTest()\n\t//demos.PreciousBlockTest()\n\t//demos.PruneBlockchainTest()\n\t//demos.SaveMempoolTest()\n\t//demos.VerifyChainTest()\n\t//demos.VerifyTXOutProofTest()\n\t//demos.VerifyChainLevelTest()\n\t//demos.VerifyChainBlocksTest()\n\n\t//Control rpc methods\n\t//demos.GetMemoryInfoTest()\n\t//demos.GetMemoryInfo4MallocInfoTest()\n\t//demos.HelpTest()\n\t//demos.StopTest()\n\t//demos.UptimeTest()\n\n\t//Generate rpc methods\n\t//demos.GenerateTest()\n\t//demos.GenerateToAddressTest()\n\n\t//Network rpc methods\n\t//demos.GetNetworkInfoTest()\n\n\t//RawTransactions rpc methods\n\t//demos.CombinePSBTTest() //ok\n\t//demos.CombineRawTransactionTest() //ok\n\t//demos.ConvertToPSBTTest() //ok\n\t//demos.CreatepSBTTest() //ok\n\t//demos.CreateRawTransactionTest() //ok\n\t//demos.DecodePSBTTest() //ok\n\t//demos.DecodeRawTransactionTest() //ok\n\t//demos.DecodeScriptTest() //ok\n\t//demos.FinalizePSBTTest() //ok\n\t//demos.FundRawTransactionTest() //ok\n\t//demos.GetRawTransactionTest() //ok\n\t//demos.GetRawTransactionVerboseTest() //ok\n\t//demos.SendRawTransactionTest() //ok\n\t//demos.SignRawTransactionWithKeyTest() //ok\n\t//demos.TestMempoolAcceptTest() //ok\n\n\t//Wallet rpc methods\n\t//demos.WalletTestInitialize() //ok\n\t//demos.AbandonTransactionTest() //ok\n\t//demos.AbortRescanTest() //ok\n\t//demos.AddMultiSigAddressTest() //ok\n\t//demos.BackupWalletTest() //ok\n\t//demos.BumpFeeTest() //ok\n\t//demos.CreateWalletTest() //ok\n\t//demos.DumpPrivkeyTest() //ok\n\t//demos.DumpWalletTest() //ok\n\t//demos.EncryptWalletTest() //ok\n\t//demos.GetAddressesByLabelTest() //ok\n\t//demos.GetAddressInfoTest() //ok\n\t//demos.GetBalanceTest() //ok\n\t//demos.GetBalanceEntireTest() //ok\n\t//demos.GetNewAddressTest() //ok\n\t//demos.GetNewAddressEntireTest() //ok\n\t//demos.GetRawChangeAddressTest() //ok\n\t//demos.GetReceivedByAddressTest() //ok\n\t//demos.GetTransactionTest() //ok\n\t//demos.GetUnconfirmedBalanceTest() //ok\n\t//demos.GetWalletInfoTest() //ok\n\t//demos.ImportaddressTest() //ok\n\t//demos.ImportMultiTest() //ok\n\t//demos.ImportPrivkeyTest() //ok\n\t//demos.ImportPrunedFundsTest() //TODO\n\t//demos.ImportPubkeyTest() //ok\n\t//demos.ImportWalletTest() //test exception\n\t//demos.KeypoolRefillTest() //ok\n\t//demos.ListAddressGroupingsTest() //ok\n\t//demos.ListLabelsTest() //ok\n\t//demos.ListLockUnspentTest() // todo https://bitcoincore.org/en/doc/0.17.0/rpc/wallet/listlockunspent/\n\t//demos.ListReceivedByAddressTest() //ok\n\t//demos.ListSinceBlockTest() //ok\n\t//demos.ListTransactionsTest() //ok\n\t//demos.ListUnspentTest() //ok\n\t//demos.ListUnspentEntireTest() //ok\n\t//demos.ListWalletsTest() //ok\n\t//demos.LoadWalletTest() //ok\n\t//demos.LockUnspentTest() //ok\n\t//demos.RemovePrunedFundsTest() //ok\n\t//demos.RescanBlockChainTest() //ok\n\t//demos.SendManyTest() //ok\n\t//demos.SendToAddressTest() //ok\n\t//demos.SendToAddressEntireTest() //ok\n\t//demos.SetHDSeedTest() //ok\n\t//demos.SetTXFeeTest() //ok\n\t//demos.SignMessageTest() //ok\n\t//demos.SignRawtransactionWithWalletTest() //TODO\n\t//demos.UnloadWalletTest() //ok\n\t//demos.WalletCreateFundedPSBTTest() //TODO no implement\n\t//demos.WalletLockTest() //ok\n\t//demos.WalletPassphraseTest() //ok\n\t//demos.WalletPassphraseChangeTest() //ok\n\t//demos.WalletProcessPSBTTest() //TODO\n}", "func main() {\n\trouter := mux.NewRouter()\n\t\n\t//initial nodes can be added form the command line \n\tif len(os.Args) > 1 {\n\t\tnodeEndpoints := strings.Split(os.Args[1], \",\")\n\t\tfor ind, node := range nodeEndpoints {\n\t\t\tcounternodes[node] = strconv.Itoa(ind) \n\t\t}\n\t} \n\n\n\tfmt.Println(\"master node started on : 8000\")\n\trouter.HandleFunc(\"/items\", UpdateCount).Methods(\"POST\")\n\trouter.HandleFunc(\"/items/{id}/count\", GetCount).Methods(\"GET\")\n\trouter.HandleFunc(\"/ping\", CheckStatus).Methods(\"GET\")\n\trouter.HandleFunc(\"/addnode\", AddCounterNode).Methods(\"POST\")\n\trouter.HandleFunc(\"/removenode\", RemoveCounterNode).Methods(\"POST\")\n\trouter.HandleFunc(\"/syncnode/{nodeid}\", SyncCounterNode).Methods(\"POST\")\n\tlog.Fatal(http.ListenAndServe(\":8000\", router))\n}", "func sendRequests(cust custInfo){\n\n /*\n Scenario for Extending the Chain this is if you want to do at the starting of the process\n\n time.Sleep(30*time.Second)\n\n */\n fmt.Println(\"start client\")\n cliReqs := clientReqs[\"Requests\"]\n var count =0\n var opCode int\n var i int;\n var amt uint64\n fmt.Println(\"as\\n\")\n for i=0;i<len(cliReqs);i++ {\n cust.reqId = cliReqs[i].ReqId\n if(cliReqs[i].Amt != \"\"){\n amount,errReadingAmt := strconv.Atoi(cliReqs[i].Amt)\n amt = uint64(amount)\n\n if(errReadingAmt != nil){\n fmt.Println(\"error reading the amount from request\",errReadingAmt)\n }\n }\n op := cliReqs[i].Operation\n cust.accountNumber = cliReqs[i].AccountNumber\n fmt.Println(\"operation\",op)\n switch op {\n case \"Query\":\n fmt.Println(\"********\")\n go cust.getBalance(cust.reqId)\n opCode = 1\n break\n case \"Deposit\":\n go cust.doDeposit(amt)\n opCode = 2\n break\n case \"Withdrawal\":\n go cust.doWithdrawal(amt)\n opCode = 3\n break\n default:\n fmt.Println(\"Wrong input!!!!!!\",opCode)\n }\n /* For Internal We wont need delay here */\n time.Sleep(10*time.Second)\n select{\n case <-chn:\n fmt.Println(\"in Channel\\n\")\n continue\n case <- time.After(50*time.Second):\n logMessage(\"Status\",\"Opps time out\")\n fmt.Println(\"Time Out!!!!!!!!\")\n if(count < 3){\n count = count + 1\n i=i-1\n }\n }\n count = 0\n fmt.Println(\"pass\",i,os.Args[1])\n }\n\n}", "func main() {\n\tcfg := loadConfig()\n\tr := mux.NewRouter()\n\tdbCtrl, er := ctrl.CreateWalletMgrCluster(cfg.Db.User, cfg.Db.Password, cfg.Db.Name, cfg.Db.Addr, cfg.Db.DbPoolSize)\n\tif er != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Error: %v\", er.Error()))\n\t}\n\n\ts := accmamaging.CreateService(dbCtrl)\n\tr.Handle(\"/accmamaging/add/\", accmamaging.MakeHandler(s)).Methods(\"PUT\")\n\n\tb := browsing.CreateService(dbCtrl)\n\tr.Handle(\"/browsing/accounts\", browsing.MakeGetAccountsHandler(b)).Methods(\"GET\")\n\tr.Handle(\"/browsing/payments\", browsing.MakeGetPaymentsHandler(b)).Methods(\"GET\")\n\n\tp := payment.CreateService(dbCtrl)\n\tr.Handle(\"/payment/change_balance\", payment.MakeChangeBalanceHandler(p)).Methods(\"PUT\")\n\tr.Handle(\"/payment/send_money\", payment.MakeSendMoneyHandler(p)).Methods(\"PUT\")\n\n\thttp.Handle(\"/\", r)\n\taddress := cfg.Addr\n\tlog.Printf(\"Start listen: %v\", address)\n\tlog.Fatal(http.ListenAndServe(address, nil))\n}", "func (s *Server) LegacyGetBlockChainInfo(path int) http.HandlerFunc {\n\n\ttype blockFees struct {\n\t\tAvg float64 `json:\"avg\"`\n\t\tMin float64 `json:\"min\"`\n\t\tMax float64 `json:\"max\"`\n\n\t\tFast float64 `json:\"fast\"`\n\t\tMed float64 `json:\"med\"`\n\t\tSlow float64 `json:\"slow\"`\n\t}\n\n\ttype blockChainInfo struct {\n\t\tBlocks int64 `json:\"blocks\"`\n\t\tFees blockFees `json:\"fees\"`\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the top 3 blocks\n\t\tblks, err := s.blockChainStore.FindBlocksByBlockIdsAndTime(btc.Symbol, nil, nil, nil, blocc.BlockIncludeHeader|blocc.BlockIncludeData, 0, 3)\n\t\tif err == blocc.ErrNotFound {\n\t\t\trender.Render(w, r, server.ErrNotFound)\n\t\t\treturn\n\t\t} else if err != nil && !blocc.IsValidationError(err) {\n\t\t\trender.Render(w, r, server.ErrInvalidRequest(err))\n\t\t\treturn\n\t\t} else if len(blks) != 3 {\n\t\t\trender.Render(w, r, s.ErrInternalLog(fmt.Errorf(\"Did not get top 3 blocks when collecting fees\")))\n\t\t\treturn\n\t\t}\n\n\t\tvar count float64\n\t\tvar txTotalSize float64\n\t\tvar txTotalCount float64\n\t\tvar info blockChainInfo\n\n\t\tfor _, blk := range blks {\n\n\t\t\t// Get the block height. It will be the first block but we'll do this to make it simple and reliable\n\t\t\tif blk.Height > info.Blocks {\n\t\t\t\tinfo.Blocks = blk.Height + 1 // This endpoint was expected to return the count of blocks (genesis block = block 0 so add 1)\n\t\t\t}\n\n\t\t\t// Make sure this is a block that actually has fees in it\n\t\t\tif cast.ToInt64(blk.DataValue(\"fee\")) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Use the median or the average for the fee, whichever is lower\n\t\t\tmedian := cast.ToFloat64(blk.DataValue(\"fee_median\"))\n\t\t\tif median > 0 && median < cast.ToFloat64(blk.DataValue(\"fee_avg\")) {\n\t\t\t\tinfo.Fees.Avg += median\n\t\t\t} else {\n\t\t\t\tinfo.Fees.Avg += cast.ToFloat64(blk.DataValue(\"fee_avg\"))\n\t\t\t}\n\n\t\t\tinfo.Fees.Min += cast.ToFloat64(blk.DataValue(\"fee_min\"))\n\t\t\tinfo.Fees.Max += cast.ToFloat64(blk.DataValue(\"fee_max\"))\n\n\t\t\tcount += 1.0\n\t\t\ttxTotalSize += cast.ToFloat64(blk.BlockSize - 88)\n\t\t\ttxTotalCount += cast.ToFloat64(blk.TxCount)\n\t\t}\n\n\t\t// If test mode, return hard coded fees\n\t\tif config.GetBool(\"server.legacy.btc_fee_testing\") {\n\t\t\tinfo.Fees.Min = 1.1\n\t\t\tinfo.Fees.Avg = 20.1\n\t\t\tinfo.Fees.Max = 40.1\n\t\t\tinfo.Fees.Slow = 1\n\t\t\tinfo.Fees.Med = 20\n\t\t\tinfo.Fees.Fast = 40\n\n\t\t\tif path == blockChainInfoPathFees {\n\t\t\t\t// Return just the fees portion\n\t\t\t\trender.JSON(w, r, info.Fees)\n\t\t\t} else {\n\t\t\t\t// Return the full info object\n\t\t\t\trender.JSON(w, r, info)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif count == 0.0 {\n\t\t\trender.Render(w, r, s.ErrInternalLog(fmt.Errorf(\"Did not get any fee blocks when collecting fees\")))\n\t\t\treturn\n\t\t}\n\n\t\tavgTxSize := txTotalSize / txTotalCount\n\n\t\tinfo.Fees.Avg = (info.Fees.Avg / count) / avgTxSize\n\t\tinfo.Fees.Min = (info.Fees.Min / count) / avgTxSize\n\t\tinfo.Fees.Max = (info.Fees.Max / count) / avgTxSize\n\n\t\t// Cap the fees\n\t\tif minMaxFee := config.GetFloat64(\"server.legacy.btc_min_fee_max\"); minMaxFee > 0 && info.Fees.Min > minMaxFee {\n\t\t\tinfo.Fees.Min = minMaxFee\n\t\t}\n\t\tif avgMaxFee := config.GetFloat64(\"server.legacy.btc_avg_fee_max\"); avgMaxFee > 0 && info.Fees.Avg > avgMaxFee {\n\t\t\tinfo.Fees.Avg = avgMaxFee\n\t\t}\n\t\tif maxMaxFee := config.GetFloat64(\"server.legacy.btc_max_fee_max\"); maxMaxFee > 0 && info.Fees.Max > maxMaxFee {\n\t\t\tinfo.Fees.Max = maxMaxFee\n\t\t}\n\n\t\t// The fast fee will be the average of the 10th percentile of the last 3 blocks\n\t\tinfo.Fees.Fast, err = s.blockChainStore.AverageBlockDataFieldByHeight(btc.Symbol, \"data.fee_vsize_p10\", true, info.Blocks-4, blocc.HeightUnknown)\n\t\tif err == blocc.ErrNotFound {\n\t\t\tinfo.Fees.Fast = info.Fees.Avg\n\t\t} else if err != nil {\n\t\t\trender.Render(w, r, s.ErrInternalLog(fmt.Errorf(\"Error AverageBlockDataFieldByHeight: %v\", err)))\n\t\t\treturn\n\t\t}\n\n\t\t// The slow fee will be the 10th percentile of the 10th percentile of the last 144 blocks\n\t\tinfo.Fees.Slow, err = s.blockChainStore.PercentileBlockDataFieldByHeight(btc.Symbol, \"data.fee_vsize_p10\", 10.0, true, info.Blocks-145, blocc.HeightUnknown)\n\t\tif err == blocc.ErrNotFound {\n\t\t\tinfo.Fees.Slow = info.Fees.Avg\n\t\t} else if err != nil {\n\t\t\trender.Render(w, r, s.ErrInternalLog(fmt.Errorf(\"Error PercentileBlockDataFieldByHeight: %v\", err)))\n\t\t\treturn\n\t\t} else {\n\t\t\t// If the fast fee is somehow better than this fee, use it instead, and then increase the fast fee by a couple sats\n\t\t\t// This should basically never happen\n\t\t\tif info.Fees.Fast < info.Fees.Slow {\n\t\t\t\tinfo.Fees.Slow = info.Fees.Fast\n\t\t\t}\n\t\t}\n\n\t\t// Now calculate the medium fee as 2/3 the way to the fast fee from the slow fee\n\t\tinfo.Fees.Med = (((info.Fees.Fast - info.Fees.Slow) / 3) * 2) + info.Fees.Slow\n\n\t\t// Make extra sure the fees didn't end up the same or in the wrong order if there are rounding errors\n\t\tif info.Fees.Med <= info.Fees.Slow {\n\t\t\tinfo.Fees.Med += (info.Fees.Slow - info.Fees.Med) + 1\n\t\t}\n\t\tif info.Fees.Fast <= info.Fees.Med {\n\t\t\tinfo.Fees.Fast += (info.Fees.Med - info.Fees.Fast) + 1\n\t\t}\n\n\t\t// Quick and dirty hack to provide the average fee as the minimum one since this is what the drop bit app uses\n\t\tif config.GetBool(\"server.legacy.btc_avg_fee_as_min\") {\n\t\t\tinfo.Fees.Min = info.Fees.Avg\n\t\t}\n\n\t\t// This will substitute the p10 fees for the average and min fees\n\t\tif config.GetBool(\"server.legacy.btc_use_p10_fee\") {\n\t\t\tinfo.Fees.Min = info.Fees.Fast\n\t\t\tinfo.Fees.Avg = info.Fees.Fast\n\t\t}\n\n\t\tif path == blockChainInfoPathFees {\n\t\t\t// Return just the fees portion\n\t\t\trender.JSON(w, r, info.Fees)\n\t\t} else {\n\t\t\t// Return the full info object\n\t\t\trender.JSON(w, r, info)\n\n\t\t}\n\t}\n\n}", "func BobPurchaseDataAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tLog.Infof(\"start purchase data...\")\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_TX\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\trequestData := r.FormValue(\"request_data\")\n\tvar data RequestData\n\terr := json.Unmarshal([]byte(requestData), &data)\n\tif err != nil {\n\t\tLog.Warnf(\"invalid parameter. data=%v, err=%v\", requestData, err)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"success to parse request data. data=%v\", requestData)\n\n\tif data.MerkleRoot == \"\" || data.AliceIP == \"\" || data.AliceAddr == \"\" || data.BulletinFile == \"\" || data.PubPath == \"\" {\n\t\tLog.Warnf(\"invalid parameter. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\t\tfmt.Fprintf(w, RESPONSE_INCOMPLETE_PARAM)\n\t\treturn\n\t}\n\tLog.Debugf(\"read parameters. merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tplog.Detail = fmt.Sprintf(\"merkleRoot=%v, AliceIP=%v, AliceAddr=%v, bulletinFile=%v, PubPath=%v\",\n\t\tdata.MerkleRoot, data.AliceIP, data.AliceAddr, data.BulletinFile, data.PubPath)\n\n\tbulletin, err := readBulletinFile(data.BulletinFile, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to read bulletin File. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tplog.Detail = fmt.Sprintf(\"%v, merkle root=%v,\", plog.Detail, bulletin.SigmaMKLRoot)\n\n\tLog.Debugf(\"step0: prepare for transaction...\")\n\tvar params = BobConnParam{data.AliceIP, data.AliceAddr, bulletin.Mode, data.SubMode, data.OT, data.UnitPrice, \"\", bulletin.SigmaMKLRoot}\n\tnode, conn, params, err := preBobConn(params, ETHKey, Log)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to prepare net for transaction. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_PURCHASE_FAILED)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := node.Close(); err != nil {\n\t\t\tfmt.Errorf(\"failed to close client node: %v\", err)\n\t\t}\n\t\tif err := conn.Close(); err != nil {\n\t\t\tLog.Errorf(\"failed to close connection on client side: %v\", err)\n\t\t}\n\t}()\n\tLog.Debugf(\"[%v]step0: success to establish connecting session with Alice. Alice IP=%v, Alice address=%v\", params.SessionID, params.AliceIPAddr, params.AliceAddr)\n\tplog.Detail = fmt.Sprintf(\"%v, sessionID=%v,\", plog.Detail, params.SessionID)\n\tplog.SessionId = params.SessionID\n\n\tvar tx BobTransaction\n\ttx.SessionID = params.SessionID\n\ttx.Status = TRANSACTION_STATUS_START\n\ttx.Bulletin = bulletin\n\ttx.AliceIP = params.AliceIPAddr\n\ttx.AliceAddr = params.AliceAddr\n\ttx.Mode = params.Mode\n\ttx.SubMode = params.SubMode\n\ttx.OT = params.OT\n\ttx.UnitPrice = params.UnitPrice\n\ttx.BobAddr = fmt.Sprintf(\"%v\", ETHKey.Address.Hex())\n\n\tLog.Debugf(\"[%v]step0: success to prepare for transaction...\", params.SessionID)\n\ttx.Status = TRANSACTION_STATUS_START\n\terr = insertBobTxToDB(tx)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to save transaction to db for Bob. err=%v\", err)\n\t\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_TRANSACTION_FAILED, \"failed to save transaction to db for Bob.\"))\n\t\treturn\n\t}\n\n\tvar response string\n\tif tx.Mode == TRANSACTION_MODE_PLAIN_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForPOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForPC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForPAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t}\n\t} else if tx.Mode == TRANSACTION_MODE_TABLE_POD {\n\t\tswitch tx.SubMode {\n\t\tcase TRANSACTION_SUB_MODE_COMPLAINT:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOC(node, ETHKey, tx, data.Demands, data.Phantoms, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTC(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\tcase TRANSACTION_SUB_MODE_ATOMIC_SWAP:\n\t\t\tresponse = BobTxForTAS(node, ETHKey, tx, data.Demands, data.BulletinFile, data.PubPath, Log)\n\t\tcase TRANSACTION_SUB_MODE_VRF:\n\t\t\tif tx.OT {\n\t\t\t\tresponse = BobTxForTOQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.PhantomKeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t} else {\n\t\t\t\tresponse = BobTxForTQ(node, ETHKey, tx, data.KeyName, data.KeyValue, data.BulletinFile, data.PubPath, Log)\n\t\t\t}\n\t\t}\n\t}\n\tvar resp Response\n\terr = json.Unmarshal([]byte(response), &resp)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to parse response. response=%v, err=%v\", response, err)\n\t\tfmt.Fprintf(w, RESPONSE_FAILED_TO_RESPONSE)\n\t\treturn\n\t}\n\tif resp.Code == \"0\" {\n\t\tplog.Result = LOG_RESULT_SUCCESS\n\t}\n\tLog.Debugf(\"[%v]the transaction finish. merkel root=%v, response=%v\", params.SessionID, bulletin.SigmaMKLRoot, response)\n\tfmt.Fprintf(w, response)\n\treturn\n}", "func BobWithdrawETHAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tLog := Logger.NewSessionLogger()\n\n\tvar plog PodLog\n\tplog.Result = LOG_RESULT_FAILED\n\tplog.Operation = LOG_OPERATION_TYPE_BOB_WITHDRAW\n\n\tdefer func() {\n\t\terr := insertLogToDB(plog)\n\t\tif err != nil {\n\t\t\tLog.Warnf(\"insert log error! %v\", err)\n\t\t\treturn\n\t\t}\n\t\tnodeRecovery(w, Log)\n\t}()\n\n\tAliceAddr := r.FormValue(\"address\")\n\tLog.Infof(\"start withdraw eth from contract. Alice address=%v\", AliceAddr)\n\tif AliceAddr == \"\" {\n\t\tLog.Warnf(\"incomplete parameter. Alice address=%v\", AliceAddr)\n\t\tfmt.Fprintf(w, RESPONSE_WITHDRAW_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tplog.Detail = fmt.Sprintf(\"Alice address=%v\", AliceAddr)\n\n\tLog.Debugf(\"start send transaction to withdraw eth from contract...Alice address=%v\", AliceAddr)\n\tt := time.Now()\n\ttxid, rs, err := BobWithdrawETHFromContract(AliceAddr)\n\tif err != nil {\n\t\tLog.Warnf(\"failed to deposit ETH to contract. err=%v\", err)\n\t\tfmt.Fprintf(w, RESPONSE_WITHDRAW_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tif !rs {\n\t\tLog.Warnf(\"failed to deposit ETH to contract.\")\n\t\tfmt.Fprintf(w, RESPONSE_WITHDRAW_CONTRACT_FAILED)\n\t\treturn\n\t}\n\tLog.Infof(\"success to send transaction to withdraw eth...txid=%v, Alice address=%v, time cost=%v\", txid, AliceAddr, time.Since(t))\n\n\tplog.Result = LOG_RESULT_SUCCESS\n\tfmt.Fprintf(w, fmt.Sprintf(RESPONSE_SUCCESS, \"withdrawing eth from contract...\"))\n\treturn\n}", "func handleTransfers(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.URL.Path != \"/transfers\" {\n\t\trespondWithError(rw, invalidURLError)\n\t\treturn\n\t}\n\n\tif req.Method != http.MethodGet && req.Method != http.MethodPost {\n\t\trespondWithError(rw, invalidMethodError)\n\t\treturn\n\t}\n\n\ttoken := req.Header.Get(\"Authorization\")\n\n\tif token == \"\" {\n\t\trespondWithError(rw, noTokenError)\n\t\treturn\n\t}\n\n\tid, err := getUserByToken(token, true)\n\n\tif err != nil {\n\t\trespondWithError(rw, err)\n\t\treturn\n\t}\n\n\tif req.Method == http.MethodPost {\n\t\tdoTransfer(rw, req, id)\n\t} else if req.Method == http.MethodGet {\n\t\tgetTransfers(rw, req, id)\n\t} else {\n\t\trespondWithError(rw, invalidMethodError)\n\t}\n}", "func Start(e *blockchainlistener.ChainEvents, t *blockchainlistener.TokenNetwork) {\n\tce = e\n\ttn = t\n\tapi := rest.NewApi()\n\tif params.DebugMode {\n\t\tapi.Use(rest.DefaultDevStack...)\n\t} else {\n\t\tapi.Use(rest.DefaultProdStack...)\n\t}\n\n\trouter, err := rest.MakeRouter(\n\t\t//peer 提交Partner的BalanceProof,更新Partner的余额\n\t\trest.Put(\"/pfs/1/:peer/balance\", UpdateBalanceProof),\n\t\trest.Put(\"/pfs/1/channel_rate/:channel/:peer\", setChannelRate),\n\t\trest.Get(\"/pfs/1/channel_rate/:channel/:peer\", getChannelRate),\n\t\trest.Put(\"/pfs/1/token_rate/:token/:peer\", setTokenRate),\n\t\trest.Get(\"/pfs/1/token_rate/:token/:peer\", getTokenRate),\n\t\trest.Put(\"/pfs/1/account_rate/:peer\", setAccountRate),\n\t\trest.Get(\"/pfs/1/account_rate/:peer\", getAccountRate),\n\t\trest.Put(\"/pfs/1/feerate/:peer\", setAllFeeRate),\n\t\trest.Post(\"/pfs/1/paths\", GetPaths),\n\t)\n\tif err != nil {\n\t\tlog.Crit(fmt.Sprintf(\"maker router :%s\", err))\n\t}\n\tapi.SetApp(router)\n\tlisten := fmt.Sprintf(\"0.0.0.0:%d\", params.Port)\n\tlog.Crit(fmt.Sprintf(\"http listen and serve :%s\", http.ListenAndServe(listen, api.MakeHandler())))\n}", "func (as *AddrServer) HandleTxGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\ttxid := mux.Vars(r)[\"txid\"]\n\n\t// paginate through transactions\n\ttxns, err := as.GetRawTransaction(txid)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error fetching all transactions for address\", err))\n\t\treturn\n\t}\n\tout, _ := json.Marshal(txns.Result)\n\tw.Write(out)\n}", "func Main(c *nine.Config, activeNet *nine.Params, path string) error {\n\t// fmt.Println(\"wallet Main\")\n\tcfg = c\n\tActiveNet = activeNet\n\tif ActiveNet.Name == \"testnet\" {\n\t\tfork.IsTestnet = true\n\t}\n\tif cfg.Profile != nil {\n\t\tgo func() {\n\t\t\tlistenAddr :=\n\t\t\t\tnet.JoinHostPort(\"127.0.0.1\", fmt.Sprint(*cfg.Profile))\n\t\t\tlog <- cl.Info{\"profile server listening on\", listenAddr}\n\t\t\tprofileRedirect := http.RedirectHandler(\"/debug/pprof\",\n\t\t\t\thttp.StatusSeeOther)\n\t\t\thttp.Handle(\"/\", profileRedirect)\n\t\t\tlog <- cl.Error{http.ListenAndServe(listenAddr, nil)}\n\t\t}()\n\t}\n\t// dbDir := NetworkDir(path, activeNet.Params)\n\tlog <- cl.Debug{\"dbDir\", path, *cfg.DataDir, *cfg.DataDir, activeNet.Params.Name}\n\tloader := wallet.NewLoader(activeNet.Params, path, 250)\n\t// Create and start HTTP server to serve wallet client connections.\n\t// This will be updated with the wallet and chain server RPC client\n\t// created below after each is created.\n\tlog <- cl.Trc(\"startRPCServers loader\")\n\trpcs, legacyRPCServer, err := startRPCServers(loader)\n\tif err != nil {\n\t\tlog <- cl.Error{\n\t\t\t\"unable to create RPC servers:\", err,\n\t\t}\n\t\treturn err\n\t}\n\t// Create and start chain RPC client so it's ready to connect to\n\t// the wallet when loaded later.\n\tif !*cfg.NoInitialLoad {\n\t\tlog <- cl.Trc(\"starting rpcClientConnectLoop\")\n\t\tgo rpcClientConnectLoop(legacyRPCServer, loader)\n\t}\n\tloader.RunAfterLoad(func(w *wallet.Wallet) {\n\t\tlog <- cl.Trc(\"starting startWalletRPCServices\")\n\t\tstartWalletRPCServices(w, rpcs, legacyRPCServer)\n\t})\n\tif !*cfg.NoInitialLoad {\n\t\tlog <- cl.Debug{\"loading database\"}\n\t\t// Load the wallet database. It must have been created already\n\t\t// or this will return an appropriate error.\n\t\tif cfg.WalletPass != nil {\n\t\t\t_, err = loader.OpenExistingWallet([]byte(*cfg.WalletPass), true)\n\t\t} else {\n\t\t\t_, err = loader.OpenExistingWallet([]byte{}, true)\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tlog <- cl.Error{err}\n\t\t\treturn err\n\t\t}\n\t}\n\tlog <- cl.Trc(\"adding interrupt handler to unload wallet\")\n\t// Add interrupt handlers to shutdown the various process components\n\t// before exiting. Interrupt handlers run in LIFO order, so the wallet\n\t// (which should be closed last) is added first.\n\tinterrupt.AddHandler(func() {\n\t\terr := loader.UnloadWallet()\n\t\tif err != nil && err != wallet.ErrNotLoaded {\n\t\t\tlog <- cl.Error{\n\t\t\t\t\"failed to close wallet:\", err,\n\t\t\t}\n\t\t}\n\t})\n\tif rpcs != nil {\n\t\tlog <- cl.Trc(\"starting rpc server\")\n\t\tinterrupt.AddHandler(func() {\n\t\t\t// TODO: Does this need to wait for the grpc server to\n\t\t\t// finish up any requests?\n\t\t\tlog <- cl.Wrn(\"stopping RPC server...\")\n\t\t\trpcs.Stop()\n\t\t\tlog <- cl.Inf(\"RPC server shutdown\")\n\t\t})\n\t}\n\tif legacyRPCServer != nil {\n\t\tinterrupt.AddHandler(func() {\n\t\t\tlog <- cl.Wrn(\"stopping legacy RPC server...\")\n\t\t\tlegacyRPCServer.Stop()\n\t\t\tlog <- cl.Inf(\"legacy RPC server shutdown\")\n\t\t})\n\t\tgo func() {\n\t\t\t<-legacyRPCServer.RequestProcessShutdown()\n\t\t\tinterrupt.Request()\n\t\t}()\n\t}\n\t<-interrupt.HandlersDone\n\tlog <- cl.Inf(\"shutdown complete\")\n\treturn nil\n}", "func (t *targetrunner) ecHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tt.httpecget(w, r)\n\tdefault:\n\t\tcmn.InvalidHandlerWithMsg(w, r, \"invalid method for /slices path\")\n\t}\n}", "func (app *App) InitChain(req abci.RequestInitChain) abci.ResponseInitChain {\n\tres := app.BandApp.InitChain(req)\n\tvar genesisState bandapp.GenesisState\n\tapp.Codec().MustUnmarshalJSON(req.AppStateBytes, &genesisState)\n\t// Auth module\n\tvar genaccountsState auth.GenesisState\n\tauth.ModuleCdc.MustUnmarshalJSON(genesisState[auth.ModuleName], &genaccountsState)\n\tfor _, account := range genaccountsState.Accounts {\n\t\tapp.Write(\"SET_ACCOUNT\", JsDict{\n\t\t\t\"address\": account.GetAddress(),\n\t\t\t\"balance\": app.BankKeeper.GetCoins(app.DeliverContext, account.GetAddress()).String(),\n\t\t})\n\t}\n\t// GenUtil module for create validator genesis transactions.\n\tvar genutilState genutil.GenesisState\n\tapp.Codec().MustUnmarshalJSON(genesisState[genutil.ModuleName], &genutilState)\n\tfor _, genTx := range genutilState.GenTxs {\n\t\tvar tx auth.StdTx\n\t\tapp.Codec().MustUnmarshalJSON(genTx, &tx)\n\t\tfor _, msg := range tx.Msgs {\n\t\t\tif msg, ok := msg.(staking.MsgCreateValidator); ok {\n\t\t\t\tapp.handleMsgCreateValidator(nil, msg, nil, nil)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Staking module\n\tvar stakingState staking.GenesisState\n\tapp.Codec().MustUnmarshalJSON(genesisState[staking.ModuleName], &stakingState)\n\tfor _, val := range stakingState.Validators {\n\t\tapp.emitSetValidator(val.OperatorAddress)\n\t}\n\n\tfor _, del := range stakingState.Delegations {\n\t\tapp.emitDelegation(del.ValidatorAddress, del.DelegatorAddress)\n\t}\n\n\tfor _, unbonding := range stakingState.UnbondingDelegations {\n\t\tfor _, entry := range unbonding.Entries {\n\t\t\tapp.Write(\"NEW_UNBONDING_DELEGATION\", JsDict{\n\t\t\t\t\"delegator_address\": unbonding.DelegatorAddress,\n\t\t\t\t\"operator_address\": unbonding.ValidatorAddress,\n\t\t\t\t\"completion_time\": entry.CompletionTime.UnixNano(),\n\t\t\t\t\"amount\": entry.Balance,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, redelegate := range stakingState.Redelegations {\n\t\tfor _, entry := range redelegate.Entries {\n\t\t\tapp.Write(\"NEW_REDELEGATION\", JsDict{\n\t\t\t\t\"delegator_address\": redelegate.DelegatorAddress,\n\t\t\t\t\"operator_src_address\": redelegate.ValidatorSrcAddress,\n\t\t\t\t\"operator_dst_address\": redelegate.ValidatorDstAddress,\n\t\t\t\t\"completion_time\": entry.CompletionTime.UnixNano(),\n\t\t\t\t\"amount\": entry.InitialBalance,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Oracle module\n\tvar oracleState oracle.GenesisState\n\tapp.Codec().MustUnmarshalJSON(genesisState[oracle.ModuleName], &oracleState)\n\tfor idx, ds := range oracleState.DataSources {\n\t\tapp.emitSetDataSource(types.DataSourceID(idx+1), ds, nil)\n\t}\n\tfor idx, os := range oracleState.OracleScripts {\n\t\tapp.emitSetOracleScript(types.OracleScriptID(idx+1), os, nil)\n\t}\n\tapp.FlushMessages()\n\treturn res\n}", "func (bi *Blockchainidentifier) GetChain(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r.RemoteAddr + \" GET /chain\")\n\n\tresponseMessage := map[string]interface{}{\n\t\t\"chain\": bi.Blocks,\n\t\t\"length\": len(bi.Blocks),\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(responseMessage)\n}", "func (p *BlsCosi) startSubProtocol(tree *onet.Tree) (*SubBlsCosi, error) {\n\n\tpi, err := p.CreateProtocol(p.subProtocolName, tree)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcosiSubProtocol := pi.(*SubBlsCosi)\n\tcosiSubProtocol.Msg = p.Msg\n\tcosiSubProtocol.Data = p.Data\n\t// Fail fast enough if the subleader is failing to try\n\t// at least three leaves as new subleader\n\tcosiSubProtocol.Timeout = p.Timeout / time.Duration(p.SubleaderFailures+1)\n\t// Give one leaf for free but as we don't know how many leaves\n\t// could fail from the other trees, we need as much as possible\n\t// responses. The main protocol will deal with early answers.\n\tcosiSubProtocol.Threshold = tree.Size() - 1\n\n\tlog.Lvlf3(\"Starting sub protocol with subleader %v\", tree.Root.Children[0].ServerIdentity)\n\terr = cosiSubProtocol.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cosiSubProtocol, err\n}", "func (s *peerRESTServer) TraceHandler(w http.ResponseWriter, r *http.Request) {\n\tif !s.IsValid(w, r) {\n\t\ts.writeErrorResponse(w, errors.New(\"Invalid request\"))\n\t\treturn\n\t}\n\ttrcAll := r.URL.Query().Get(peerRESTTraceAll) == \"true\"\n\ttrcErr := r.URL.Query().Get(peerRESTTraceErr) == \"true\"\n\n\tw.WriteHeader(http.StatusOK)\n\tw.(http.Flusher).Flush()\n\n\tdoneCh := make(chan struct{})\n\tdefer close(doneCh)\n\n\t// Trace Publisher uses nonblocking publish and hence does not wait for slow subscribers.\n\t// Use buffered channel to take care of burst sends or slow w.Write()\n\tch := make(chan interface{}, 2000)\n\n\tglobalHTTPTrace.Subscribe(ch, doneCh, func(entry interface{}) bool {\n\t\treturn mustTrace(entry, trcAll, trcErr)\n\t})\n\n\tkeepAliveTicker := time.NewTicker(500 * time.Millisecond)\n\tdefer keepAliveTicker.Stop()\n\n\tenc := gob.NewEncoder(w)\n\tfor {\n\t\tselect {\n\t\tcase entry := <-ch:\n\t\t\tif err := enc.Encode(entry); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.(http.Flusher).Flush()\n\t\tcase <-keepAliveTicker.C:\n\t\t\tif err := enc.Encode(&trace.Info{}); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.(http.Flusher).Flush()\n\t\t}\n\t}\n}", "func rpcClientConnectLoop(legacyRPCServer *legacyrpc.Server, loader *wallet.Loader) {\n\tvar certs []byte\n\t// if !cfg.UseSPV {\n\tcerts = readCAFile()\n\t// }\n\tfor {\n\t\tvar (\n\t\t\tchainClient chain.Interface\n\t\t\terr error\n\t\t)\n\t\t// if cfg.UseSPV {\n\t\t// \tvar (\n\t\t// \t\tchainService *neutrino.ChainService\n\t\t// \t\tspvdb walletdb.DB\n\t\t// \t)\n\t\t// \tnetDir := networkDir(cfg.AppDataDir.Value, ActiveNet.Params)\n\t\t// \tspvdb, err = walletdb.Create(\"bdb\",\n\t\t// \t\tfilepath.Join(netDir, \"neutrino.db\"))\n\t\t// \tdefer spvdb.Close()\n\t\t// \tif err != nil {\n\t\t// \t\tlog<-cl.Errorf{\"unable to create Neutrino DB: %s\", err)\n\t\t// \t\tcontinue\n\t\t// \t}\n\t\t// \tchainService, err = neutrino.NewChainService(\n\t\t// \t\tneutrino.Config{\n\t\t// \t\t\tDataDir: netDir,\n\t\t// \t\t\tDatabase: spvdb,\n\t\t// \t\t\tChainParams: *ActiveNet.Params,\n\t\t// \t\t\tConnectPeers: cfg.ConnectPeers,\n\t\t// \t\t\tAddPeers: cfg.AddPeers,\n\t\t// \t\t})\n\t\t// \tif err != nil {\n\t\t// \t\tlog<-cl.Errorf{\"couldn't create Neutrino ChainService: %s\", err)\n\t\t// \t\tcontinue\n\t\t// \t}\n\t\t// \tchainClient = chain.NewNeutrinoClient(ActiveNet.Params, chainService)\n\t\t// \terr = chainClient.Start()\n\t\t// \tif err != nil {\n\t\t// \t\tlog<-cl.Errorf{\"couldn't start Neutrino client: %s\", err)\n\t\t// \t}\n\t\t// } else {\n\t\tchainClient, err = startChainRPC(certs)\n\t\tif err != nil {\n\t\t\tlog <- cl.Error{\n\t\t\t\t\"unable to open connection to consensus RPC server:\", err}\n\t\t\tcontinue\n\t\t}\n\t\t// }\n\t\t// Rather than inlining this logic directly into the loader\n\t\t// callback, a function variable is used to avoid running any of\n\t\t// this after the client disconnects by setting it to nil. This\n\t\t// prevents the callback from associating a wallet loaded at a\n\t\t// later time with a client that has already disconnected. A\n\t\t// mutex is used to make this concurrent safe.\n\t\tassociateRPCClient := func(w *wallet.Wallet) {\n\t\t\tw.SynchronizeRPC(chainClient)\n\t\t\tif legacyRPCServer != nil {\n\t\t\t\tlegacyRPCServer.SetChainServer(chainClient)\n\t\t\t}\n\t\t}\n\t\tmu := new(sync.Mutex)\n\t\tloader.RunAfterLoad(func(w *wallet.Wallet) {\n\t\t\tmu.Lock()\n\t\t\tassociate := associateRPCClient\n\t\t\tmu.Unlock()\n\t\t\tif associate != nil {\n\t\t\t\tassociate(w)\n\t\t\t}\n\t\t})\n\t\tchainClient.WaitForShutdown()\n\t\tmu.Lock()\n\t\tassociateRPCClient = nil\n\t\tmu.Unlock()\n\t\tloadedWallet, ok := loader.LoadedWallet()\n\t\tif ok {\n\t\t\t// Do not attempt a reconnect when the wallet was explicitly stopped.\n\t\t\tif loadedWallet.ShuttingDown() {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tloadedWallet.SetChainSynced(false)\n\t\t\t// TODO: Rework the wallet so changing the RPC client does not require stopping and restarting everything.\n\t\t\tloadedWallet.Stop()\n\t\t\tloadedWallet.WaitForShutdown()\n\t\t\tloadedWallet.Start()\n\t\t}\n\t}\n}", "func main() {\n\tr := mux.NewRouter()\n\theaders := handlers.AllowedHeaders([]string{\"X-Requested-With\", \"Content-Type\", \"Authorization\"})\n\tmethods := handlers.AllowedMethods([]string{\"GET\", \"POST\", \"PUT\", \"HEAD\", \"OPTIONS\"})\n\torigins := handlers.AllowedOrigins([]string{\"*\"})\n\n\tr.HandleFunc(\"/assets\", get_list_assets).Methods(\"GET\")\n\tr.HandleFunc(\"/assets\", post_asset).Methods(\"POST\")\n\n\tr.HandleFunc(\"/coins\", get_list_coins).Methods(\"GET\")\n\tr.HandleFunc(\"/coins\", post_coin).Methods(\"POST\")\n\n\tif err := http.ListenAndServe(\":5555\", handlers.CORS(headers, methods, origins)(r)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}", "func main() {\n\t//Init router\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/api/secp256k1\", DecodeSecp256k1Input).Methods(\"POST\")\n\tr.HandleFunc(\"/api/sha256\", DecodeSha256Input).Methods(\"POST\")\n\tlog.Fatal(http.ListenAndServe(\":8000\", r))\n}", "func (t *targetrunner) rebalanceHandler(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tcaller = r.Header.Get(cmn.HeaderCallerName)\n\t\tquery = r.URL.Query()\n\t\tgetRebData = cmn.IsParseBool(query.Get(cmn.URLParamRebData))\n\t)\n\tif !getRebData {\n\t\tt.invalmsghdlr(w, r, \"invalid request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tbody, status := t.rebManager.RebECDataStatus()\n\tif status != http.StatusOK {\n\t\tw.WriteHeader(status)\n\t\treturn\n\t}\n\n\tif ok := t.writeJSON(w, r, body, \"rebalance-data\"); !ok {\n\t\tglog.Errorf(\"Failed to send data to %s\", caller)\n\t}\n}", "func (s *Server) handleTransaction(client string, req *pb.Command) (err error) {\n\t// Get the transfer from the original command, will panic if nil\n\ttransfer := req.GetTransfer()\n\tmsg := fmt.Sprintf(\"starting transaction of %0.2f from %s to %s\", transfer.Amount, transfer.Account, transfer.Beneficiary)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Handle Demo UI errors before the account lookup\n\tif transfer.OriginatingVasp != \"\" && transfer.OriginatingVasp != s.vasp.Name {\n\t\tlog.Info().Str(\"requested\", transfer.OriginatingVasp).Str(\"local\", s.vasp.Name).Msg(\"requested originator does not match local VASP\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrWrongVASP, \"message sent to the wrong originator VASP\"),\n\t\t)\n\t}\n\n\t// Lookup the account associated with the transfer originator\n\tvar account Account\n\tif err = LookupAccount(s.db, transfer.Account).First(&account).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"account\", transfer.Account).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"account not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch account: %s\", err)\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"account %04d accessed successfully\", account.ID), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Lookup the wallet of the beneficiary\n\tvar beneficiary Wallet\n\tif err = LookupBeneficiary(s.db, transfer.Beneficiary).First(&beneficiary).Error; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tlog.Info().Str(\"beneficiary\", transfer.Beneficiary).Msg(\"not found\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrNotFound, \"beneficiary wallet not found\"),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Errorf(\"could not fetch beneficiary wallet: %s\", err)\n\t}\n\n\tif transfer.CheckBeneficiary {\n\t\tif transfer.BeneficiaryVasp != beneficiary.Provider.Name {\n\t\t\tlog.Info().\n\t\t\t\tStr(\"expected\", transfer.BeneficiaryVasp).\n\t\t\t\tStr(\"actual\", beneficiary.Provider.Name).\n\t\t\t\tMsg(\"check beneficiary failed\")\n\t\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\t\tpb.Errorf(pb.ErrWrongVASP, \"beneficiary wallet does not match beneficiary vasp\"),\n\t\t\t)\n\t\t}\n\t}\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"wallet %s provided by %s\", beneficiary.Address, beneficiary.Provider.Name), pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// TODO: lookup peer from cache rather than always doing a directory service lookup\n\tvar peer *peers.Peer\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"search for %s in directory service\", beneficiary.Provider.Name), pb.MessageCategory_TRISADS)\n\tif peer, err = s.peers.Search(beneficiary.Provider.Name); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not search peer from directory service\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not search peer from directory service\"),\n\t\t)\n\t}\n\tinfo := peer.Info()\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"identified TRISA remote peer %s at %s via directory service\", info.ID, info.Endpoint), pb.MessageCategory_TRISADS)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\tvar signKey *rsa.PublicKey\n\ts.updates.Broadcast(req.Id, \"exchanging peer signing keys\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\tif signKey, err = peer.ExchangeKeys(true); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not exchange keys with remote peer\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not exchange keyrs with remote peer\"),\n\t\t)\n\t}\n\n\t// Prepare the transaction\n\t// Save the pending transaction and increment the accounts pending field\n\txfer := Transaction{\n\t\tEnvelope: uuid.New().String(),\n\t\tAccount: account,\n\t\tAmount: decimal.NewFromFloat32(transfer.Amount),\n\t\tDebit: true,\n\t\tCompleted: false,\n\t}\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save transaction\"),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending++\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save originator account\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not save originator account\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"ready to execute transaction\", pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Create an identity and transaction payload for TRISA exchange\n\ttransaction := &generic.Transaction{\n\t\tTxid: fmt.Sprintf(\"%d\", xfer.ID),\n\t\tOriginator: account.WalletAddress,\n\t\tBeneficiary: beneficiary.Address,\n\t\tAmount: float64(transfer.Amount),\n\t\tNetwork: \"TestNet\",\n\t\tTimestamp: xfer.Timestamp.Format(time.RFC3339),\n\t}\n\tidentity := &ivms101.IdentityPayload{\n\t\tOriginator: &ivms101.Originator{},\n\t\tOriginatingVasp: &ivms101.OriginatingVasp{},\n\t}\n\tif identity.OriginatingVasp.OriginatingVasp, err = s.vasp.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator vasp\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator vasp\"),\n\t\t)\n\t}\n\n\tidentity.Originator = &ivms101.Originator{\n\t\tOriginatorPersons: make([]*ivms101.Person, 0, 1),\n\t\tAccountNumbers: []string{account.WalletAddress},\n\t}\n\tvar originator *ivms101.Person\n\tif originator, err = account.LoadIdentity(); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not load originator identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not load originator identity\"),\n\t\t)\n\t}\n\tidentity.Originator.OriginatorPersons = append(identity.Originator.OriginatorPersons, originator)\n\n\tpayload := &protocol.Payload{}\n\tif payload.Transaction, err = anypb.New(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize transaction payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize transaction payload\"),\n\t\t)\n\t}\n\tif payload.Identity, err = anypb.New(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not serialize identity payload\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not serialize identity payload\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"transaction and identity payload constructed\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Secure the envelope with the remote beneficiary's signing keys\n\tvar envelope *protocol.SecureEnvelope\n\tif envelope, err = handler.New(xfer.Envelope, payload, nil).Seal(signKey); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not create or sign secure envelope\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not create or sign secure envelope\"),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"secure envelope %s sealed: encrypted with AES-GCM and RSA - sending ...\", envelope.Id), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Conduct the TRISA transaction, handle errors and send back to user\n\tif envelope, err = peer.Transfer(envelope); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not perform TRISA exchange\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"received %s information exchange reply from %s\", envelope.Id, peer.String()), pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Open the response envelope with local private keys\n\tvar opened *handler.Envelope\n\tif opened, err = handler.Open(envelope, s.trisa.sign); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unseal TRISA response\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Verify the contents of the response\n\tpayload = opened.Payload\n\tif payload.Identity.TypeUrl != \"type.googleapis.com/ivms101.IdentityPayload\" {\n\t\tlog.Warn().Str(\"type\", payload.Identity.TypeUrl).Msg(\"unsupported identity type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported identity type\", payload.Identity.TypeUrl),\n\t\t)\n\t}\n\n\tif payload.Transaction.TypeUrl != \"type.googleapis.com/trisa.data.generic.v1beta1.Transaction\" {\n\t\tlog.Warn().Str(\"type\", payload.Transaction.TypeUrl).Msg(\"unsupported transaction type\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"unsupported transaction type\", payload.Transaction.TypeUrl),\n\t\t)\n\t}\n\n\tidentity = &ivms101.IdentityPayload{}\n\ttransaction = &generic.Transaction{}\n\tif err = payload.Identity.UnmarshalTo(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal identity\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\tif err = payload.Transaction.UnmarshalTo(transaction); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not unmarshal transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\ts.updates.Broadcast(req.Id, \"successfully decrypted and parsed secure envelope\", pb.MessageCategory_TRISAP2P)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\t// Update the completed transaction and save to disk\n\txfer.Beneficiary = Identity{\n\t\tWalletAddress: transaction.Beneficiary,\n\t}\n\txfer.Completed = true\n\txfer.Timestamp, _ = time.Parse(time.RFC3339, transaction.Timestamp)\n\n\t// Serialize the identity information as JSON data\n\tvar data []byte\n\tif data, err = json.Marshal(identity); err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, \"could not marshal IVMS 101 identity\"),\n\t\t)\n\t}\n\txfer.Identity = string(data)\n\n\tif err = s.db.Save(&xfer).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\t// Save the pending transaction on the account\n\t// TODO: remove pending transactions\n\taccount.Pending--\n\taccount.Completed++\n\taccount.Balance.Sub(xfer.Amount)\n\tif err = s.db.Save(&account).Error; err != nil {\n\t\tlog.Error().Err(err).Msg(\"could not save transaction\")\n\t\treturn s.updates.SendTransferError(client, req.Id,\n\t\t\tpb.Errorf(pb.ErrInternal, err.Error()),\n\t\t)\n\t}\n\n\tmsg = fmt.Sprintf(\"transaction %04d complete: %s transfered from %s to %s\", xfer.ID, xfer.Amount.String(), xfer.Originator.WalletAddress, xfer.Beneficiary.WalletAddress)\n\ts.updates.Broadcast(req.Id, msg, pb.MessageCategory_BLOCKCHAIN)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\ts.updates.Broadcast(req.Id, fmt.Sprintf(\"%04d new account balance: %s\", account.ID, account.Balance), pb.MessageCategory_LEDGER)\n\ttime.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)\n\n\trep := &pb.Message{\n\t\tType: pb.RPC_TRANSFER,\n\t\tId: req.Id,\n\t\tTimestamp: time.Now().Format(time.RFC3339),\n\t\tCategory: pb.MessageCategory_LEDGER,\n\t\tReply: &pb.Message_Transfer{Transfer: &pb.TransferReply{\n\t\t\tTransaction: xfer.Proto(),\n\t\t}},\n\t}\n\n\treturn s.updates.Send(client, rep)\n}", "func (app *Application) GetLogisticsHandler(w http.ResponseWriter, r *http.Request) {\n\tvar data map[string]interface{}\n\tvar tInfo webutil.TransitInfo\n\tdata = make(map[string]interface{})\n\tuName := webutil.MySession.GetUserName(r)\n\toName := webutil.MySession.GetOrgName(r)\n\t//oName := webutil.MySession.GetOrgName(r)\n\tif len(uName) == 0 {\n\t\thttp.Redirect(w, r, \"./login.html\", 302)\n\t\treturn\n\t}\n\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tuName := webutil.MySession.GetUserName(r)\n\t\toName := webutil.MySession.GetOrgName(r)\n\t\tif fSetup, ok := app.Fabric[uName]; ok {\n\t\t\t//befor send request we need to check session\n\n\t\t\tvar cn string\n\t\t\tvar ccn string\n\t\t\tvar fcn string\n\t\t\t//find cfg name\n\t\t\tfor _, v := range webutil.Orgnization[oName] {\n\t\t\t\tif v.UserName == uName {\n\t\t\t\t\tcn = v.UserOperation[\"GetLogistics\"].ChannelName\n\t\t\t\t\tccn = v.UserOperation[\"GetLogistics\"].CCName\n\t\t\t\t\tfcn = v.UserOperation[\"GetLogistics\"].Fcn\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Println(\"cn,ccn,fcn GetLogistics is\", cn, ccn, fcn)\n\t\t\tkey := webutil.PhoneType + r.FormValue(\"bnumber\")\n\n\t\t\tcompanyInfo, err := fSetup.QueryCC(cn, ccn, fcn, []byte(key))\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, \"Unable to invoke hello in the blockchain\", 500)\n\t\t\t}\n\t\t\tjson.Unmarshal([]byte(companyInfo), &tInfo)\n\t\t\tfmt.Println(\"logistics is cinfo is\", companyInfo, tInfo)\n\t\t}\n\t\tdata[\"LogisticsInfo\"] = tInfo.ConcreteTransitInfo\n\t\t// txid, err := app.Fabric.InvokeSupplier(passargs)\n\t}\n\tfmt.Println(\"org and username\", oName, uName)\n\tvar batch []string\n\tif oName == \"smartphone\" {\n\t\tbatch = app.GetPhoneBatchInfo(\"logistics\", uName)\n\t} else {\n\t\tbatch = app.GetBatchInfo(oName, uName)\n\t}\n\tdata[\"BatchInfo\"] = batch\n\trenderTemplate(w, r, \"getlogistics.html\", data)\n}", "func (as *AddrServer) HandleRawTxGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\taddr := mux.Vars(r)[\"txid\"]\n\n\t// paginate through transactions\n\ttxns, err := as.GetRawTransaction(addr)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error fetching all transactions for address\", err))\n\t\treturn\n\t}\n\tout, _ := json.Marshal(map[string]string{\"rawtx\": txns.Result.Hex})\n\tw.Write(out)\n}", "func (sc *SuperChain) chainRegister(stub shim.ChaincodeStubInterface, args []string) pb.Response{\n\tif len(args) != 5 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 5\")\n\t}\n\n\tinfo := args[0]\n\tip := args[1]\n\tserial := args[2]\n\tcsr := args[3]\n\torgCACert := args[4]\n\n\t// create cert\n\tcert,err := sc.CreateCertWithCsr(stub, []byte(csr))\n\tif err != nil{\n\t\treturn shim.Error(fmt.Errorf(\"create cert with csr error: %w\", err).Error())\n\t}\n\n\t// create ID\n\ttempString := info + ip + serial\n\tSha1Inst := sha1.New()\n\tio.WriteString(Sha1Inst,tempString)\n\tchainID := fmt.Sprintf(\"%x\",Sha1Inst.Sum(nil))\n\n\t// create chain struct\n\tchain := Chain{\n\t\tID: chainID,\n\t\tINFO: info,\n\t\tIP: ip,\n\t\tSERIAL: serial,\n\t}\n\tchainJson, err := json.Marshal(chain)\n\tif err != nil {\n\t\treturn shim.Error(fmt.Errorf(\"chain json marshal error: %w\", err).Error())\n\t}\n\n\t// save chain\n\tif err := stub.PutState(chain.ID, chainJson); err != nil {\n\t\treturn shim.Error(fmt.Errorf(\"save chain error: %w\").Error())\n\t}\n\n\t// save chain's org ca cert\n\tif err := stub.PutState(ToChainOrgCertID(chain.ID), []byte(orgCACert)); err != nil {\n\t\treturn shim.Error(fmt.Errorf(\"save chain's org ca cert error: %w\", err).Error())\n\t}\n\n\t// get root certificate\n\trootCertificateByte, err := stub.GetState(RootCertificate)\n\tif err != nil {\n\t\treturn shim.Error(fmt.Errorf(\"get root certificate error: %w\", err).Error())\n\t}\n\n\t// create return struct\n\trtr := ReturnToRegister{\n\t\tID: chain.ID,\n\t\tCERT: string(cert),\n\t\tROOTCERT: string(rootCertificateByte),\n\t}\n\trtrJson, err := json.Marshal(rtr)\n\tif err != nil {\n\t\treturn shim.Error(fmt.Errorf(\"rtr json marshal error: %w\", err).Error())\n\t}\n\n\treturn shim.Success(rtrJson)\n}", "func (network *Network) HTTPhandler(w http.ResponseWriter, r *http.Request){\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tbody, error := ioutil.ReadAll(r.Body) // Read Request\n\t\tdefer r.Body.Close() // Always CLOSE.\n\t\t// Check for errors or if body is empty.\n\t\tif error != nil || removeQuotationMarks(string(body)) == \"\" {\n\t\t\thttp.Error(w, \"ERROR\", http.StatusBadRequest)\n\t\t\tfmt.Println(\"Error when POST\")\n\t\t} else{\n\t\t\t// Same as in Cli.go Store\n\t\t\thashedFileString := NewKademliaIDFromData(string(body))\n\t\t\tnetwork.Store([]byte(body),hashedFileString)\n\t\t\thashSuffix := hashedFileString.String()\n\n\t\t\tmessage := map[string]string{ hashSuffix: string(body)} // JSON DATA FORMAT\n\t\t\tjsonValue,_ := json.Marshal(message)\n\n\t\t\tw.Header().Set(\"Location\", URLprefix+hashSuffix)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusCreated)\t// Status 201 as detailed\n\n\t\t\tw.Write(jsonValue)\n\t\t\tfmt.Println(\"HTTP Data Written. Hash = \", hashSuffix )\n\t\t}\n\tcase \"GET\":\n\t\t// Checks if there is something after the prefix. /objects/XXXXXXXXXXXXXX\n\t\tURLcomponents := strings.Split(r.URL.Path, \"/\")\t// [ \"\", \"objects\", \"hash\" ]\n\t\thashValue := URLcomponents[2]\n\t\t// Check if there is a hashvalue of correct size.\n\t\tif(len(hashValue) != 40){\n\t\t\thttp.Error(w, \"ERROR\", http.StatusLengthRequired)\n\t\t\tfmt.Println(\"Error when GET \", hashValue, \" is not of correct length. (40)\")\n\t\t}else{\n\t\t\t\t// Same as in Cli.go Get\n\t\t\t\thash := NewKademliaID(hashValue)\n\t\t\t\tdata, nodes := network.DataLookup(hash)\n\t\t\t\tif data != nil {\n\t\t\t\t\t// If data is not nil, send OK status and write.\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(data)\n\t\t\t\t\tfmt.Println(\"HTTP Data Read. Input was = \", string(data) )\n\t\t\t\t} else if len(nodes) > 0{\n\t\t\t\t\thttp.Error(w, \"ERROR\", http.StatusNotFound)\n\t\t\t\t\tfmt.Println(\"Error when GET - DataLookUP (Length)\")\n\t\t\t\t} else {\n\t\t\t\t\thttp.Error(w, \"ERROR\", http.StatusNoContent)\n\t\t\t\t\tfmt.Println(\"Error when GET - DataLookUP\")\n\t\t\t\t}\n\t\t}\n\tdefault:\n\t\thttp.Error(w, \"Wrong. Use POST or GET\", http.StatusMethodNotAllowed)\n\t}\n}", "func (d *Daemon) connectHandler(w *rest.ResponseWriter, r *rest.Request) {\n\tvar id string\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\tApiResponse(w, 500, \"BAD_REQUEST\")\n\t\treturn\n\t}\n\n\t_, hasFrom := r.Form[\"from\"]\n\tif hasFrom == false {\n\t\tApiResponse(w, 500, \"MISSING_FROM_BLOCK_ID\")\n\t\treturn\n\t}\n\n\t_, hasTo := r.Form[\"to\"]\n\tif hasTo == false {\n\t\tApiResponse(w, 500, \"MISSING_TO_BLOCK_ID\")\n\t\treturn\n\t}\n\n\tfID, hasID := r.Form[\"id\"]\n\tif hasID == false {\n\t\tid = <-idChan\n\t} else {\n\n\t\tif len(strings.TrimSpace(fID[0])) == 0 {\n\t\t\tApiResponse(w, 500, \"BAD_CONNECTION_ID\")\n\t\t\treturn\n\t\t}\n\n\t\t_, ok := d.blockMap[fID[0]]\n\t\tif ok == false {\n\t\t\tid = fID[0]\n\t\t} else {\n\t\t\tApiResponse(w, 500, \"BLOCK_ID_ALREADY_EXISTS\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tfrom := r.Form[\"from\"][0]\n\tto := r.Form[\"to\"][0]\n\n\tif len(from) == 0 {\n\t\tApiResponse(w, 500, \"MISSING_FROM_BLOCK_ID\")\n\t\treturn\n\t}\n\n\tif len(to) == 0 {\n\t\tApiResponse(w, 500, \"MISSING_TO_BLOCK_ID\")\n\t\treturn\n\t}\n\n\t_, exists := d.blockMap[from]\n\tif exists == false {\n\t\tApiResponse(w, 500, \"FROM_BLOCK_NOT_FOUND\")\n\t\treturn\n\t}\n\n\t_, exists = d.blockMap[strings.Split(to, \"/\")[0]]\n\tif exists == false {\n\t\tApiResponse(w, 500, \"TO_BLOCK_NOT_FOUND\")\n\t\treturn\n\t}\n\n\terr = d.CreateConnection(from, to, id)\n\tif err != nil {\n\t\tApiResponse(w, 500, \"TO_ROUTE_NOT_FOUND\")\n\t\treturn\n\t}\n\n\tApiResponse(w, 200, \"CONNECTION_CREATED\")\n}", "func (as *AddrServer) HandleGetBlock(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tblockhash := mux.Vars(r)[\"blockHash\"]\n\n\t// Make the chainhash for fetching data\n\thash, err := chainhash.NewHashFromStr(blockhash)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error parsing txhash\", err))\n\t\treturn\n\t}\n\n\t// paginate through transactions\n\tblock, err := as.Client.GetBlockVerbose(hash)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error fetching block\", err))\n\t\treturn\n\t}\n\tout, _ := json.Marshal(block)\n\tw.Write(out)\n}", "func handleKVRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest) () {\n\tlog.Println(\"start handling request\")\n\tlog.Println(msgID)\n\tlog.Println(\"sender IP:\", net.IPv4(msgID[0], msgID[1], msgID[2], msgID[3]).String(), \":\", binary.LittleEndian.Uint16(msgID[4:6]))\n\tlog.Println(\"command:\", reqPay.Command)\n\tif reqPay.Addr == nil {\n\n\t\treqPay.Addr = []byte(clientAddr.String())\n\t}\n\n\t// Try to find the response in the cache\n\tif respMsgBytes, ok := GetCachedResponse(msgID); ok {\n\t\t// Send the message back to the client\n\t\t_, _ = conn.WriteToUDP(respMsgBytes, clientAddr)\n\t} else {\n\t\t// Handle the command\n\t\trespPay := pb.KVResponse{}\n\n\t\t/*\n\t\t\tIf the command is PUT, GET or REMOVE, check whether the key exists in\n\t\t\tthis node first. Otherwise,\n\t\t*/\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\t// respPay.ErrCode = Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase GET:\n\t\t\t// var version int32\n\t\t\t// respPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t// respPay.Version = &version\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\tvar version int32\n\t\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\t\trespPay.Version = version\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay, msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\tif node, existed := checkNode(reqPay.Key); existed {\n\t\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t} else {\n\t\t\t\tsendRequestToCorrectNode(node, reqPay,msgID)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\t//log.Println(\"############################################################################\")\n\t\t\t//log.Println(\"########################### SHUT DOWN ! ####################################\")\n\t\t\t//log.Println(\"############################################################################\")\n\n\t\t\tshutdown <- true\n\t\t\treturn\n\t\tcase WIPEOUT:\n\t\t\trespPay.ErrCode = RemoveAll()\n\t\t\tnormalReplicate(WIPEOUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := int32(1) // Unused, return 1 for now\n\t\t\trespPay.MembershipCount = members\n\t\t\trespPay.ErrCode = NO_ERR\n\t\tcase GET_MEMBERSHIP_LIST:\n\t\t\tGetMemberShipList(clientAddr, msgID, respPay)\n\t\t\treturn\n\t\t//forward request\n\t\tcase PUT_FORWARD:\n\t\t\trespPay.ErrCode = Put(reqPay.Key, reqPay.Value, &reqPay.Version)\n\t\t\tnormalReplicate(PUT, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase GET_FORWARD:\n\t\t\tvar version int32\n\t\t\trespPay.Value, version, respPay.ErrCode = Get(reqPay.Key)\n\t\t\trespPay.Version = version\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase REMOVE_FORWARD:\n\t\t\t// respPay.ErrCode = Remove(reqPay.Key)\n\t\t\trespPay.ErrCode = Remove(reqPay.Key)\n\t\t\tnormalReplicate(REMOVE, reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\tclientAddr, _ = net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\n\t\tcase PUT_REPLICATE_SON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 0)\n\t\t\treturn\n\t\tcase PUT_REPLICATE_GRANDSON:\n\t\t\tPutReplicate(reqPay.Key, reqPay.Value, &reqPay.Version, 1)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_SON:\n\t\t\tRemoveReplicate(reqPay.Key, 0)\n\t\t\treturn\n\t\tcase REMOVE_REPLICATE_GRANDSON:\n\t\t\tRemoveReplicate(reqPay.Key, 1)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_SON:\n\t\t\tWipeoutReplicate(0)\n\t\t\treturn\n\t\tcase WIPEOUT_REPLICATE_GRANDSON:\n\t\t\tWipeoutReplicate(1)\n\t\t\treturn\n\n\t\tcase GRANDSON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(FATHER_DIED, KVStore, addr)\n\t\t\treturn\n\t\tcase SON_DIED:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\",string(reqPay.Addr))\n\t\t\tsendNodeDieReplicateRequest(GRANDFATHER_DIED_1, KVStore, addr)\n\t\t\treturn\n\n\t\tcase HELLO:\n\t\t\taddr, _ := net.ResolveUDPAddr(\"udp\", string(reqPay.Addr))\n\t\t\treceiveHello(addr, msgID)\n\t\t\treturn\n\t\tdefault:\n\t\t\trespPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t}\n\n\t\t// Send the response\n\t\tsendResponse(clientAddr, msgID, respPay)\n\t}\n}", "func rootHandler(w http.ResponseWriter, r *http.Request) {\n\tparts := strings.Split(r.URL.Path, \"/\")\n\tif r.URL.Path == \"/igcinfo/api/\" {\n\t\tinfoHandler(w, r)\n\t\treturn\n\t} else if r.URL.Path == \"/igcinfo/api/igc/\" {\n\t\tigcHandler(w, r)\n\t\treturn\n\t} else if id, err := uuid.Parse(parts[4]); strings.HasPrefix(r.URL.Path, \"/igcinfo/api/igc/\") && err == nil && len(parts) < 6 {\n\t\ttrackHandler(w, r, id)\n\t\treturn\n\t} else if id, err := uuid.Parse(parts[4]); strings.HasPrefix(r.URL.Path, \"/igcinfo/api/igc/\") && err == nil && len(parts[5]) > 0 {\n\t\ttrackFieldHandler(w, r, id, parts[5])\n\t\treturn\n\t}\n\n\thttp.NotFound(w, r)\n}", "func (_tree *tree) serve(reqCtx *fasthttp.RequestCtx, path string) bool {\n\tctx := _tree.pool.Get().(*Context)\n\tctx.Reset(reqCtx)\n\tmiddleware, params, mustRedirect := _tree.rootBranch.GetBranch(path, ctx.Params) // pass the parameters here for 0 allocation\n\tif middleware != nil {\n\t\tctx.Params = params\n\t\tctx.middleware = middleware\n\t\t//ctx.Request.Header.SetUserAgentBytes(DefaultUserAgent)\n\t\tctx.Do()\n\t\t_tree.pool.Put(ctx)\n\t\treturn true\n\t} else if mustRedirect && !_tree.station.config.DisablePathCorrection && !bytes.Equal(reqCtx.Method(), MethodConnectBytes) {\n\n\t\treqPath := path\n\t\tpathLen := len(reqPath)\n\n\t\tif pathLen > 1 {\n\n\t\t\tif reqPath[pathLen-1] == '/' {\n\t\t\t\treqPath = reqPath[:pathLen-1] //remove the last /\n\t\t\t} else {\n\t\t\t\t//it has path prefix, it doesn't ends with / and it hasn't be found, then just add the slash\n\t\t\t\treqPath = reqPath + \"/\"\n\t\t\t}\n\n\t\t\tctx.Request.URI().SetPath(reqPath)\n\t\t\turlToRedirect := utils.BytesToString(ctx.Request.RequestURI())\n\n\t\t\tctx.Redirect(urlToRedirect, 301) //\tStatusMovedPermanently\n\t\t\t// RFC2616 recommends that a short note \"SHOULD\" be included in the\n\t\t\t// response because older user agents may not understand 301/307.\n\t\t\t// Shouldn't send the response for POST or HEAD; that leaves GET.\n\t\t\tif _tree.method == MethodGet {\n\t\t\t\tnote := \"<a href=\\\"\" + utils.HTMLEscape(urlToRedirect) + \"\\\">Moved Permanently</a>.\\n\"\n\t\t\t\tctx.Write(note)\n\t\t\t}\n\t\t\t_tree.pool.Put(ctx)\n\t\t\treturn true\n\t\t}\n\t}\n\n\t_tree.pool.Put(ctx)\n\treturn false\n}", "func (h HTTPHandler) HandlePeers(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\tpeers := h.p2p.GetPeers()\n\tif bytes.Compare(peers, []byte(\"null\")) == 0 {\n\t\tpeers = []byte(\"[]\")\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(peers)\n}", "func Router(clientRedis *services.RedisClient, gateWayClient *services.GateWayClient) *mux.Router {\n\n\t//Routing\n\trouter := mux.NewRouter()\n\tsubRouter := router.PathPrefix(\"/api/v1/\").Subrouter()\n\t//Cart routes\n\tsubRouter.HandleFunc(\"/carts/{ID}\", HandleCartGet(clientRedis)).Methods(\"GET\")\n\tsubRouter.HandleFunc(\"/carts\", HandleCartPost(clientRedis, gateWayClient)).Methods(\"POST\")\n\tsubRouter.HandleFunc(\"/carts\", HandleCartPut(clientRedis, gateWayClient)).Methods(\"PUT\")\n\tsubRouter.HandleFunc(\"/carts/{ID}\", HandleCartDelete(clientRedis)).Methods(\"DELETE\")\n\t//CartElment routes\n\tsubRouter.HandleFunc(\"/carts/{customerID}/elements/{elementID}\", HandleCartElementGet(clientRedis)).Methods(\"GET\")\n\tsubRouter.HandleFunc(\"/carts/elements\", HandleCartElementPost(clientRedis, gateWayClient)).Methods(\"POST\")\n\tsubRouter.HandleFunc(\"/carts/elements\", HandleCartElementPut(clientRedis, gateWayClient)).Methods(\"PUT\")\n\tsubRouter.HandleFunc(\"/carts/{customerID}/elements/{elementID}\", HandleCartElementDelete(clientRedis)).Methods(\"DELETE\")\n\n\treturn router\n\n}", "func handleRequest(clientAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte) {\n\tif respMsgBytes := responseCache.Get(msgID, getNetAddress(clientAddr)); respMsgBytes != nil {\n\t\tfmt.Println(\"Handle repeated request - 😡\", respMsgBytes, \"sending to \", clientAddr.Port)\n\n\t\t_, err := conn.WriteToUDP(respMsgBytes, clientAddr)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"handleRequest WriteToUDP\", err)\n\t\t}\n\t} else {\n\t\tincomingCache.Add(msgID, clientAddr)\n\n\t\trespPay := pb.KVResponse{}\n\t\tswitch reqPay.Command {\n\t\tcase PUT:\n\t\t\tfmt.Println(\"+PUT request come in from\", clientAddr.Port)\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\n\t\t\t\tfmt.Println(\"who's sending responsee 🤡 \", self.Addr.String(), \" to \", clientAddr.Port)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second) {\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Put(reqPay.Key, reqPay.Value, reqPay.Version)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase GET:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tvar version int32\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[0].Get(reqPay.Key)\n\t\t\t\trespPay.Version = &version\n\t\t\t\t// TODO: check failure, then send request to other two nodes.\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\n\t\t\t\trespPay.Value, version, respPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Get(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase REMOVE:\n\t\t\tnode := NodeForKey(reqPay.Key)\n\t\t\tif node.IsSelf && reqPay.ReplicaNum == nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].Remove(reqPay.Key)\n\n\t\t\t\tmsgId := requestToReplicaNode(self.nextNode(), reqPay, 1)\n\t\t\t\tmsgId2 := requestToReplicaNode(self.nextNode().nextNode(), reqPay, 2)\n\t\t\t\tif waitingForResonse(msgId, time.Second) && waitingForResonse(msgId2, time.Second){\n\t\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t\t} else {\n\t\t\t\t\t// TODO: revert primary, send error (can't revert primary lol)\n\t\t\t\t\tfmt.Println(\"????? can't remove fully??\")\n\t\t\t\t}\n\t\t\t} else if reqPay.ReplicaNum != nil {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[*reqPay.ReplicaNum].Remove(reqPay.Key)\n\t\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\t\t} else {\n\t\t\t\tforwardRequest(clientAddr, msgID, reqPay, rawMsg, node)\n\t\t\t}\n\t\tcase SHUTDOWN:\n\t\t\tshutdown <- true\n\t\tcase WIPEOUT:\n\t\t\tif reqPay.ReplicaNum != nil {\n\t\t\t\tdataStorage.Replicas[*reqPay.ReplicaNum].RemoveAll()\n\t\t\t} else {\n\t\t\t\trespPay.ErrCode = dataStorage.Replicas[0].RemoveAll()\n\t\t\t\tdataStorage.Replicas[1].RemoveAll()\n\t\t\t\tdataStorage.Replicas[2].RemoveAll()\n\t\t\t}\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase IS_ALIVE:\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_PID:\n\t\t\tpid := int32(os.Getpid())\n\t\t\trespPay.Pid = &pid\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase GET_MEMBERSHIP_CNT:\n\t\t\tmembers := GetMembershipCount()\n\t\t\trespPay.MembershipCount = &members\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase NOTIFY_FAUILURE:\n\t\t\tfailedNode := GetNodeByIpPort(*reqPay.NodeIpPort)\n\t\t\tif failedNode != nil {\n\t\t\t\tfmt.Println(self.Addr.String(), \" STARTT CONTIUE GOSSSSSSIP 👻💩💩💩💩💩🤢🤢🤢🤢\", *reqPay.NodeIpPort, \"failed\")\n\t\t\t\tRemoveNode(failedNode)\n\t\t\t\tstartGossipFailure(failedNode)\n\t\t\t}\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase ADD_REPLICA:\n\t\t\tkv := dataStorage.decompressReplica(reqPay.Value)\n\t\t\tdataStorage.addReplica(kv, int(*reqPay.ReplicaNum))\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase SEND_REPLICA:\n\t\t\trespPay.Value = dataStorage.compressReplica(int(*reqPay.ReplicaNum))\n\t\t\trespPay.ReceiveData = true\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase RECOVER_PREV_NODE_KEYSPACE:\n\t\t\t// TODO: error handling on and internal failure\n\t\t\tRecoverDataStorage()\n\n\t\t\trespPay.ErrCode = NO_ERR\n\t\t\tsendResponse(clientAddr, msgID, respPay)\n\t\tcase TEST_GOSSIP:\n\t\t\tfmt.Println(self.Addr.String(), \" TESTING GOSSIP 😡\", *reqPay.NodeIpPort, \"failed\")\n\t\t\tRemoveNode(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\t\tstartGossipFailure(GetNodeByIpPort(\"127.0.0.1:3331\"))\n\t\tcase TEST_RECOVER_REPLICA:\n\t\t\treqPay := pb.KVRequest{Command: SHUTDOWN}\n\t\t\tsendRequestToNodeUUID(reqPay, self.prevNode())\n\t\t\tRemoveNode(self.prevNode())\n\n\t\t\tRecoverDataStorage()\n\t\tdefault:\n\t\t\t//respPay.ErrCode = UNKNOWN_CMD_ERR\n\t\t\t//sendResponse(clientAddr, msgID, respPay)\n\t\t}\n\t}\n\tprintReplicas(self.Addr.String())\n}", "func (c *MainChannelCC) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n funcName, args := stub.GetFunctionAndParameters()\n\n switch funcName {\n // 任务上传\n case \"requestUpload\":\n return requestUpload(stub, args)\n // 查询任务\n case \"requestQuery\":\n return requestQuery(stub, args)\n // 查询全部任务\n case \"requestQueryArr\":\n return requestQueryArr(stub, args)\n // 难度值上传\n case \"difficultyUpload\":\n return difficultyUpload(stub, args)\n // 难度值查询\n case \"difficultyQuery\":\n return difficultyQuery(stub, args)\n // 难度值统一查询\n case \"difficultyQueryArr\":\n return difficultyQueryArr(stub, args)\n // 判断胜利者\n case \"winnerUpload\":\n return winnerUpload(stub, args)\n // 查询胜利者\n case \"winnerQuery\":\n return winnerQuery(stub, args)\n // 查询全部胜利者\n case \"winnerQueryArr\":\n return winnerQueryArr(stub, args)\n // 子channel上传\n case \"subChannelUpload\":\n return subChannelUpload(stub, args)\n // 子channel查询\n case \"subChannelQuery\":\n return subChannelQuery(stub, args)\n // 数据上传\n case \"dataUpload\":\n return dataUpload(stub, args)\n // 查询数据\n case \"dataQuery\":\n return dataQuery(stub, args)\n // 数据统一查询\n case \"dataQueryArr\":\n return dataQueryArr(stub, args)\n // 奖励发放\n case \"rewardsUpload\":\n return rewardsUpload(stub, args)\n // 奖励获取\n case \"rewardsReceive\":\n return rewardsReceive(stub, args)\n }\n\n\treturn shim.Success(nil)\n}", "func (srv *Server) walletTransactionHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\t// Parse the id from the url.\n\tvar id types.TransactionID\n\tjsonID := \"\\\"\" + ps.ByName(\"id\") + \"\\\"\"\n\terr := id.UnmarshalJSON([]byte(jsonID))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/history: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttxn, ok := srv.wallet.Transaction(id)\n\tif !ok {\n\t\twriteError(w, \"error when calling /wallet/transaction/$(id): transaction not found\", http.StatusBadRequest)\n\t\treturn\n\t}\n\twriteJSON(w, WalletTransactionGETid{\n\t\tTransaction: txn,\n\t})\n}", "func (v *VirtualMachinesServerTransport) Do(req *http.Request) (*http.Response, error) {\n\trawMethod := req.Context().Value(runtime.CtxAPINameKey{})\n\tmethod, ok := rawMethod.(string)\n\tif !ok {\n\t\treturn nil, nonRetriableError{errors.New(\"unable to dispatch request, missing value for CtxAPINameKey\")}\n\t}\n\n\tvar resp *http.Response\n\tvar err error\n\n\tswitch method {\n\tcase \"VirtualMachinesClient.BeginAssessPatches\":\n\t\tresp, err = v.dispatchBeginAssessPatches(req)\n\tcase \"VirtualMachinesClient.BeginCapture\":\n\t\tresp, err = v.dispatchBeginCapture(req)\n\tcase \"VirtualMachinesClient.BeginConvertToManagedDisks\":\n\t\tresp, err = v.dispatchBeginConvertToManagedDisks(req)\n\tcase \"VirtualMachinesClient.BeginCreateOrUpdate\":\n\t\tresp, err = v.dispatchBeginCreateOrUpdate(req)\n\tcase \"VirtualMachinesClient.BeginDeallocate\":\n\t\tresp, err = v.dispatchBeginDeallocate(req)\n\tcase \"VirtualMachinesClient.BeginDelete\":\n\t\tresp, err = v.dispatchBeginDelete(req)\n\tcase \"VirtualMachinesClient.Generalize\":\n\t\tresp, err = v.dispatchGeneralize(req)\n\tcase \"VirtualMachinesClient.Get\":\n\t\tresp, err = v.dispatchGet(req)\n\tcase \"VirtualMachinesClient.BeginInstallPatches\":\n\t\tresp, err = v.dispatchBeginInstallPatches(req)\n\tcase \"VirtualMachinesClient.InstanceView\":\n\t\tresp, err = v.dispatchInstanceView(req)\n\tcase \"VirtualMachinesClient.NewListPager\":\n\t\tresp, err = v.dispatchNewListPager(req)\n\tcase \"VirtualMachinesClient.NewListAllPager\":\n\t\tresp, err = v.dispatchNewListAllPager(req)\n\tcase \"VirtualMachinesClient.NewListAvailableSizesPager\":\n\t\tresp, err = v.dispatchNewListAvailableSizesPager(req)\n\tcase \"VirtualMachinesClient.NewListByLocationPager\":\n\t\tresp, err = v.dispatchNewListByLocationPager(req)\n\tcase \"VirtualMachinesClient.BeginPerformMaintenance\":\n\t\tresp, err = v.dispatchBeginPerformMaintenance(req)\n\tcase \"VirtualMachinesClient.BeginPowerOff\":\n\t\tresp, err = v.dispatchBeginPowerOff(req)\n\tcase \"VirtualMachinesClient.BeginReapply\":\n\t\tresp, err = v.dispatchBeginReapply(req)\n\tcase \"VirtualMachinesClient.BeginRedeploy\":\n\t\tresp, err = v.dispatchBeginRedeploy(req)\n\tcase \"VirtualMachinesClient.BeginReimage\":\n\t\tresp, err = v.dispatchBeginReimage(req)\n\tcase \"VirtualMachinesClient.BeginRestart\":\n\t\tresp, err = v.dispatchBeginRestart(req)\n\tcase \"VirtualMachinesClient.RetrieveBootDiagnosticsData\":\n\t\tresp, err = v.dispatchRetrieveBootDiagnosticsData(req)\n\tcase \"VirtualMachinesClient.BeginRunCommand\":\n\t\tresp, err = v.dispatchBeginRunCommand(req)\n\tcase \"VirtualMachinesClient.SimulateEviction\":\n\t\tresp, err = v.dispatchSimulateEviction(req)\n\tcase \"VirtualMachinesClient.BeginStart\":\n\t\tresp, err = v.dispatchBeginStart(req)\n\tcase \"VirtualMachinesClient.BeginUpdate\":\n\t\tresp, err = v.dispatchBeginUpdate(req)\n\tdefault:\n\t\terr = fmt.Errorf(\"unhandled API %s\", method)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (h *HttpReceiver) handleBeaconEndpoint(writer http.ResponseWriter, reader *http.Request) {\n\t// Get data from the message that client peer sent.\n\tbody, err := io.ReadAll(reader.Body)\n\tif err != nil {\n\t\toutput.VerbosePrint(fmt.Sprintf(\"[!] Error: could not read data from beacon request: %s\", err.Error()))\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\treader.Body = io.NopCloser(bytes.NewReader(body))\n\n\t// Extract profile from the data.\n\tprofileData, err := base64.StdEncoding.DecodeString(string(body))\n\tif err != nil {\n\t\toutput.VerbosePrint(fmt.Sprintf(\"[!] Error: malformed profile base64 received: %s\", err.Error()))\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tprofile := make(map[string]interface{})\n\tif err = json.Unmarshal(profileData, &profile); err != nil {\n\t\toutput.VerbosePrint(fmt.Sprintf(\"[!] Error: malformed profile data received on beacon endpoint: %s\", err.Error()))\n\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t//make sure our paw is not in the peer chain (loop scenario)\n\tif isInPeerChain(profile, h.agentPaw) {\n\t output.VerbosePrint(fmt.Sprintf(\"[!] Error: agent paw already in proxy chain, loop detected\"))\n\t http.Error(writer, \"peer loop detected\", http.StatusInternalServerError)\n\t return\n\t}\n\n\t// Update server value in profile with our agent's server value.\n\tprofile[\"server\"] = *h.agentServer\n\n\t// Get local address that received the request\n\treceiverAddress, err := h.getLocalAddressForRequest(reader)\n\tif err != nil {\n\t\toutput.VerbosePrint(fmt.Sprintf(\"[!] Error getting local address: %s\", err.Error()))\n\t http.Error(writer, \"Could not get local address from request\", http.StatusInternalServerError)\n\t return\n\t}\n\n\t// Check if profile contains execution results\n\tif results, ok := profile[\"results\"]; ok {\n\t\toutput.VerbosePrint(\"[*] HTTP proxy: handling execution results from client.\")\n\t\tresultList := results.([]interface{})\n\t\tif len(resultList) > 0 {\n\t\t\t(*h.upstreamComs).SendExecutionResults(profile, resultList[0].(map[string]interface{}))\n\t\t} else {\n\t\t\toutput.VerbosePrint(\"[!] Error: client sent empty result list.\")\n\t\t\thttp.Error(writer, \"Empty result list received from client\", http.StatusInternalServerError)\n\t\t}\n\t} else {\n\t\toutput.VerbosePrint(\"[*] HTTP proxy: handling beacon request from client.\")\n\n\t\t// Update peer proxy chain information to indicate that the beacon is going through this agent.\n\t\tupdatePeerChain(profile, h.agentPaw, receiverAddress, h.receiverName)\n\t\tbeaconResponse := (*h.upstreamComs).GetBeaconBytes(profile)\n\t\tencodedResponse := []byte(base64.StdEncoding.EncodeToString(beaconResponse))\n\t\tif err = sendResponseToClient(encodedResponse, nil, writer); err != nil {\n\t\t\toutput.VerbosePrint(fmt.Sprintf(\"[!] Error sending response to client: %s\", err.Error()))\n\t\t\thttp.Error(writer, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t}\n}", "func clientSendHandler(from, to string, serialNumber, salt string, bc *Blockchain) {\n\tif !ValidateAddress(from) {\n\t\tcolor.Red(\"Invalid sender address: %s\\n\", from)\n\t\treturn\n\t}\n\tif !ValidateAddress(to) {\n\t\tcolor.Red(\"Invalid recipient address: %s\\n\", to)\n\t\treturn\n\t}\n\n\tUTXOSet := UTXOSet{bc}\n\n\twallets, err := NewWallets(ParseNodeID(nodeAddress)) //this line will crash if we change db and wallet file naming convention\n\tif err != nil {\n\t\tcolor.Red(\"Error: %s\\n\", err)\n\t\treturn\n\t}\n\n\twallet := wallets.GetWallet(from)\n\tif wallet == nil {\n\t\tcolor.Red(\"You do not own the address: %s\", from)\n\t\treturn\n\t}\n\n\t// later may be modified to transfer labels in batch\n\ttx, err := NewUTXOTransaction(wallet, to, serialNumber, salt, &UTXOSet)\n\n\tif err != nil {\n\t\tcolor.Red(\"Error: %s\\n\", err)\n\t\treturn\n\t}\n\n\tfor _, nodeAddr := range knownNodes {\n\t\tsendTx(nodeAddr, tx)\n\t}\n\n\tfmt.Println(\"Success!\")\n}", "func main() {\n\trouter := mux.NewRouter().StrictSlash(true)\n\tsub := router.PathPrefix(\"/api/v1\").Subrouter()\n\tsub.Methods(\"GET\").Path(\"/companies\").HandlerFunc(handler.GetCompanies)\n\tsub.Methods(\"POST\").Path(\"/companies\").HandlerFunc(handler.SaveCompany)\n\tsub.Methods(\"GET\").Path(\"/companies/{name}\").HandlerFunc(handler.GetCompany)\n\tsub.Methods(\"PUT\").Path(\"/companies/{name}\").HandlerFunc(handler.UpdateCompany)\n\tsub.Methods(\"DELETE\").Path(\"/companies/{name}\").HandlerFunc(handler.DeleteCompany)\n\n\tlog.Fatal(http.ListenAndServe(\":3000\", router))\n}", "func (a *WalletApplication) initMainnetConnection() {\n\ta.Network.URL = \"cl-lb-111349175.us-west-1.elb.amazonaws.com:9000\" // Temp\n\n\ta.Network.Handles.Send = \"/send\"\n\ta.Network.Handles.Transaction = \"/transaction\"\n\ta.Network.Handles.Balance = \"/balance\"\n\n\ta.Network.BlockExplorer.URL = \"https://2mqil2w38l.execute-api.us-west-1.amazonaws.com/block-explorer-api-dev\"\n\ta.Network.BlockExplorer.Handles.Transactions = \"/transactions/\"\n\ta.Network.BlockExplorer.Handles.Checkpoints = \"/checkpoints/\"\n\ta.Network.BlockExplorer.Handles.Snapshots = \"/snapshots/\"\n\ta.Network.BlockExplorer.Handles.CollectTX = \"/transactions?sender=\"\n}", "func (listener *RootChainListener) eventListener(contract string) {\n\n\tlatestBlock := listener.GetLatestBlock()\n\n\tfmt.Println(\"start event listener, latest block is \", latestBlock)\n\n\tcontractAddress := common.HexToAddress(\"0x44da3d92af236ffb5069781fa202c2d0e740d6a3\")\n\n\tfmt.Println(\"contract address is \", contract)\n\n\t// 6 blocks ensure confirmation\n\t//from := i.SetInt64(latestBlock - (Confirmations * 2 + 1))\n\t//to := i.SetInt64(latestBlock + 1 - Confirmations)\n\n\tq := ethereum.FilterQuery{\n\t\tAddresses: []common.Address{contractAddress},\n\t}\n\n\tlogs := make(chan types.Log)\n\n\tsub, err := listener.ethClient.SubscribeFilterLogs(context.Background(), q, logs)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor {\n\n\t\tfmt.Println(\"select...\")\n\n\t\tselect {\n\n\t\tcase err := <-sub.Err():\n\n\t\t\tfmt.Println(\"get error \", err)\n\t\t\tlog.Fatal(err)\n\n\t\tcase vLog := <-logs:\n\n\t\t\tfmt.Println(\"get logs \")\n\t\t\tcontractAbi, err := abi.JSON(strings.NewReader(string(artifact.RootChainABI)))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tdepositEvent := chain.RootChainDeposit{}\n\t\t\texitStartedEvent := chain.RootChainExitStarted{}\n\t\t\terr = contractAbi.Unpack(&depositEvent, \"Deposit\", vLog.Data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t\terr = contractAbi.Unpack(&exitStartedEvent, \"ExitStarted\", vLog.Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t} else {\n\t\t\t\t\tutxoId := exitStartedEvent.UtxoPos\n\t\t\t\t\tlistener.chain.MarkUTXOSpend(utxoId.Uint64())\n\t\t\t\t\tb, e := json.Marshal(exitStartedEvent)\n\t\t\t\t\tif e != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error: %s\", err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tlistener.handledEvent[string(b)] = exitStartedEvent\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t//add to depositor block to child block\n\t\t\t\towner := depositEvent.Depositor\n\t\t\t\tamount := depositEvent.Amount\n\t\t\t\tdepositTx := core.MakeTransaction(owner, amount.Uint64())\n\t\t\t\ttxs := make([]*core.Transaction, 0)\n\t\t\t\ttxs = append(txs, depositTx)\n\t\t\t\t//block := core.MakeBlock(txs, depositEvent.DepositBlock)\n\t\t\t\t//listener.chain.AddBlock(&block)\n\t\t\t\t//b, e := json.Marshal(depositEvent)\n\t\t\t\t//if e != nil {\n\t\t\t\t//\tfmt.Printf(\"Error: %s\", err)\n\t\t\t\t//\treturn\n\t\t\t\t//}\n\t\t\t\t//\n\t\t\t\t//listener.handledEvent[string(b)] = depositEvent\n\t\t\t}\n\n\t\t}\n\t}\n}", "func (as *AddrServer) HandleGetBlocks(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tquery := r.URL.Query()\n\tlimit := \"10\"\n\tif len(query[\"limit\"]) > 0 {\n\t\tlimit = query[\"limit\"][0]\n\t}\n\tlim, err := strconv.ParseInt(limit, 10, 64)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"failed parsing ?limit={val}\", err))\n\t\treturn\n\t}\n\tw.Write(as.GetBlocksResponse(lim))\n}", "func Index() func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tstart := time.Now()\n\t\tidObj := identity.Get(req.Context()).Identity\n\t\torgId := idObj.Internal.OrgID\n\t\tres := GetFeatureStatus(orgId)\n\t\taccNum := idObj.AccountNumber\n\t\tisInternal := idObj.User.Internal\n\t\tvalidEmailMatch, _ := regexp.MatchString(`^.*@redhat.com$`, idObj.User.Email)\n\n\t\tvalidAccNum := !(accNum == \"\" || accNum == \"-1\")\n\t\tvalidOrgId := !(orgId == \"\" || orgId == \"-1\")\n\n\t\tinclude_filter := filtersFromParams(req, \"include_bundles\")\n\t\texclude_filter := filtersFromParams(req, \"exclude_bundles\")\n\n\t\tif res.Error != nil {\n\t\t\terrMsg := \"Unexpected error while talking to Subs Service\"\n\t\t\tl.Log.WithFields(logrus.Fields{\"error\": res.Error}).Error(errMsg)\n\t\t\tsentry.CaptureException(res.Error)\n\t\t\tfailOnDependencyError(errMsg, res, w)\n\t\t\treturn\n\t\t}\n\n\t\tsubsTimeTaken := time.Since(start).Seconds()\n\t\tl.Log.WithFields(logrus.Fields{\"subs_call_duration\": subsTimeTaken, \"cache_hit\": res.CacheHit}).Info(\"subs call complete\")\n\t\tsubsTimeHistogram.Observe(subsTimeTaken)\n\n\t\tif res.StatusCode != 200 {\n\t\t\terrMsg := \"Got back a non 200 status code from Subscriptions Service\"\n\t\t\tl.Log.WithFields(logrus.Fields{\"code\": res.StatusCode, \"body\": res.Body}).Error(errMsg)\n\n\t\t\tsentry.WithScope(func(scope *sentry.Scope) {\n\t\t\t\tscope.SetExtra(\"response_body\", res.Body)\n\t\t\t\tscope.SetExtra(\"response_status\", res.StatusCode)\n\t\t\t\tsentry.CaptureException(errors.New(errMsg))\n\t\t\t})\n\n\t\t\tfailOnDependencyError(errMsg, res, w)\n\t\t\treturn\n\t\t}\n\n\t\tentitlementsResponse := make(map[string]types.EntitlementsSection)\n\t\tfor _, b := range bundleInfo {\n\t\t\tif len(include_filter) > 0 {\n\t\t\t\tif !contains(include_filter, b.Name) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if len(exclude_filter) > 0 {\n\t\t\t\tif contains(exclude_filter, b.Name) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentitle := true\n\t\t\ttrial := false\n\t\t\tentitleAll := configOptions.GetString(config.Keys.EntitleAll)\n\n\t\t\tif entitleAll == \"true\" {\n\t\t\t\tentitlementsResponse[b.Name] = setBundlePayload(entitle, trial)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(b.Skus) > 0 {\n\t\t\t\tentitle = false\n\t\t\t\tfor _, f := range res.Data.Features {\n\t\t\t\t\tif f.Name == b.Name {\n\t\t\t\t\t\tentitle = f.Entitled\n\t\t\t\t\t\ttrial = f.IsEval\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif b.UseValidAccNum {\n\t\t\t\tentitle = validAccNum && entitle\n\t\t\t}\n\n\t\t\tif b.UseValidOrgId {\n\t\t\t\tentitle = validOrgId && entitle\n\t\t\t}\n\n\t\t\tif b.UseIsInternal {\n\t\t\t\tentitle = validAccNum && isInternal && validEmailMatch\n\t\t\t}\n\t\t\tentitlementsResponse[b.Name] = setBundlePayload(entitle, trial)\n\t\t}\n\n\t\tobj, err := json.Marshal(entitlementsResponse)\n\n\t\tif err != nil {\n\t\t\tl.Log.WithFields(logrus.Fields{\"error\": err}).Error(\"Unexpected error while unmarshalling JSON data from Subs Service\")\n\t\t\tsentry.CaptureException(err)\n\t\t\thttp.Error(w, http.StatusText(500), 500)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write([]byte(obj))\n\t}\n}", "func (sc *SuperChain) getChainInfo(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tchainID := args[0]\n\n\tchainInfo , err := stub.GetState(chainID)\n\tif err != nil {\n\t\treturn shim.Error(fmt.Errorf(\"get chain from chainID error: %w\", err).Error())\n\t}\n\n\treturn shim.Success(chainInfo)\n}", "func main() {\n\tgob.Register(&net.TCPAddr{})\n\tgob.Register(&elliptic.CurveParams{})\n\n\t// Command line input parsing\n\tflag.Parse()\n\tif len(flag.Args()) != 2 {\n\t\tfmt.Fprintln(os.Stderr, \"Usage: go run onion_router.go [dir-server ip:port] [or ip:port]\")\n\t\tos.Exit(1)\n\t}\n\n\tdirServerAddr := flag.Arg(0)\n\torAddr := flag.Arg(1)\n\n\t// Generate RSA PublicKey and PrivateKey\n\tpriv, err := rsa.GenerateKey(rand.Reader, RSAKeySize)\n\tutil.HandleFatalError(\"Could not generate RSA key\", err)\n\tpub := &priv.PublicKey\n\n\t// Establish RPC channel to server\n\tdirServer, err := rpc.Dial(\"tcp\", dirServerAddr)\n\tutil.HandleFatalError(\"Could not dial directory server\", err)\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", orAddr)\n\tutil.HandleFatalError(\"Could not resolve onion-router address\", err)\n\n\tinbound, err := net.ListenTCP(\"tcp\", addr)\n\tutil.HandleFatalError(\"Could not listen\", err)\n\n\tutil.OutLog.Println(\"OR Address: \", orAddr)\n\tutil.OutLog.Println(\"Full Address: \", inbound.Addr().String())\n\n\t// Create OnionRouter instance\n\tonionRouter := &OnionRouter{\n\t\taddr: orAddr,\n\t\tdirServer: dirServer,\n\t\tpubKey: pub,\n\t\tprivKey: priv,\n\t}\n\n\tif err = onionRouter.registerNode(); err != nil {\n\t\tutil.HandleFatalError(\"Could not register onion router with directory server\", err)\n\t}\n\n\tgo onionRouter.startSendingHeartbeatsToServer()\n\n\t// Start listening for RPC calls from other onion routers\n\torServer := new(ORServer)\n\torServer.OnionRouter = onionRouter\n\n\tonionRouterServer := rpc.NewServer()\n\tonionRouterServer.Register(orServer)\n\n\tutil.OutLog.Printf(\"ORServer started. Receiving on %s\\n\", orAddr)\n\n\tfor {\n\t\tconn, _ := inbound.Accept()\n\t\tgo onionRouterServer.ServeConn(conn)\n\t}\n}", "func (srv *Server) walletTransactionsHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\t// Get the start and end blocks.\n\tstart, err := strconv.Atoi(req.FormValue(\"startheight\"))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tend, err := strconv.Atoi(req.FormValue(\"endheight\"))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tconfirmedTxns, err := srv.wallet.Transactions(types.BlockHeight(start), types.BlockHeight(end))\n\tif err != nil {\n\t\twriteError(w, \"error after call to /wallet/transactions: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tunconfirmedTxns := srv.wallet.UnconfirmedTransactions()\n\n\twriteJSON(w, WalletTransactionsGET{\n\t\tConfirmedTransactions: confirmedTxns,\n\t\tUnconfirmedTransactions: unconfirmedTxns,\n\t})\n}", "func submitSwapHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar req SwapReq\n\t\tif !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {\n\t\t\treturn\n\t\t}\n\n\t\treq.BaseReq = req.BaseReq.Sanitize()\n\t\tif !req.BaseReq.ValidateBasic(w) {\n\t\t\treturn\n\t\t}\n\n\t\tfromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From)\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tvar msg sdk.Msg\n\t\tif req.Receiver == \"\" {\n\t\t\tmsg = types.NewMsgSwap(fromAddress, req.OfferCoin, req.AskDenom)\n\t\t} else {\n\t\t\ttoAddress, err := sdk.AccAddressFromBech32(req.Receiver)\n\t\t\tif err != nil {\n\t\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmsg := types.NewMsgSwapSend(fromAddress, toAddress, req.OfferCoin, req.AskDenom)\n\t\t\tif req.BaseReq.Fees.IsZero() {\n\t\t\t\tfees, gas, err := feeutils.ComputeFees(cliCtx, feeutils.ComputeReqParams{\n\t\t\t\t\tMemo: req.BaseReq.Memo,\n\t\t\t\t\tChainID: req.BaseReq.ChainID,\n\t\t\t\t\tAccountNumber: req.BaseReq.AccountNumber,\n\t\t\t\t\tSequence: req.BaseReq.Sequence,\n\t\t\t\t\tGasPrices: req.BaseReq.GasPrices,\n\t\t\t\t\tGas: req.BaseReq.Gas,\n\t\t\t\t\tGasAdjustment: req.BaseReq.GasAdjustment,\n\t\t\t\t\tMsgs: []sdk.Msg{msg},\n\t\t\t\t})\n\n\t\t\t\tif err != nil {\n\t\t\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// override gas and fees\n\t\t\t\treq.BaseReq.Gas = strconv.FormatUint(gas, 10)\n\t\t\t\treq.BaseReq.Fees = fees\n\t\t\t\treq.BaseReq.GasPrices = sdk.DecCoins{}\n\t\t\t}\n\t\t}\n\n\t\t// create the message\n\t\terr = msg.ValidateBasic()\n\t\tif err != nil {\n\t\t\trest.WriteErrorResponse(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tutils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg})\n\t}\n}", "func Start(w http.ResponseWriter, r *http.Request) {\n\tif os.Args[1] == \"6686\" {\n\t\tSBC.UpdateEntireBlockChain(BLOCKCHAIN_JSON)\n\t\tUpload(w, r)\n\t} else {\n\t\tDownload()\n\t}\n\tFirstHeatdBeat()\n\tgo StartHeartBeat()\n\tgo StartTryingNonces()\n}", "func Setup(router *mux.Router, accountDB *accounts.Database, deviceDB *devices.Database, levelDB *levels.Database) {\n\troute := routerConfig{map[string]bool{\n\t\t\"/login\": true,\n\t\t\"/register\": true,\n\t\t\"/welcome\": true,\n\t\t\"/trade\": true,\n\t}}\n\trouter.HandleFunc(\"/welcome\", SayWelcome).Methods(http.MethodGet)\n\trouter.HandleFunc(\"/login\", LoginHandler(accountDB, deviceDB, levelDB)).Methods(http.MethodPost)\n\trouter.HandleFunc(\"/register\", RegisterHandler(accountDB, deviceDB, levelDB)).Methods(http.MethodPost)\n\trouter.HandleFunc(\"/registration\", RegistrationHandler(levelDB)).Methods(http.MethodPut, http.MethodDelete, http.MethodGet)\n\n\t// routes with auth = true\n\trouter.HandleFunc(\"/logout\", LogoutHandler(deviceDB)).Methods(http.MethodPost)\n\trouter.HandleFunc(\"/levels\", RouteLevelsHandler(levelDB, sql.NullBool{false, true}, GetAllAccountLevels)).Methods(http.MethodPost)\n\trouter.HandleFunc(\"/levels/{levelname}\", RouteLevelsHandler(levelDB, sql.NullBool{}, RequestLevelByLocalpart)).Methods(http.MethodPost)\n\trouter.HandleFunc(\"/levels/{levelname}/{localpart}\", RouteLevelsHandler(levelDB, sql.NullBool{true, true}, SetLevelByLocalpart)).Methods(http.MethodPut)\n\trouter.HandleFunc(\"/levels/{levelname}/{localpart}\", RouteLevelsHandler(levelDB, sql.NullBool{false, true}, SetLevelByLocalpart)).Methods(http.MethodDelete)\n\trouter.HandleFunc(\"/accounts\", RouteHandlerAccounts(accountDB)).Methods(http.MethodPost)\n\trouter.HandleFunc(\"/devices\", RouteHandlerDevices(deviceDB)).Methods(http.MethodPost)\n\n\t//binance api paths\n\tbinanceProxy := proxy_handles.NewProxy(\"http://localhost:8080\")\n\trouter.PathPrefix(\"/trade\").HandlerFunc(binanceProxy.Handle)\n\n\trouter.Use(route.authMiddleware(deviceDB))\n}", "func innerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\t// path\n\tg := e.Group(\"/x/internal/click\")\n\t{\n\t\tg.GET(\"\", click)\n\t\tg.GET(\"/lock\", lock)\n\t\tg.GET(\"/lock/mid\", lockMid)\n\t}\n}", "func handleGetRequest(key string, s *Sailor, st *storage.State) (string, error) {\n\tgt := storage.GenerateTransaction(storage.GetOp, key, \"\")\n\treturn st.ApplyTransaction(gt)\n}", "func (r *Router) HandleFaucetRequest(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tbody := parseRequestBody(req.Body)\n\taddress, ok := body[\"address\"].(string)\n\tif !ok {\n\t\thttp.Error(res, \"Malformed Request: missing address\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tamount, ok := body[\"amount\"].(float64)\n\tif !ok {\n\t\t// the default 100 000 000 satoshis\n\t\tamount = 1\n\t}\n\tasset, ok := body[\"asset\"].(string)\n\tif !ok {\n\t\t// this means sending bitcoin\n\t\tasset = \"\"\n\t}\n\n\tvar status int\n\tvar tx string\n\tvar err error\n\n\tif r.Config.Chain() == \"liquid\" {\n\t\tstatus, tx, err = r.Faucet.SendLiquidTransaction(address, amount, asset)\n\t} else {\n\t\tstatus, tx, err = r.Faucet.SendBitcoinTransaction(address, amount)\n\t}\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), status)\n\t\treturn\n\t}\n\n\tif r.Config.IsMiningEnabled() {\n\t\tr.Faucet.Mine(1)\n\t}\n\tjson.NewEncoder(res).Encode(map[string]string{\"txId\": tx})\n\treturn\n}", "func (c *Consenter) HandleChain(support consensus.ConsenterSupport, metadata *common.Metadata) (consensus.Chain, error) {\n\tm := &etcdraft.ConfigMetadata{}\n\tif err := proto.Unmarshal(support.SharedConfig().ConsensusMetadata(), m); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to unmarshal consensus metadata\")\n\t}\n\n\tif m.Options == nil {\n\t\treturn nil, errors.New(\"etcdraft options have not been provided\")\n\t}\n\n\tisMigration := (metadata == nil || len(metadata.Value) == 0) && (support.Height() > 1)\n\tif isMigration {\n\t\tc.Logger.Debugf(\"Block metadata is nil at block height=%d, it is consensus-type migration\", support.Height())\n\t}\n\n\t// determine raft replica set mapping for each node to its id\n\t// for newly started chain we need to read and initialize raft\n\t// metadata by creating mapping between conseter and its id.\n\t// In case chain has been restarted we restore raft metadata\n\t// information from the recently committed block meta data\n\t// field.\n\tblockMetadata, err := ReadBlockMetadata(metadata, m)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to read Raft metadata\")\n\t}\n\n\tconsenters := CreateConsentersMap(blockMetadata, m)\n\n\tid, err := c.detectSelfID(consenters)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"without a system channel, a follower should have been created\")\n\t}\n\n\tvar evictionSuspicion time.Duration\n\tif c.EtcdRaftConfig.EvictionSuspicion == \"\" {\n\t\tc.Logger.Infof(\"EvictionSuspicion not set, defaulting to %v\", DefaultEvictionSuspicion)\n\t\tevictionSuspicion = DefaultEvictionSuspicion\n\t} else {\n\t\tevictionSuspicion, err = time.ParseDuration(c.EtcdRaftConfig.EvictionSuspicion)\n\t\tif err != nil {\n\t\t\tc.Logger.Panicf(\"Failed parsing Consensus.EvictionSuspicion: %s: %v\", c.EtcdRaftConfig.EvictionSuspicion, err)\n\t\t}\n\t}\n\n\tvar tickInterval time.Duration\n\tif c.EtcdRaftConfig.TickIntervalOverride == \"\" {\n\t\ttickInterval, err = time.ParseDuration(m.Options.TickInterval)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"failed to parse TickInterval (%s) to time duration\", m.Options.TickInterval)\n\t\t}\n\t} else {\n\t\ttickInterval, err = time.ParseDuration(c.EtcdRaftConfig.TickIntervalOverride)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithMessage(err, \"failed parsing Consensus.TickIntervalOverride\")\n\t\t}\n\t\tc.Logger.Infof(\"TickIntervalOverride is set, overriding channel configuration tick interval to %v\", tickInterval)\n\t}\n\n\topts := Options{\n\t\tRPCTimeout: c.OrdererConfig.General.Cluster.RPCTimeout,\n\t\tRaftID: id,\n\t\tClock: clock.NewClock(),\n\t\tMemoryStorage: raft.NewMemoryStorage(),\n\t\tLogger: c.Logger,\n\n\t\tTickInterval: tickInterval,\n\t\tElectionTick: int(m.Options.ElectionTick),\n\t\tHeartbeatTick: int(m.Options.HeartbeatTick),\n\t\tMaxInflightBlocks: int(m.Options.MaxInflightBlocks),\n\t\tMaxSizePerMsg: uint64(support.SharedConfig().BatchSize().PreferredMaxBytes),\n\t\tSnapshotIntervalSize: m.Options.SnapshotIntervalSize,\n\n\t\tBlockMetadata: blockMetadata,\n\t\tConsenters: consenters,\n\n\t\tMigrationInit: isMigration,\n\n\t\tWALDir: path.Join(c.EtcdRaftConfig.WALDir, support.ChannelID()),\n\t\tSnapDir: path.Join(c.EtcdRaftConfig.SnapDir, support.ChannelID()),\n\t\tEvictionSuspicion: evictionSuspicion,\n\t\tCert: c.Cert,\n\t\tMetrics: c.Metrics,\n\t}\n\n\trpc := &cluster.RPC{\n\t\tTimeout: c.OrdererConfig.General.Cluster.RPCTimeout,\n\t\tLogger: c.Logger,\n\t\tChannel: support.ChannelID(),\n\t\tComm: c.Communication,\n\t\tStreamsByType: cluster.NewStreamsByType(),\n\t}\n\n\t// Called after the etcdraft.Chain halts when it detects eviction from the cluster.\n\t// When we do NOT have a system channel, we switch to a follower.Chain upon eviction.\n\tc.Logger.Info(\"After eviction from the cluster Registrar.SwitchToFollower will be called, and the orderer will become a follower of the channel.\")\n\thaltCallback := func() { c.ChainManager.SwitchChainToFollower(support.ChannelID()) }\n\n\treturn NewChain(\n\t\tsupport,\n\t\topts,\n\t\tc.Communication,\n\t\trpc,\n\t\tc.BCCSP,\n\t\tfunc() (BlockPuller, error) {\n\t\t\treturn NewBlockPuller(support, c.Dialer, c.OrdererConfig.General.Cluster, c.BCCSP)\n\t\t},\n\t\thaltCallback,\n\t\tnil,\n\t)\n}", "func (mpi *mempoolImpl) handleTrackNewChainHead(req *reqTrackNewChainHead) {\n\tdefer close(req.responseCh)\n\tmpi.log.Debugf(\"handleTrackNewChainHead, %v from %v, current=%v\", req.till, req.from, mpi.chainHeadAO)\n\tif len(req.removed) != 0 {\n\t\tmpi.log.Infof(\"Reorg detected, removing %v blocks, adding %v blocks\", len(req.removed), len(req.added))\n\t\t// TODO: For IOTA 2.0: Maybe re-read the state from L1 (when reorgs will become possible).\n\t}\n\t//\n\t// Re-add requests from the blocks that are reverted now.\n\tfor _, block := range req.removed {\n\t\tblockReceipts, err := blocklog.RequestReceiptsFromBlock(block)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot extract receipts from block: %w\", err))\n\t\t}\n\t\tfor _, receipt := range blockReceipts {\n\t\t\tif blocklog.HasUnprocessableRequestBeenRemovedInBlock(block, receipt.Request.ID()) {\n\t\t\t\tcontinue // do not add unprocessable requests that were successfully retried back into the mempool in case of a reorg\n\t\t\t}\n\t\t\tmpi.tryReAddRequest(receipt.Request)\n\t\t}\n\t}\n\t//\n\t// Cleanup the requests that were consumed in the added blocks.\n\tfor _, block := range req.added {\n\t\tblockReceipts, err := blocklog.RequestReceiptsFromBlock(block)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot extract receipts from block: %w\", err))\n\t\t}\n\t\tmpi.metrics.IncBlocksPerChain()\n\t\tmpi.listener.BlockApplied(mpi.chainID, block)\n\t\tfor _, receipt := range blockReceipts {\n\t\t\tmpi.metrics.IncRequestsProcessed()\n\t\t\tmpi.tryRemoveRequest(receipt.Request)\n\t\t}\n\t\tunprocessableRequests, err := blocklog.UnprocessableRequestsAddedInBlock(block)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"cannot extract unprocessable requests from block: %w\", err))\n\t\t}\n\t\tfor _, req := range unprocessableRequests {\n\t\t\tmpi.metrics.IncRequestsProcessed()\n\t\t\tmpi.tryRemoveRequest(req)\n\t\t}\n\t}\n\t//\n\t// Cleanup processed requests, if that's the first time we received the state.\n\tif mpi.chainHeadState == nil {\n\t\tmpi.log.Debugf(\"Cleanup processed requests based on the received state...\")\n\t\tmpi.tryCleanupProcessed(req.st)\n\t\tmpi.log.Debugf(\"Cleanup processed requests based on the received state... Done\")\n\t}\n\t//\n\t// Record the head state.\n\tmpi.chainHeadState = req.st\n\tmpi.chainHeadAO = req.till\n\t//\n\t// Process the pending consensus proposal requests if any.\n\tif len(mpi.waitChainHead) != 0 {\n\t\tnewWaitChainHead := []*reqConsensusProposal{}\n\t\tfor i, waiting := range mpi.waitChainHead {\n\t\t\tif waiting.ctx.Err() != nil {\n\t\t\t\tcontinue // Drop it.\n\t\t\t}\n\t\t\tif waiting.aliasOutput.Equals(mpi.chainHeadAO) {\n\t\t\t\tmpi.handleConsensusProposalForChainHead(waiting)\n\t\t\t\tcontinue // Drop it from wait queue.\n\t\t\t}\n\t\t\tnewWaitChainHead = append(newWaitChainHead, mpi.waitChainHead[i])\n\t\t}\n\t\tmpi.waitChainHead = newWaitChainHead\n\t}\n}", "func TxReceiverHandler(w http.ResponseWriter, r *http.Request) {\n\t// receive the payload and read\n\tvar tx TxReceiver\n\tif !ReadRESTReq(w, r, &tx) {\n\t\tWriteErrorResponse(w, http.StatusBadRequest, \"Cannot read request\")\n\t}\n\n\t// create a new pending transaction\n\tuserTx := core.NewPendingTx(tx.From, tx.To, core.TX_TRANSFER_TYPE, tx.Signature, tx.Message)\n\n\t// add the transaction to pool\n\terr := core.DBInstance.InsertTx(&userTx)\n\tif err != nil {\n\t\tWriteErrorResponse(w, http.StatusBadRequest, \"Cannot read request\")\n\t}\n\n\toutput, err := json.Marshal(userTx)\n\tif err != nil {\n\t\tWriteErrorResponse(w, http.StatusBadRequest, \"Unable to marshall account\")\n\t}\n\n\t// write headers and data\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, _ = w.Write(output)\n\treturn\n}", "func Start(w http.ResponseWriter, r *http.Request) {\n\t// The first Node will read two blocks from a Json string and add it to the BlockChain\n\tif os.Args[2] == \"yes\" {\n\t\tfmt.Println(\"Create BlockChain from json \")\n\t\tSBC.UpdateEntireBlockChain(JSON_BLOCKCHAIN)\n\t\thighestblockTransaction = SBC.GetLatestBlocks()[0].GetHeight()\n\t\thighestblockTransactionHash = SBC.GetLatestBlocks()[0].GetHash()\n\t} else {\n\t\tfmt.Println(\"Download BlockChain from first node..\")\n\t\tDownload()\n\t}\n\tifStarted = true\n\tgo StartHeartBeat()\n\tgo CreateBlockWithTransactions()\n\n\tfmt.Fprintf(w, \"Node started\")\n}", "func TransferOwnershipHandler(app *App) func(c echo.Context) error {\n\treturn func(c echo.Context) error {\n\t\tc.Set(\"route\", \"TransferClanOwnership\")\n\t\tstart := time.Now()\n\t\tgameID := c.Param(\"gameID\")\n\t\tpublicID := c.Param(\"clanPublicID\")\n\n\t\tlogClanOwnerID(app, c, gameID, publicID, \"before\", \"transferClanOwnership\")\n\t\tdefer logClanOwnerID(app, c, gameID, publicID, \"after\", \"transferClanOwnership\")\n\n\t\tlogger := app.Logger.With(\n\t\t\tzap.String(\"source\", \"clanHandler\"),\n\t\t\tzap.String(\"operation\", \"transferClanOwnership\"),\n\t\t\tzap.String(\"gameID\", gameID),\n\t\t\tzap.String(\"clanPublicID\", publicID),\n\t\t)\n\t\tvar payload TransferClanOwnershipPayload\n\t\tif err := LoadJSONPayload(&payload, c, logger); err != nil {\n\t\t\treturn FailWith(400, err.Error(), c)\n\t\t}\n\n\t\tlogger = logger.With(\n\t\t\tzap.String(\"newOwnerPublicID\", payload.PlayerPublicID),\n\t\t)\n\n\t\tgame, err := app.GetGame(c.StdContext(), gameID)\n\t\tif err != nil {\n\t\t\tlog.W(logger, \"Could not find game.\")\n\t\t\treturn FailWith(404, err.Error(), c)\n\t\t}\n\n\t\tvar tx interfaces.Transaction\n\t\tvar clan *models.Clan\n\t\tvar previousOwner, newOwner *models.Player\n\n\t\trb := func(err error) error {\n\t\t\ttxErr := app.Rollback(tx, \"Clan ownership transfer failed\", c, logger, err)\n\t\t\tif txErr != nil {\n\t\t\t\treturn txErr\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\ttx, err = app.BeginTrans(c.StdContext(), logger)\n\t\tif err != nil {\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\n\t\tlog.D(logger, \"Transferring clan ownership...\")\n\t\tclan, previousOwner, newOwner, err = models.TransferClanOwnership(\n\t\t\ttx,\n\t\t\tapp.EncryptionKey,\n\t\t\tgameID,\n\t\t\tpublicID,\n\t\t\tpayload.PlayerPublicID,\n\t\t\tgame.MembershipLevels,\n\t\t\tgame.MaxMembershipLevel,\n\t\t)\n\t\tif err != nil {\n\t\t\ttxErr := rb(err)\n\t\t\tif txErr == nil {\n\t\t\t\tlog.E(logger, \"Clan ownership transfer failed.\", func(cm log.CM) {\n\t\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\n\t\terr = dispatchClanOwnershipChangeHook(\n\t\t\tapp, models.ClanOwnershipTransferredHook,\n\t\t\tclan, previousOwner, newOwner,\n\t\t)\n\n\t\tif err != nil {\n\t\t\ttxErr := rb(err)\n\t\t\tif txErr == nil {\n\t\t\t\tlog.E(logger, \"Clan ownership transfer hook dispatch failed.\", func(cm log.CM) {\n\t\t\t\t\tcm.Write(zap.Error(err))\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\n\t\tpOwnerJSON := previousOwner.Serialize(app.EncryptionKey)\n\t\tdelete(pOwnerJSON, \"gameID\")\n\n\t\tnOwnerJSON := newOwner.Serialize(app.EncryptionKey)\n\t\tdelete(nOwnerJSON, \"gameID\")\n\n\t\terr = app.Commit(tx, \"Clan ownership transfer\", c, logger)\n\t\tif err != nil {\n\t\t\treturn FailWith(500, err.Error(), c)\n\t\t}\n\n\t\tlog.I(logger, \"Clan ownership transfer completed successfully.\", func(cm log.CM) {\n\t\t\tcm.Write(\n\t\t\t\tzap.String(\"previousOwnerPublicID\", previousOwner.PublicID),\n\t\t\t\tzap.String(\"newOwnerPublicID\", newOwner.PublicID),\n\t\t\t\tzap.Duration(\"duration\", time.Now().Sub(start)),\n\t\t\t)\n\t\t})\n\t\treturn SucceedWith(map[string]interface{}{\n\t\t\t\"previousOwner\": pOwnerJSON,\n\t\t\t\"newOwner\": nOwnerJSON,\n\t\t}, c)\n\t}\n}", "func outerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\tr := e.Group(\"/x/resource\")\n\t{\n\t\tr.GET(\"/plugin\", plugin)\n\t\tr.GET(\"/sidebar\", authSvc.GuestMobile, sidebar)\n\t\tr.GET(\"/topbar\", topbar)\n\t\tr.GET(\"/abtest\", abTest)\n\t\tr.GET(\"/abtest/v2\", abTestV2)\n\t\tr.GET(\"/abtest/abserver\", authSvc.GuestMobile, abserver)\n\t\tm := r.Group(\"/module\")\n\t\t{\n\t\t\tm.POST(\"\", module)\n\t\t\tm.POST(\"/list\", list)\n\t\t}\n\t\tg := r.Group(\"/guide\", authSvc.GuestMobile)\n\t\t{\n\t\t\tg.GET(\"/interest\", interest)\n\t\t\tg.GET(\"/interest2\", interest2)\n\t\t}\n\t\tr.GET(\"/static\", getStatic)\n\t\tr.GET(\"/domain\", domain)\n\t\tr.GET(\"/broadcast/servers\", serverList)\n\t\tr.GET(\"/white/list\", whiteList)\n\t\tr.GET(\"/show/tab\", authSvc.GuestMobile, tabs)\n\t}\n\tv := e.Group(\"/x/v2/version\")\n\t{\n\t\tv.GET(\"\", getVersion)\n\t\tv.GET(\"/update\", versionUpdate)\n\t\tv.GET(\"/update.pb\", versionUpdatePb)\n\t\tv.GET(\"/so\", versionSo)\n\t\tv.GET(\"/rn/update\", versionRn)\n\t}\n\tp := e.Group(\"/x/v2/param\", authSvc.GuestMobile)\n\t{\n\t\tp.GET(\"\", getParam)\n\t}\n\tn := e.Group(\"/x/v2/notice\", authSvc.GuestMobile)\n\t{\n\t\tn.GET(\"\", getNotice)\n\t}\n\ts := e.Group(\"/x/v2/splash\")\n\t{\n\t\ts.GET(\"\", splashs)\n\t\ts.GET(\"/birthday\", birthSplash)\n\t\ts.GET(\"/list\", authSvc.GuestMobile, splashList)\n\t}\n\ta := e.Group(\"/x/v2/audit\")\n\t{\n\t\ta.GET(\"\", audit)\n\t}\n}", "func nodeHandler(w http.ResponseWriter, r *http.Request, gos *Gossiper) {\n\t// If GET send the peers in json format\n\tif r.Method == \"GET\" {\n\t\tgos.mutexs.peersMutex.Lock()\n\t\tpeers := NodesResponse{gos.peers}\n\t\tgos.mutexs.peersMutex.Unlock()\n\n\t\tjs, err := json.Marshal(peers)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(js)\n\n\t\t// If POST get the ID and if it's new add it to the list of peers of the gossiper and send 200\n\t} else if r.Method == \"POST\" {\n\t\treqBody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\taddr := string(reqBody)\n\n\t\t// If peer is new add it to the gossiper's peerster list\n\t\tgos.mutexs.peersMutex.Lock()\n\t\tif !strings.Contains(gos.peers, addr) {\n\t\t\tif gos.peers == \"\" {\n\t\t\t\tgos.peers = addr\n\t\t\t} else {\n\t\t\t\tauxPeers := strings.Split(gos.peers, \",\")\n\t\t\t\tauxPeers = append(auxPeers, addr)\n\t\t\t\tgos.peers = strings.Join(auxPeers, \",\")\n\t\t\t}\n\t\t}\n\t\tgos.mutexs.peersMutex.Unlock()\n\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"200 OK\"))\n\n\t}\n}", "func (t *myTransport) block(ctx context.Context, parsedRequests []ModifiedRequest) (int, interface{}) {\n\tvar union *blockRange\n\tfor _, parsedRequest := range parsedRequests {\n\t\tctx = gotils.With(ctx, \"ip\", parsedRequest.RemoteAddr)\n\t\tif allowed, _ := t.AllowVisitor(parsedRequest); !allowed {\n\t\t\tgotils.L(ctx).Info().Print(\"Request blocked: Rate limited\")\n\t\t\treturn http.StatusTooManyRequests, jsonRPCLimit(parsedRequest.ID)\n\t\t} //else if added {\n\t\t// gotils.L(ctx).Debug().Printf(\"Added new visitor, ip: %v\", parsedRequest.RemoteAddr)\n\t\t// }\n\n\t\tif !t.MatchAnyRule(parsedRequest.Path) {\n\t\t\t// gotils.L(ctx).Debug().Print(\"Request blocked: Method not allowed\")\n\t\t\treturn http.StatusMethodNotAllowed, jsonRPCUnauthorized(parsedRequest.ID, parsedRequest.Path)\n\t\t}\n\t\tif t.blockRangeLimit > 0 && parsedRequest.Path == \"eth_getLogs\" {\n\t\t\tr, invalid, err := t.parseRange(ctx, parsedRequest)\n\t\t\tif err != nil {\n\t\t\t\treturn http.StatusInternalServerError, jsonRPCError(parsedRequest.ID, jsonRPCInternal, err.Error())\n\t\t\t} else if invalid != nil {\n\t\t\t\tgotils.L(ctx).Info().Printf(\"Request blocked: Invalid params: %v\", invalid)\n\t\t\t\treturn http.StatusBadRequest, jsonRPCError(parsedRequest.ID, jsonRPCInvalidParams, invalid.Error())\n\t\t\t}\n\t\t\tif r != nil {\n\t\t\t\tif l := r.len(); l > t.blockRangeLimit {\n\t\t\t\t\tgotils.L(ctx).Info().Println(\"Request blocked: Exceeds block range limit, range:\", l, \"limit:\", t.blockRangeLimit)\n\t\t\t\t\treturn http.StatusBadRequest, jsonRPCBlockRangeLimit(parsedRequest.ID, l, t.blockRangeLimit)\n\t\t\t\t}\n\t\t\t\tif union == nil {\n\t\t\t\t\tunion = r\n\t\t\t\t} else {\n\t\t\t\t\tunion.extend(r)\n\t\t\t\t\tif l := union.len(); l > t.blockRangeLimit {\n\t\t\t\t\t\tgotils.L(ctx).Info().Println(\"Request blocked: Exceeds block range limit, range:\", l, \"limit:\", t.blockRangeLimit)\n\t\t\t\t\t\treturn http.StatusBadRequest, jsonRPCBlockRangeLimit(parsedRequest.ID, l, t.blockRangeLimit)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, nil\n}", "func HttpRootHandler(w http.ResponseWriter, r *http.Request) {\n\tcmd := CommandStruct{}\n\n\tbs, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\t_ = json.Unmarshal(bs, &cmd)\n\tswitch cmd.Command {\n\tcase \"check\":\n\t\tfmt.Fprintln(w, \"HTTP-Server is online.\")\n\t\tbreak\n\n\tcase \"disc\":\n\t\tfmt.Fprintln(w, \"HTTP-Server shutting down...\")\n\t\thttpAlive <- 1\n\t\tbreak\n\n\tcase \"lista\":\n\t\tfmt.Fprintln(w, \"List of all available NBD-devices:\")\n\t\tfor key, value := range AvailableList {\n\t\t\tif AvailableList[key] != \"\" {\n\t\t\t\tfmt.Fprintln(w, value)\n\t\t\t}\n\t\t}\n\t\tbreak\n\n\tcase \"listm\":\n\t\tfmt.Fprintln(w, \"List of all mounted NBD-devices:\")\n\t\tfor key, value := range MountedList {\n\t\t\tfmt.Fprintln(w, key+\"\\t\"+value)\n\t\t}\n\t\tbreak\n\n\tcase \"mount\":\n\t\tif strings.Contains(cmd.Device, \"/dev/nbd\") {\n\t\t\tfor i := 0; i < len(AvailableList); i++ {\n\t\t\t\tif AvailableList[i] == cmd.Device {\n\n\t\t\t\t\tLinkedLogins[len(LinkedLogins)+1], err = nethandler.SetupConnection(cmd.Image, cmd.User, cmd.Pass, cmd.Device)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Fprintf(w, \"Error: \", err)\n\t\t\t\t\t\tfmt.Fprintf(w, \"\\n\")\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tAddToMountedList(cmd.Device, cmd.Image)\n\t\t\t\t\tfmt.Fprintf(w, \"Successfully mounted \"+cmd.Image+\" to \"+cmd.Device+\"\\n\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, value := range AvailableList {\n\t\t\t\tif value != \"\" {\n\t\t\t\t\tAddToMountedList(value, cmd.Image)\n\t\t\t\t\tfmt.Fprintf(w, \"Device \"+cmd.Device+\" is already mounted.\\n\"+cmd.Image+\" has been mounted to \"+value+\" instead.\\n\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Fprintf(w, \"No more devices available!\\n\")\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"Specified device not recognised.\\n\")\n\t\t}\n\t\tbreak\n\n\tcase \"unmount\":\n\t\t//TODO Real unmounting of NBD-devices\n\t\tfor key, _ := range AvailableList {\n\t\t\tif AvailableList[key] == \"\" {\n\t\t\t\tdelete(MountedList, cmd.Device)\n\t\t\t\tAvailableList[key] = cmd.Device\n\t\t\t\tfmt.Fprint(w, \"Successfully unmounted \"+cmd.Device)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n}", "func (app *Application) RequestItemHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := &struct{\n\t\tName string\n\t\tCat string\n\t\tAmount string\n\t\tRequest string\n\t\tMessage string\n\t\tTransactionId string\n\t\tSuccess bool\n\t\tResponse bool\n\n\t}{\n\t\tName: \"\",\n\t\tCat: \"\",\n\t\tAmount: \"\",\n\t\tRequest:\"\",\n\t\tMessage: \"\",\n\t\tTransactionId: \"\",\n\t\tSuccess:false,\n\t\tResponse:false,\n\t}\n\tnow:=time.Now()\n\tt:=strings.Split(now.String(),\" \")\n\tday:=t[0]\n\tif r.FormValue(\"submitted\") == \"true\" {\n\t\tname := r.FormValue(\"name\")\n\t\tcat := r.FormValue(\"cat_num\")\n\t\tamount:=r.FormValue(\"amount\")\n\t\trequest:=r.FormValue(\"request\")\n\t\tamount_f,_:= strconv.ParseFloat(amount,32)\n\n\t\tkey := \"new:\"+string(name)+\":\"+string(cat)\n\n\t\t//check if key exists, if yes, information will be updated otherwise error message will be returned \n\t\tresult_state :=checkState(app,key,w,r)\n\t\tvar j1 Parser.Inventory\n\t\tif name!=\"\" && cat!=\"\" && request!=\"\" && amount!=\"\"{\n\t\t\tif result_state !=\"\" {\n\t\t\t\t//update the amount information and add to ledger\n\t\t\t\tvar key_value []string\n\t\t\t\tkey_value = append(key_value,key)\n\t\t\t\tfmt.Println(\"key exists, updating the ledger\")\n\t\t\t\tjsonstr:=[]byte(result_state)\n\t\t\t\titem:=j1.ToJson(jsonstr)\n\t\t\t\titem.Amount= (item.Amount-float32(amount_f))\n\t\t\t\tfmt.Println(item.Amount)\n\n\t\t\t\titem.Request_by=request\n\t\t\t\titem_str:=j1.Tostring(&item)\n\t\t\t\tkey_value = append(key_value,item_str)\n\t\t\t\ttxid, err := app.Fabric.Invokekey(key_value)\n\t\t\t\tdata.Message=\"ledger has been successfully updated\"\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, \"Unable to invoke key in the blockchain\", 500)\n\t\t\t\t}\n\t\t\t\tdata.TransactionId=txid\n\t\t\t\tdata.Success=true\n\t\t\t\tdata.Response=true\n\t\t\t\tdata.Message=\"ledger has been updated but request tranaction has not been recoreded \"\n\t\t\t}else{\n\t\t\t\tdata.Message=\"No record found\"\n\t\t\t}\n\t\t\t//request transaction\n\t\t\tif data.Success && data.Response{\n\t\t\t\tn1:=rand.Intn(100)\n\t\t\t\tn2:=rand.Intn(100)\n\t\t\t\tkey=\"used:\"+string(name)+\":\"+string(cat)+\":\"+string(n1)+string(n2)\n\t\t\t\tkey=strings.ToLower(key)\n\t\t\t\tj1.Name=name\n\t\t\t\tj1.Catalog_num=cat\n\t\t\t\tj1.Amount=float32(amount_f)\n\t\t\t\tj1.Request_by=request\n\t\t\t\tj1.Purchase_date=day\n\t\t\t\ts:=j1.Tostring(&j1)\n\t\t\t\tvar key_value []string\n\t\t\t\tkey_value = append(key_value,key)\n\t\t\t\tkey_value = append(key_value,s)\n\t\t\t\t_, err := app.Fabric.Invokekey(key_value)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, \"Unable to invoke key in the blockchain\", 500)\n\t\t\t\t}\n\t\t\t\tdata.Message=\"ledger has been updated and request tranaction has been recoreded \"\n\t\t\t}\n\t\t}else{\n\t\t\tdata.Message=\"Please enter the name and catalog number\"\n\t\t}\n\n\t}\n\trenderTemplate(w, r, \"requestItem.html\", data)\n}", "func (s *SmartContract) requestLC(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n \n \n\t LC := LetterOfCredit{}\n \n\t err := json.Unmarshal([]byte(args[0]),&LC)\n if err != nil {\n\t\t return shim.Error(\"Not able to parse args into LC\")\n\t }\n \n // Verify that the Amount requested is within the limits of Buyer's bank\n\t\tif LC.Amount > 1000000 || LC.Amount < 10000 {\n\t\t\tfmt.Printf(\"The amount requested is not within the limits of Buyer bank to issue a Letter of Credit.\\n\")\n\t\t\treturn shim.Error(\"The amount requested is not within the limits of Buyer bank to issue a Letter of Credit.\\n\")\n\t\t}\n\t\tLC.Status = \"New\"\n\t LCBytes, err := json.Marshal(LC)\n\t APIstub.PutState(LC.LCId,LCBytes)\n\t fmt.Println(\"LC Requested -> \", LC)\n\t response:=struct{TxID string `json:\"txid\"`}{TxID: APIstub.GetTxID()}\n\t responsebytes,err := json.Marshal(response)\n\t return shim.Success(responsebytes)\n }", "func GetTransactionHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\t// retrieve the parameters\n\tparam := make(map[string]uint64)\n\tfor _, key := range []string{\"blockId\", \"txId\"} {\n\t\tparam[key], _ = strconv.ParseUint(vars[\"blockId\"], 10, 64)\n\t}\n\n\ttmp := atomic.LoadUint64(&lastBlock)\n\tif param[\"blockId\"] > tmp {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\terr := fmt.Errorf(\"requested id %d latest %d\", param[\"blockId\"], lastBlock)\n\t\tlog.Println(err.Error())\n\t\t_, _ = w.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\t// retuning anything in the body regardless of any error code\n\t// it may contain\n\t_, _, body, _ := dataCollection.GetTransaction(param[\"blockId\"], param[\"txId\"], config.DefaultRequestsTimeout)\n\twriteResponse(body, &w)\n}", "func (p *pbft) handleClientRequest(content []byte) {\n\tfmt.Println(\"The primary node has received the request from the client.\")\n\t//The Request structure is parsed using JSON\n\tr := new(Request)\n\terr := json.Unmarshal(content, r)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t//to add infoID\n\tp.sequenceIDAdd()\n\t//to get the digest\n\tdigest := getDigest(*r)\n\tfmt.Println(\"The request has been stored into the temporary message pool.\")\n\t//to store into the temp message pool\n\tp.messagePool[digest] = *r\n\t//to sign the digest by the primary node\n\tdigestByte, _ := hex.DecodeString(digest)\n\tsignInfo := p.RsaSignWithSha256(digestByte, p.node.rsaPrivKey)\n\t//setup PrePrepare message and send to other nodes\n\tpp := PrePrepare{*r, digest, p.sequenceID, signInfo}\n\tb, err := json.Marshal(pp)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tfmt.Println(\"sending PrePrepare messsage to all the other nodes...\")\n\t//to send PrePrepare message to other nodes\n\tp.broadcast(cPrePrepare, b)\n\tfmt.Println(\"PrePrepare is done.\")\n}", "func (t *Colorado) getMatchableTrades(stub shim.ChaincodeStubInterface, args []string) peer.Response {\n\t if len(args) != 1 {\n\t\t return shim.Error(\"Incorrect number of arguments. Expecting 1.\")\n\t }\n \n\t if len(args[0]) == 0 {\n\t\t return shim.Error(\"1st argument (Request JSON) must be a non-empty string, i.e. {\\\"investmentManager\\\":\\\"IMi\\\",\\\"executingBroker\\\":\\\"EBj\\\",\\\"tradeIdToBeMatched\\\":\\\"IDn\\\",\\\"matchableTradeIds\\\":[\\\"IDx\\\",\\\"IDy\\\",\\\"IDz\\\"]}\")\n\t }\n \n\t requestJSON := args[0]\n\t fmt.Println(\"- start getting matchable trades with request: \" + requestJSON)\n \n\t type requstType struct {\n\t\t InvestmentManager string `json:\"investmentManager\"` // the json fieldtags are needed to keep case from bouncing around\n\t\t ExecutingBroker string `json:\"executingBroker\"` // the json fieldtags are needed to keep case from bouncing around\n\t\t TradeIdToBeMatched string `json:\"tradeIdToBeMatched\"` // the json fieldtags are needed to keep case from bouncing around\n\t\t MatchableTradeIds []string `json:\"matchableTradeIds\"` // the json fieldtags are needed to keep case from bouncing around\n\t }\n\t var request requstType\n\t err := json.Unmarshal([]byte(requestJSON), &request)\n\t if err != nil {\n\t\t return shim.Error(\"Unable to parse request: \" + err.Error())\n\t }\n \n\t if len(request.TradeIdToBeMatched) == 0 {\n\t\t return shim.Success([]byte(\"There is no trade to be matched.\"))\n\t }\n \n\t // get trade to be matched\n\t privateCollection := \"privateTradeFor\" + request.InvestmentManager + request.ExecutingBroker\n\t tradeToBeMatchedAsBytes, err := stub.GetPrivateData(privateCollection, request.TradeIdToBeMatched)\n\t if err != nil {\n\t\t // e.g. no defined private collection for the combination of IM, EB\n\t\t return shim.Error(\"Unable to get trade: \" + err.Error())\n\t } else if tradeToBeMatchedAsBytes == nil {\n\t\t fmt.Println(\"This trade does not exist: \" + request.TradeIdToBeMatched)\n\t\t return shim.Error(\"This trade does not exist: \" + request.TradeIdToBeMatched)\n\t }\n\t tradeToBeMatched := trade{}\n\t err = json.Unmarshal(tradeToBeMatchedAsBytes, &tradeToBeMatched) // unmarshal it aka JSON.parse()\n\t if err != nil {\n\t\t return shim.Error(\"Unable to parse Trade To Be Matched: \" + err.Error())\n\t }\n \n\t // Query the tradeMatchingCompositeKey index by all fields in the composite key,\n\t // e.g. return all trades of a Source, a Buy Side, a Sell Side, a Product, a Sub-Product,\n\t // a Trade Date, a Quantity, a Price, a Security ID, and a Status\n\t var buffer bytes.Buffer\n\t delimiter := \",\"\n\t sourceToBeMatched := tradeToBeMatched.BuySide\n\t if tradeToBeMatched.Source == tradeToBeMatched.BuySide {\n\t\t sourceToBeMatched = tradeToBeMatched.SellSide\n\t }\n\t quantityToBeMatchedAsString := strconv.Itoa(tradeToBeMatched.Quantity)\n\t priceToBeMatchedAsString := strconv.FormatFloat(tradeToBeMatched.Price, 'f', -1, 64)\n\t tradeResultsIterator, err := stub.GetPrivateDataByPartialCompositeKey(privateCollection, \"tradeMatchingCompositeKey\", []string{sourceToBeMatched, tradeToBeMatched.BuySide, tradeToBeMatched.SellSide, tradeToBeMatched.Product, tradeToBeMatched.SubProduct, tradeToBeMatched.TradeDate, quantityToBeMatchedAsString, priceToBeMatchedAsString, tradeToBeMatched.SecurityId, \"CREATED\"})\n\t if err != nil {\n\t\t return shim.Error(\"Unable to call GetPrivateDataByPartialCompositeKey: \" + err.Error())\n\t }\n \n\t defer tradeResultsIterator.Close()\n\t for tradeResultsIterator.HasNext() {\n\t\t tradeResult, err := tradeResultsIterator.Next()\n\t\t if err != nil {\n\t\t\t return shim.Error(\"Unable to iterate through StateQueryIteratorInterface: \" + err.Error())\n\t\t }\n\t\t if buffer.Len() > 0 {\n\t\t\t buffer.WriteString(delimiter)\n\t\t }\n\t\t buffer.WriteString(\"\\\"\" + string(tradeResult.Value) + \"\\\"\")\n\t }\n \n\t responseJSON := fmt.Sprintf(\"{\\\"investmentManager\\\":\\\"%s\\\",\\\"executingBroker\\\":\\\"%s\\\",\\\"tradeIdToBeMatched\\\":\\\"%s\\\",\\\"matchableTradeIds\\\":[%s]}\", request.InvestmentManager, request.ExecutingBroker, request.TradeIdToBeMatched, buffer.String())\n\t fmt.Println(\"- end getting matchable trades with response: \" + responseJSON)\n \n\t return shim.Success([]byte(responseJSON))\n }", "func (kvs *keyValueServer) handleRequest(req *Request) {\n\tvar request []string\n\trequest = kvs.parseRequest(req.input)\n\tif request[0] == \"get\" {\n\t\tclient := kvs.clienter[req.cid]\n\t\tkvs.getFromDB(request, client)\n\t}\n\tif request[0] == \"put\" {\n\t\tkvs.putIntoDB(request)\n\t}\n}", "func (ch *ChainHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {\n\tctx := &Context{}\n\n\t// Build the context handler chain\n\thandler := ch.handler(ctx)\n\tchain := ch.chain\n\tfor chain != nil {\n\t\tif chain.middleware != nil {\n\t\t\thandler = chain.middleware(ctx, handler)\n\t\t}\n\t\tchain = chain.parent\n\t}\n\n\thandler.ServeHTTP(resp, req)\n}", "func RunAPI(server *Server, quit qu.C) {\n\tnrh := RPCHandlers\n\tgo func() {\n\t\tD.Ln(\"starting up node cAPI\")\n\t\tvar e error\n\t\tvar res interface{}\n\t\tfor {\n\t\t\tselect { \n\t\t\tcase msg := <-nrh[\"addnode\"].Call:\n\t\t\t\tif res, e = nrh[\"addnode\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.AddNodeCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan AddNodeRes) <-AddNodeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"createrawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"createrawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.CreateRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan CreateRawTransactionRes) <-CreateRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"decoderawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"decoderawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.DecodeRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.TxRawDecodeResult); ok { \n\t\t\t\t\tmsg.Ch.(chan DecodeRawTransactionRes) <-DecodeRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"decodescript\"].Call:\n\t\t\t\tif res, e = nrh[\"decodescript\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.DecodeScriptCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.DecodeScriptResult); ok { \n\t\t\t\t\tmsg.Ch.(chan DecodeScriptRes) <-DecodeScriptRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"estimatefee\"].Call:\n\t\t\t\tif res, e = nrh[\"estimatefee\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.EstimateFeeCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(float64); ok { \n\t\t\t\t\tmsg.Ch.(chan EstimateFeeRes) <-EstimateFeeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"generate\"].Call:\n\t\t\t\tif res, e = nrh[\"generate\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]string); ok { \n\t\t\t\t\tmsg.Ch.(chan GenerateRes) <-GenerateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getaddednodeinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getaddednodeinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetAddedNodeInfoCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.GetAddedNodeInfoResultAddr); ok { \n\t\t\t\t\tmsg.Ch.(chan GetAddedNodeInfoRes) <-GetAddedNodeInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getbestblock\"].Call:\n\t\t\t\tif res, e = nrh[\"getbestblock\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBestBlockResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBestBlockRes) <-GetBestBlockRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getbestblockhash\"].Call:\n\t\t\t\tif res, e = nrh[\"getbestblockhash\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBestBlockHashRes) <-GetBestBlockHashRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblock\"].Call:\n\t\t\t\tif res, e = nrh[\"getblock\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBlockVerboseResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockRes) <-GetBlockRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockchaininfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockchaininfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBlockChainInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockChainInfoRes) <-GetBlockChainInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockcount\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockcount\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(int64); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockCountRes) <-GetBlockCountRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockhash\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockhash\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockHashCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockHashRes) <-GetBlockHashRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblockheader\"].Call:\n\t\t\t\tif res, e = nrh[\"getblockheader\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockHeaderCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetBlockHeaderVerboseResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockHeaderRes) <-GetBlockHeaderRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getblocktemplate\"].Call:\n\t\t\t\tif res, e = nrh[\"getblocktemplate\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetBlockTemplateCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetBlockTemplateRes) <-GetBlockTemplateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getcfilter\"].Call:\n\t\t\t\tif res, e = nrh[\"getcfilter\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetCFilterCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetCFilterRes) <-GetCFilterRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getcfilterheader\"].Call:\n\t\t\t\tif res, e = nrh[\"getcfilterheader\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetCFilterHeaderCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetCFilterHeaderRes) <-GetCFilterHeaderRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getconnectioncount\"].Call:\n\t\t\t\tif res, e = nrh[\"getconnectioncount\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(int32); ok { \n\t\t\t\t\tmsg.Ch.(chan GetConnectionCountRes) <-GetConnectionCountRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getcurrentnet\"].Call:\n\t\t\t\tif res, e = nrh[\"getcurrentnet\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetCurrentNetRes) <-GetCurrentNetRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getdifficulty\"].Call:\n\t\t\t\tif res, e = nrh[\"getdifficulty\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetDifficultyCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(float64); ok { \n\t\t\t\t\tmsg.Ch.(chan GetDifficultyRes) <-GetDifficultyRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getgenerate\"].Call:\n\t\t\t\tif res, e = nrh[\"getgenerate\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetHeadersCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(bool); ok { \n\t\t\t\t\tmsg.Ch.(chan GetGenerateRes) <-GetGenerateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"gethashespersec\"].Call:\n\t\t\t\tif res, e = nrh[\"gethashespersec\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(float64); ok { \n\t\t\t\t\tmsg.Ch.(chan GetHashesPerSecRes) <-GetHashesPerSecRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getheaders\"].Call:\n\t\t\t\tif res, e = nrh[\"getheaders\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetHeadersCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetHeadersRes) <-GetHeadersRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.InfoChainResult0); ok { \n\t\t\t\t\tmsg.Ch.(chan GetInfoRes) <-GetInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getmempoolinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getmempoolinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetMempoolInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetMempoolInfoRes) <-GetMempoolInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getmininginfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getmininginfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetMiningInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetMiningInfoRes) <-GetMiningInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getnettotals\"].Call:\n\t\t\t\tif res, e = nrh[\"getnettotals\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetNetTotalsResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetNetTotalsRes) <-GetNetTotalsRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getnetworkhashps\"].Call:\n\t\t\t\tif res, e = nrh[\"getnetworkhashps\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetNetworkHashPSCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.GetPeerInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetNetworkHashPSRes) <-GetNetworkHashPSRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getpeerinfo\"].Call:\n\t\t\t\tif res, e = nrh[\"getpeerinfo\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.GetPeerInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan GetPeerInfoRes) <-GetPeerInfoRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getrawmempool\"].Call:\n\t\t\t\tif res, e = nrh[\"getrawmempool\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetRawMempoolCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetRawMempoolRes) <-GetRawMempoolRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"getrawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"getrawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetRawTransactionRes) <-GetRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"gettxout\"].Call:\n\t\t\t\tif res, e = nrh[\"gettxout\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.GetTxOutCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan GetTxOutRes) <-GetTxOutRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"help\"].Call:\n\t\t\t\tif res, e = nrh[\"help\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.HelpCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan HelpRes) <-HelpRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"node\"].Call:\n\t\t\t\tif res, e = nrh[\"node\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.NodeCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan NodeRes) <-NodeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"ping\"].Call:\n\t\t\t\tif res, e = nrh[\"ping\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan PingRes) <-PingRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"resetchain\"].Call:\n\t\t\t\tif res, e = nrh[\"resetchain\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan ResetChainRes) <-ResetChainRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"restart\"].Call:\n\t\t\t\tif res, e = nrh[\"restart\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan RestartRes) <-RestartRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"searchrawtransactions\"].Call:\n\t\t\t\tif res, e = nrh[\"searchrawtransactions\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SearchRawTransactionsCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.([]btcjson.SearchRawTransactionsResult); ok { \n\t\t\t\t\tmsg.Ch.(chan SearchRawTransactionsRes) <-SearchRawTransactionsRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"sendrawtransaction\"].Call:\n\t\t\t\tif res, e = nrh[\"sendrawtransaction\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SendRawTransactionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan SendRawTransactionRes) <-SendRawTransactionRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"setgenerate\"].Call:\n\t\t\t\tif res, e = nrh[\"setgenerate\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SetGenerateCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan SetGenerateRes) <-SetGenerateRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"stop\"].Call:\n\t\t\t\tif res, e = nrh[\"stop\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(None); ok { \n\t\t\t\t\tmsg.Ch.(chan StopRes) <-StopRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"submitblock\"].Call:\n\t\t\t\tif res, e = nrh[\"submitblock\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.SubmitBlockCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(string); ok { \n\t\t\t\t\tmsg.Ch.(chan SubmitBlockRes) <-SubmitBlockRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"uptime\"].Call:\n\t\t\t\tif res, e = nrh[\"uptime\"].\n\t\t\t\t\tFn(server, msg.Params.(*None), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.GetMempoolInfoResult); ok { \n\t\t\t\t\tmsg.Ch.(chan UptimeRes) <-UptimeRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"validateaddress\"].Call:\n\t\t\t\tif res, e = nrh[\"validateaddress\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.ValidateAddressCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(btcjson.ValidateAddressChainResult); ok { \n\t\t\t\t\tmsg.Ch.(chan ValidateAddressRes) <-ValidateAddressRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"verifychain\"].Call:\n\t\t\t\tif res, e = nrh[\"verifychain\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.VerifyChainCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(bool); ok { \n\t\t\t\t\tmsg.Ch.(chan VerifyChainRes) <-VerifyChainRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"verifymessage\"].Call:\n\t\t\t\tif res, e = nrh[\"verifymessage\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.VerifyMessageCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(bool); ok { \n\t\t\t\t\tmsg.Ch.(chan VerifyMessageRes) <-VerifyMessageRes{&r, e} } \n\t\t\tcase msg := <-nrh[\"version\"].Call:\n\t\t\t\tif res, e = nrh[\"version\"].\n\t\t\t\t\tFn(server, msg.Params.(*btcjson.VersionCmd), nil); E.Chk(e) {\n\t\t\t\t}\n\t\t\t\tif r, ok := res.(map[string]btcjson.VersionResult); ok { \n\t\t\t\t\tmsg.Ch.(chan VersionRes) <-VersionRes{&r, e} } \n\t\t\tcase <-quit.Wait():\n\t\t\t\tD.Ln(\"stopping wallet cAPI\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func restAPI(keyCollection *ED25519Keys) {\n\n\t// CORS\n\tcorsAllowedHeaders := []string{\n\t\t\"Access-Control-Allow-Headers\",\n\t\t\"Access-Control-Allow-Methods\",\n\t\t\"Access-Control-Allow-Origin\",\n\t\t\"Cache-Control\",\n\t\t\"Content-Security-Policy\",\n\t\t\"Feature-Policy\",\n\t\t\"Referrer-Policy\",\n\t\t\"X-Requested-With\"}\n\n\tcorsOrigins := []string{\n\t\t\"*\",\n\t\t\"127.0.0.1\"}\n\n\tcorsMethods := []string{\n\t\t\"GET\",\n\t\t\"HEAD\",\n\t\t\"POST\",\n\t\t\"PUT\",\n\t\t\"OPTIONS\"}\n\n\theadersCORS := handlers.AllowedHeaders(corsAllowedHeaders)\n\toriginsCORS := handlers.AllowedOrigins(corsOrigins)\n\tmethodsCORS := handlers.AllowedMethods(corsMethods)\n\n\t// Init API\n\tr := mux.NewRouter()\n\tapi := r.PathPrefix(\"/api/v1\").Subrouter()\n\n\t// Home\n\tapi.HandleFunc(\"/\", home).Methods(http.MethodGet)\n\n\t// Version\n\tapi.HandleFunc(\"/version\", returnVersion).Methods(http.MethodGet)\n\n\t// Stats\n\tapi.HandleFunc(\"/stats\", func(w http.ResponseWriter, r *http.Request) {\n\t\treturnStatsWeb(w, r, keyCollection)\n\t}).Methods(http.MethodGet)\n\n\t// Transaction by ID\n\tapi.HandleFunc(\"/transaction/{hash}\", func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\thash := vars[\"hash\"]\n\t\treturnSingleTransaction(w, r, hash)\n\t}).Methods(http.MethodGet)\n\n\t// Transaction by qty\n\tapi.HandleFunc(\"/transactions/{number}\", func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\tnumber := vars[\"number\"]\n\t\treturnNTransactions(w, r, number)\n\t}).Methods(http.MethodGet)\n\n\t// Channel Socket\n\tapi.HandleFunc(\"/channel\", func(w http.ResponseWriter, r *http.Request) {\n\t\tupgrader.CheckOrigin = func(r *http.Request) bool { return true }\n\t\tconn, _ := upgrader.Upgrade(w, r, nil)\n\t\tdefer conn.Close()\n\t\t// fmt.Printf(brightgreen+\"\\n[%s] [%s] Peer socket opened!\"+white, timeStamp(), conn.RemoteAddr())\n\t\tsocketAuthAgent(conn, keyCollection)\n\t})\n\n\t// Serve via HTTP\n\thttp.ListenAndServe(\":\"+strconv.Itoa(karaiAPIPort), handlers.CORS(headersCORS, originsCORS, methodsCORS)(api))\n}", "func checkinHandler(wrt http.ResponseWriter, req *http.Request) {\n\t// use h2conn\n\tconn, err := h2conn.Accept(wrt, req)\n\tdefer func() {\n\t\terr = conn.Close()\n\t\tif err != nil {\n\t\t\tCliPrintWarning(\"checkinHandler close connection: %v\", err)\n\t\t}\n\t\tif DebugLevel >= 4 {\n\t\t\tCliPrintDebug(\"checkinHandler finished\")\n\t\t}\n\t}()\n\tif err != nil {\n\t\tCliPrintError(\"checkinHandler: failed creating connection from %s: %s\", req.RemoteAddr, err)\n\t\thttp.Error(wrt, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar (\n\t\ttarget emp3r0r_data.AgentSystemInfo\n\t\tin = json.NewDecoder(conn)\n\t)\n\n\terr = in.Decode(&target)\n\tif err != nil {\n\t\tCliPrintWarning(\"checkinHandler decode: %v\", err)\n\t\treturn\n\t}\n\n\t// set target IP\n\ttarget.From = req.RemoteAddr\n\n\tif !IsAgentExist(&target) {\n\t\tinx := assignTargetIndex()\n\t\tTargetsMutex.RLock()\n\t\tTargets[&target] = &Control{Index: inx, Conn: nil}\n\t\tTargetsMutex.RUnlock()\n\t\tshortname := strings.Split(target.Tag, \"-agent\")[0]\n\t\t// set labels\n\t\tif util.IsExist(AgentsJSON) {\n\t\t\tif l := SetAgentLabel(&target); l != \"\" {\n\t\t\t\tshortname = l\n\t\t\t}\n\t\t}\n\t\tCliMsg(\"Checked in: %s from %s, \"+\n\t\t\t\"running %s\\n\",\n\t\t\tstrconv.Quote(shortname), fmt.Sprintf(\"'%s - %s'\", target.From, target.Transport),\n\t\t\tstrconv.Quote(target.OS))\n\n\t\tListTargets() // refresh agent list\n\t} else {\n\t\t// just update this agent's sysinfo\n\t\tfor a := range Targets {\n\t\t\tif a.Tag == target.Tag {\n\t\t\t\ta = &target\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tshortname := strings.Split(target.Tag, \"-agent\")[0]\n\t\t// set labels\n\t\tif util.IsExist(AgentsJSON) {\n\t\t\tif l := SetAgentLabel(&target); l != \"\" {\n\t\t\t\tshortname = l\n\t\t\t}\n\t\t}\n\t\tif DebugLevel >= 4 {\n\t\t\tCliPrintDebug(\"Refreshing sysinfo\\n%s from %s, \"+\n\t\t\t\t\"running %s\\n\",\n\t\t\t\tshortname, fmt.Sprintf(\"%s - %s\", target.From, target.Transport),\n\t\t\t\tstrconv.Quote(target.OS))\n\t\t}\n\t}\n}", "func (t TransactionHandler) route() {\n\tt.Router.HandleFunc(\"/getItemList\", t.respond(getItemList, handleError)).Methods(\"POST\")\n\tt.Router.HandleFunc(\"/addItems\", t.respond(createItems, handleError)).Methods(\"POST\")\n\tt.Router.HandleFunc(\"/submitTx\", t.respond(submitTx, handleError)).Methods(\"POST\")\n\tt.Router.HandleFunc(\"/getTxByRecipient\", t.respond(getRecipientTx, handleError)).Methods(\"POST\")\n\tt.Router.HandleFunc(\"/getTxByMerchant\", t.respond(getMerchantTx, handleError)).Methods(\"POST\")\n}", "func innerRouter(e *bm.Engine) {\n\t// health check\n\te.Ping(ping)\n\tspy := e.Group(\"/x/admin/spy\", vfySvc.Verify)\n\n\tscore := spy.Group(\"/score\")\n\tscore.GET(\"/query\", userInfo)\n\tscore.GET(\"/record\", historyPage)\n\tscore.POST(\"/base/reset\", resetBase)\n\tscore.POST(\"/base/refresh\", refreshBase)\n\tscore.POST(\"/event/reset\", resetEvent)\n\n\tspy.POST(\"/stat/clear\", clearCount)\n\n\tfactor := spy.Group(\"/factor\")\n\tfactor.GET(\"/list\", factors)\n\tfactor.POST(\"/add\", addFactor)\n\tfactor.POST(\"/modify\", updateFactor)\n\n\tspy.POST(\"/event/add\", addEvent)\n\tspy.POST(\"/event/modify\", updateEventName)\n\tspy.POST(\"/service/add\", addService)\n\tspy.POST(\"/group/add\", addGroup)\n\n\tsetting := spy.Group(\"/setting\")\n\tsetting.GET(\"/list\", settingList)\n\tsetting.POST(\"/add\", updateSetting)\n\n\tsin := spy.Group(\"/sin\")\n\tsin.POST(\"/state/update\", updateStatState)\n\tsin.POST(\"/quantity/update\", updateStatQuantity)\n\tsin.POST(\"/delete\", deleteStat)\n\tsin.POST(\"/remark/add\", addRemark)\n\tsin.GET(\"/remark/list\", remarkList)\n\tsin.GET(\"/page\", statPage)\n\n\tspy.GET(\"/report\", report)\n\n\tspyWithoutAuth := e.Group(\"/x/admin/spy/internal\")\n\tspyWithoutAuth.POST(\"/event/add\", addEvent)\n\tspyWithoutAuth.POST(\"/event/modify\", updateEventName)\n\n\tscoreWithoutAuth := spyWithoutAuth.Group(\"/score\")\n\tscoreWithoutAuth.GET(\"/query\", userInfo)\n\tscoreWithoutAuth.GET(\"/record\", historyPage)\n\tscoreWithoutAuth.POST(\"/base/reset\", resetBase)\n\tscoreWithoutAuth.POST(\"/base/refresh\", refreshBase)\n\tscoreWithoutAuth.POST(\"/event/reset\", resetEvent)\n\n\tfactorWithoutAuth := spyWithoutAuth.Group(\"/factor\")\n\tfactorWithoutAuth.GET(\"/list\", factors)\n\tfactorWithoutAuth.POST(\"/add\", addFactor)\n\tfactorWithoutAuth.POST(\"/modify\", updateFactor)\n}", "func doRelay(w http.ResponseWriter, r *http.Request) {\n\treg := regexp.MustCompile(\"^\" + ServerURL + `/relay/(([^/]+)/[^/]*.*)`)\n\tm := reg.FindStringSubmatch(r.URL.Path)\n\tif m == nil || len(m) < 3 {\n\t\tlog.Println(\"invalid path\", r.URL.Path)\n\t\treturn\n\t}\n\tbackup := r.URL\n\tvar err error\n\tr.URL, err = url.ParseRequestURI(\"http://\" + m[1])\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\thost, port, err := net.SplitHostPort(m[2])\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tp, err := strconv.Atoi(port)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tn, err := node.MakeNode(host, \"/server.cgi\", p)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif !n.IsAllowed() {\n\t\tlog.Println(n, \"is not allowed\")\n\t\treturn\n\t}\n\trelay.HandleServer(host, w, r, func(res *relay.ResponseWriter) bool {\n\t\treturn true\n\t})\n\tr.URL = backup\n}" ]
[ "0.5844577", "0.56329745", "0.5578209", "0.5482666", "0.54420656", "0.5347861", "0.5323568", "0.5304798", "0.5262302", "0.52571183", "0.52263904", "0.5204237", "0.51906383", "0.518504", "0.51638216", "0.5162992", "0.51466084", "0.5141968", "0.510756", "0.5105206", "0.5061075", "0.5056672", "0.5052943", "0.503437", "0.503306", "0.5031393", "0.4978272", "0.49739933", "0.4968316", "0.49655893", "0.49636143", "0.49613485", "0.49551892", "0.4941611", "0.49307904", "0.49289492", "0.4920729", "0.49034962", "0.48969778", "0.489539", "0.48823187", "0.48808822", "0.48775887", "0.48765028", "0.48739392", "0.48656362", "0.48648402", "0.48644635", "0.48588282", "0.4858737", "0.48537132", "0.48535216", "0.484702", "0.48468614", "0.4835262", "0.48324993", "0.48161256", "0.48119038", "0.4801349", "0.4795432", "0.47826573", "0.47750232", "0.4774838", "0.477007", "0.47645357", "0.475612", "0.47518405", "0.47485512", "0.4735963", "0.4735281", "0.47245362", "0.47236997", "0.4722676", "0.47201127", "0.4715891", "0.47139502", "0.47089225", "0.4706828", "0.47014096", "0.47010025", "0.47007397", "0.46979675", "0.46954766", "0.46946043", "0.46937424", "0.46932673", "0.4691379", "0.4691316", "0.46822703", "0.46770456", "0.467483", "0.46741638", "0.4673024", "0.46704772", "0.4662734", "0.46625674", "0.46592507", "0.46549356", "0.4653205", "0.46507657" ]
0.62619346
0
Handler to manage requests to /garage/ subchain
func garageViewHandler(w http.ResponseWriter, r *http.Request) { // Take the URL beyond /garage/ and split into request and value strings requestAction := strings.Split(r.URL.String(), "/") requestItem, err := strconv.Atoi(requestAction[3]) if err != nil { log.Println("INFO: garageViewHandler(): No garage id requested, setting to -1") requestItem = -1 } if requestItem < 0 { //no value so display them all garageString, err := json.MarshalIndent(ValidGarages, "", "\t") if err != nil { log.Println("ERROR: garageViewHandler(): Cannot print Garages JSON data") } fmt.Fprintf(w, "\n %s", garageString) } else { garageString, _ := json.MarshalIndent(ValidGarages[requestItem], "", "\t") // Do nothing if index too high fmt.Fprintf(w, "\n %s.", garageString) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *Frontend) triageHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\ttr := &TriageRequest{}\n\tif err := json.NewDecoder(r.Body).Decode(tr); err != nil {\n\t\thttputils.ReportError(w, err, \"Failed to decode JSON.\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif !f.isEditor(w, r, \"triage\", tr) {\n\t\treturn\n\t}\n\tdetail, err := f.perfGit.CommitFromCommitNumber(ctx, tr.Cid)\n\tif err != nil {\n\t\thttputils.ReportError(w, err, \"Failed to find CommitID.\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tkey := tr.Alert.IDAsString\n\tif tr.ClusterType == \"low\" {\n\t\terr = f.regStore.TriageLow(r.Context(), detail.CommitNumber, key, tr.Triage)\n\t} else {\n\t\terr = f.regStore.TriageHigh(r.Context(), detail.CommitNumber, key, tr.Triage)\n\t}\n\n\tif err != nil {\n\t\thttputils.ReportError(w, err, \"Failed to triage.\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlink := fmt.Sprintf(\"%s/t/?begin=%d&end=%d&subset=all\", r.Header.Get(\"Origin\"), detail.Timestamp, detail.Timestamp+1)\n\n\tresp := &TriageResponse{}\n\n\tif tr.Triage.Status == regression.Negative && config.Config.NotifyConfig.Notifications != notifytypes.MarkdownIssueTracker {\n\t\tcfgs, err := f.configProvider(ctx)\n\t\tif err != nil {\n\t\t\tsklog.Errorf(\"Failed to load configs looking for BugURITemplate: %s\", err)\n\t\t}\n\t\turitemplate := defaultBugURLTemplate\n\t\tfor _, c := range cfgs {\n\t\t\tif c.IDAsString == tr.Alert.IDAsString {\n\t\t\t\tif c.BugURITemplate != \"\" {\n\t\t\t\t\turitemplate = c.BugURITemplate\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tresp.Bug = bug.Expand(uritemplate, link, detail, tr.Triage.Message)\n\t}\n\tif err := json.NewEncoder(w).Encode(resp); err != nil {\n\t\tsklog.Errorf(\"Failed to write or encode output: %s\", err)\n\t}\n}", "func (g *Group) GET(path string, h Handler, gases ...Gas) {\n\tg.Air.GET(g.Prefix+path, h, append(g.Gases, gases...)...)\n}", "func (t *targetrunner) bucketHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tt.httpbckget(w, r)\n\tcase http.MethodDelete:\n\t\tt.httpbckdelete(w, r)\n\tcase http.MethodPost:\n\t\tt.httpbckpost(w, r)\n\tcase http.MethodHead:\n\t\tt.httpbckhead(w, r)\n\tdefault:\n\t\tinvalhdlr(w, r)\n\t}\n}", "func rootHandler(w http.ResponseWriter, r *http.Request) {\n\tparts := strings.Split(r.URL.Path, \"/\")\n\tif r.URL.Path == \"/igcinfo/api/\" {\n\t\tinfoHandler(w, r)\n\t\treturn\n\t} else if r.URL.Path == \"/igcinfo/api/igc/\" {\n\t\tigcHandler(w, r)\n\t\treturn\n\t} else if id, err := uuid.Parse(parts[4]); strings.HasPrefix(r.URL.Path, \"/igcinfo/api/igc/\") && err == nil && len(parts) < 6 {\n\t\ttrackHandler(w, r, id)\n\t\treturn\n\t} else if id, err := uuid.Parse(parts[4]); strings.HasPrefix(r.URL.Path, \"/igcinfo/api/igc/\") && err == nil && len(parts[5]) > 0 {\n\t\ttrackFieldHandler(w, r, id, parts[5])\n\t\treturn\n\t}\n\n\thttp.NotFound(w, r)\n}", "func (t *targetrunner) bucketHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tt.httpbckget(w, r)\n\tcase http.MethodDelete:\n\t\tt.httpbckdelete(w, r)\n\tcase http.MethodPost:\n\t\tt.httpbckpost(w, r)\n\tcase http.MethodHead:\n\t\tt.httpbckhead(w, r)\n\tdefault:\n\t\tcmn.InvalidHandlerWithMsg(w, r, \"invalid method for /buckets path\")\n\t}\n}", "func (t *targetrunner) bucketHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tt.httpbckget(w, r)\n\tcase http.MethodDelete:\n\t\tt.httpbckdelete(w, r)\n\tcase http.MethodPost:\n\t\tt.httpbckpost(w, r)\n\tcase http.MethodHead:\n\t\tt.httpbckhead(w, r)\n\tdefault:\n\t\tcmn.InvalidHandlerWithMsg(w, r, \"invalid method for /buckets path\")\n\t}\n}", "func Router(rg *gin.RouterGroup) {\n\trg.POST(\"/signupmerchant\" /*service.Authorization(\"admin\"),*/, SignUpMerchant)\n\trg.POST(\"/setupmerchantimage\" /*service.Authorization(\"admin\"),*/, SetupMerchantImage)\n\trg.POST(\"/setupmerchantmanager\" /*service.Authorization(\"admin\"),*/, SetupMerchantManager)\n\trg.POST(\"/changestatus\", service.Authorization(constants.MERCHANTADMIN), ChangeStatus)\n\trg.GET(\"/list\", service.Authorization(constants.MERCHANTADMIN), List)\n}", "func (g *Gateway) dashHandler(c *gin.Context) {\n\tctx, cancel := context.WithTimeout(context.Background(), handlerTimeout)\n\tdefer cancel()\n\n\tproject := c.Param(\"project\")\n\trep, err := g.client.ListBucketPath(ctx, project, c.Param(\"path\"), g.clientAuth)\n\tif err != nil {\n\t\tabort(c, http.StatusNotFound, fmt.Errorf(\"project not found\"))\n\t\treturn\n\t}\n\n\tif !rep.Item.IsDir {\n\t\tif err := g.client.PullBucketPath(ctx, c.Param(\"path\"), c.Writer, g.clientAuth); err != nil {\n\t\t\tabort(c, http.StatusInternalServerError, err)\n\t\t}\n\t} else {\n\t\tprojectPath := path.Join(\"dashboard\", project)\n\n\t\tlinks := make([]link, len(rep.Item.Items))\n\t\tfor i, item := range rep.Item.Items {\n\t\t\tvar pth string\n\t\t\tif rep.Root != nil {\n\t\t\t\tpth = strings.Replace(item.Path, rep.Root.Path, rep.Root.Name, 1)\n\t\t\t} else {\n\t\t\t\tpth = item.Name\n\t\t\t}\n\n\t\t\tlinks[i] = link{\n\t\t\t\tName: item.Name,\n\t\t\t\tPath: path.Join(projectPath, pth),\n\t\t\t\tSize: byteCountDecimal(item.Size),\n\t\t\t\tLinks: strconv.Itoa(len(item.Items)),\n\t\t\t}\n\t\t}\n\n\t\tvar root, back string\n\t\tif rep.Root != nil {\n\t\t\troot = strings.Replace(rep.Item.Path, rep.Root.Path, rep.Root.Name, 1)\n\t\t} else {\n\t\t\troot = \"\"\n\t\t}\n\t\tif root == \"\" {\n\t\t\tback = projectPath\n\t\t} else {\n\t\t\tback = path.Dir(path.Join(projectPath, root))\n\t\t}\n\t\tc.HTML(http.StatusOK, \"/public/html/buckets.gohtml\", gin.H{\n\t\t\t\"Path\": rep.Item.Path,\n\t\t\t\"Root\": root,\n\t\t\t\"Back\": back,\n\t\t\t\"Links\": links,\n\t\t})\n\t}\n}", "func (ctx *Context) UserGroceriesHandler(w http.ResponseWriter, r *http.Request) {\n\t//gets the current user\n\tstate := &SessionState{}\n\ts, err := sessions.GetSessionID(r, ctx.SessionKey)\n\tif err != nil {\n\t\thttp.Error(w, \"Error getting sessionID\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\terr = ctx.SessionStore.Get(s, state)\n\tif err != nil {\n\t\thttp.Error(w, \"Error getting session\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tuser := state.User\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tgroceries, err := ctx.UserStore.GetUserGroceries(user)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Error fetching groceries\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Add(\"Content-Type\", contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(groceries.Ingredients)\n\tcase \"POST\": //Adds a grocery to users list\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tnewGrocery := &users.SpecificGrocery{}\n\t\tif err := decoder.Decode(newGrocery); err != nil {\n\t\t\thttp.Error(w, \"Invalid JSON\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t//Adds grocery\n\t\terr := ctx.UserStore.AddToGrocery(user, newGrocery.Grocery)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Error adding grocery\", http.StatusInternalServerError)\n\t\t}\n\t\t//Get all the diets to return\n\t\tallGroceries, err := ctx.UserStore.GetUserGroceries(user)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Unable to get groceries\", http.StatusInternalServerError)\n\t\t}\n\t\tw.Header().Add(\"Content-Type\", contentTypeJSONUTF8)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(allGroceries.Ingredients)\n\tcase \"DELETE\": //Adds a grocery to users list\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tnewGrocery := &users.SpecificGrocery{}\n\t\tif err := decoder.Decode(newGrocery); err != nil {\n\t\t\thttp.Error(w, \"Invalid JSON\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t//Delete grocery\n\t\terr := ctx.UserStore.DeleteFromGrocery(user, newGrocery.Grocery)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Error removing grocery\", http.StatusInternalServerError)\n\t\t}\n\t\tw.Header().Add(\"Content-Type\", contentTypeTextUTF8)\n\t\tw.Write([]byte(\"removed grocery from list\"))\n\t}\n}", "func router(writer http.ResponseWriter, request *http.Request) {\n\twriter.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t//writer.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n \twriter.Header().Set(\"Content-Type\", \"application/json\")\n\n\t// build the url\n\turl := request.URL.Scheme + request.URL.Opaque + request.URL.Host + request.URL.Path\n\n\t// Append the query if any exists\n\tif request.URL.RawQuery != \"\" {\n\t\turl += \"?\" + request.URL.RawQuery\n\t}\n\n\t// kill the favicon\n\tif url == \"/favicon.ico\" {\n\t\tkill_favicon(writer)\n\t\treturn\n\t}\n\n\tpath := request.URL.Path[len(\"/\"):]\n\tsfxlog.Log(nil, \"main.go:router() \" + request.Method + \" \" + request.Proto + \" \" + url, \"info\")\n\n\tswitch path {\n\tcase \"geofence\":\n\t\trt_geomap(writer, request)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(writer, \"Sphire API\")\n}", "func otelBaggageExtractor(next http.Handler) http.Handler {\n\tpropagator := propagation.Baggage{}\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tcarrier := propagation.HeaderCarrier(r.Header)\n\t\tctx := propagator.Extract(r.Context(), carrier)\n\t\tr = r.WithContext(ctx)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func SpecificCourseRelationHandler(w http.ResponseWriter, r *http.Request) {\n}", "func (_tree *tree) serve(reqCtx *fasthttp.RequestCtx, path string) bool {\n\tctx := _tree.pool.Get().(*Context)\n\tctx.Reset(reqCtx)\n\tmiddleware, params, mustRedirect := _tree.rootBranch.GetBranch(path, ctx.Params) // pass the parameters here for 0 allocation\n\tif middleware != nil {\n\t\tctx.Params = params\n\t\tctx.middleware = middleware\n\t\t//ctx.Request.Header.SetUserAgentBytes(DefaultUserAgent)\n\t\tctx.Do()\n\t\t_tree.pool.Put(ctx)\n\t\treturn true\n\t} else if mustRedirect && !_tree.station.config.DisablePathCorrection && !bytes.Equal(reqCtx.Method(), MethodConnectBytes) {\n\n\t\treqPath := path\n\t\tpathLen := len(reqPath)\n\n\t\tif pathLen > 1 {\n\n\t\t\tif reqPath[pathLen-1] == '/' {\n\t\t\t\treqPath = reqPath[:pathLen-1] //remove the last /\n\t\t\t} else {\n\t\t\t\t//it has path prefix, it doesn't ends with / and it hasn't be found, then just add the slash\n\t\t\t\treqPath = reqPath + \"/\"\n\t\t\t}\n\n\t\t\tctx.Request.URI().SetPath(reqPath)\n\t\t\turlToRedirect := utils.BytesToString(ctx.Request.RequestURI())\n\n\t\t\tctx.Redirect(urlToRedirect, 301) //\tStatusMovedPermanently\n\t\t\t// RFC2616 recommends that a short note \"SHOULD\" be included in the\n\t\t\t// response because older user agents may not understand 301/307.\n\t\t\t// Shouldn't send the response for POST or HEAD; that leaves GET.\n\t\t\tif _tree.method == MethodGet {\n\t\t\t\tnote := \"<a href=\\\"\" + utils.HTMLEscape(urlToRedirect) + \"\\\">Moved Permanently</a>.\\n\"\n\t\t\t\tctx.Write(note)\n\t\t\t}\n\t\t\t_tree.pool.Put(ctx)\n\t\t\treturn true\n\t\t}\n\t}\n\n\t_tree.pool.Put(ctx)\n\treturn false\n}", "func (t *targetrunner) ecHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\tt.httpecget(w, r)\n\tdefault:\n\t\tcmn.InvalidHandlerWithMsg(w, r, \"invalid method for /slices path\")\n\t}\n}", "func main() {\n\trouter := mux.NewRouter()\n\n\trouter.HandleFunc(\"/property/{name}/{prop}\", GetProcessedProperty).Methods(\"GET\")\n\t//router.HandleFunc(\"/graph/{name}/{prop}\", GetProcessedGraph).Methods(\"GET\")\n\trouter.HandleFunc(\"/graph/{name}/{prop}/{tmout}/{speed}\", GetProcessedGraph).Methods(\"GET\")\n\n\thandler := cors.Default().Handler(router)\n\tlog.Fatal(http.ListenAndServe(\":8000\", handler))\n}", "func Router(c *ctx.AptlyContext) http.Handler {\n\tif aptly.EnableDebug {\n\t\tgin.SetMode(gin.DebugMode)\n\t} else {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\trouter := gin.New()\n\tcontext = c\n\n\trouter.UseRawPath = true\n\n\tif c.Config().LogFormat == \"json\" {\n\t\tc.StructuredLogging(true)\n\t\tutils.SetupJSONLogger(c.Config().LogLevel, os.Stdout)\n\t\tgin.DefaultWriter = utils.LogWriter{Logger: log.Logger}\n\t\trouter.Use(JSONLogger())\n\t} else {\n\t\tc.StructuredLogging(false)\n\t\tutils.SetupDefaultLogger(c.Config().LogLevel)\n\t\trouter.Use(gin.Logger())\n\t}\n\n\trouter.Use(gin.Recovery(), gin.ErrorLogger())\n\n\tif c.Config().EnableMetricsEndpoint {\n\t\tMetricsCollectorRegistrar.Register(router)\n\t}\n\n\tif c.Config().ServeInAPIMode {\n\t\trouter.GET(\"/repos/\", reposListInAPIMode(c.Config().FileSystemPublishRoots))\n\t\trouter.GET(\"/repos/:storage/*pkgPath\", reposServeInAPIMode)\n\t}\n\n\tapi := router.Group(\"/api\")\n\tif context.Flags().Lookup(\"no-lock\").Value.Get().(bool) {\n\t\t// We use a goroutine to count the number of\n\t\t// concurrent requests. When no more requests are\n\t\t// running, we close the database to free the lock.\n\t\tdbRequests = make(chan dbRequest)\n\n\t\tgo acquireDatabase()\n\n\t\tapi.Use(func(c *gin.Context) {\n\t\t\tvar err error\n\n\t\t\terrCh := make(chan error)\n\t\t\tdbRequests <- dbRequest{acquiredb, errCh}\n\n\t\t\terr = <-errCh\n\t\t\tif err != nil {\n\t\t\t\tAbortWithJSONError(c, 500, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tdbRequests <- dbRequest{releasedb, errCh}\n\t\t\t\terr = <-errCh\n\t\t\t\tif err != nil {\n\t\t\t\t\tAbortWithJSONError(c, 500, err)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tc.Next()\n\t\t})\n\t}\n\n\t{\n\t\tif c.Config().EnableMetricsEndpoint {\n\t\t\tapi.GET(\"/metrics\", apiMetricsGet())\n\t\t}\n\t\tapi.GET(\"/version\", apiVersion)\n\n\t\tisReady := &atomic.Value{}\n\t\tisReady.Store(false)\n\t\tdefer isReady.Store(true)\n\t\tapi.GET(\"/ready\", apiReady(isReady))\n\t\tapi.GET(\"/healthy\", apiHealthy)\n\t}\n\n\t{\n\t\tapi.GET(\"/repos\", apiReposList)\n\t\tapi.POST(\"/repos\", apiReposCreate)\n\t\tapi.GET(\"/repos/:name\", apiReposShow)\n\t\tapi.PUT(\"/repos/:name\", apiReposEdit)\n\t\tapi.DELETE(\"/repos/:name\", apiReposDrop)\n\n\t\tapi.GET(\"/repos/:name/packages\", apiReposPackagesShow)\n\t\tapi.POST(\"/repos/:name/packages\", apiReposPackagesAdd)\n\t\tapi.DELETE(\"/repos/:name/packages\", apiReposPackagesDelete)\n\n\t\tapi.POST(\"/repos/:name/file/:dir/:file\", apiReposPackageFromFile)\n\t\tapi.POST(\"/repos/:name/file/:dir\", apiReposPackageFromDir)\n\n\t\tapi.POST(\"/repos/:name/include/:dir/:file\", apiReposIncludePackageFromFile)\n\t\tapi.POST(\"/repos/:name/include/:dir\", apiReposIncludePackageFromDir)\n\n\t\tapi.POST(\"/repos/:name/snapshots\", apiSnapshotsCreateFromRepository)\n\t}\n\n\t{\n\t\tapi.POST(\"/mirrors/:name/snapshots\", apiSnapshotsCreateFromMirror)\n\t}\n\n\t{\n\t\tapi.GET(\"/mirrors\", apiMirrorsList)\n\t\tapi.GET(\"/mirrors/:name\", apiMirrorsShow)\n\t\tapi.GET(\"/mirrors/:name/packages\", apiMirrorsPackages)\n\t\tapi.POST(\"/mirrors\", apiMirrorsCreate)\n\t\tapi.PUT(\"/mirrors/:name\", apiMirrorsUpdate)\n\t\tapi.DELETE(\"/mirrors/:name\", apiMirrorsDrop)\n\t}\n\n\t{\n\t\tapi.POST(\"/gpg/key\", apiGPGAddKey)\n\t}\n\n\t{\n\t\tapi.GET(\"/files\", apiFilesListDirs)\n\t\tapi.POST(\"/files/:dir\", apiFilesUpload)\n\t\tapi.GET(\"/files/:dir\", apiFilesListFiles)\n\t\tapi.DELETE(\"/files/:dir\", apiFilesDeleteDir)\n\t\tapi.DELETE(\"/files/:dir/:name\", apiFilesDeleteFile)\n\t}\n\n\t{\n\t\tapi.GET(\"/publish\", apiPublishList)\n\t\tapi.POST(\"/publish\", apiPublishRepoOrSnapshot)\n\t\tapi.POST(\"/publish/:prefix\", apiPublishRepoOrSnapshot)\n\t\tapi.PUT(\"/publish/:prefix/:distribution\", apiPublishUpdateSwitch)\n\t\tapi.DELETE(\"/publish/:prefix/:distribution\", apiPublishDrop)\n\t}\n\n\t{\n\t\tapi.GET(\"/snapshots\", apiSnapshotsList)\n\t\tapi.POST(\"/snapshots\", apiSnapshotsCreate)\n\t\tapi.PUT(\"/snapshots/:name\", apiSnapshotsUpdate)\n\t\tapi.GET(\"/snapshots/:name\", apiSnapshotsShow)\n\t\tapi.GET(\"/snapshots/:name/packages\", apiSnapshotsSearchPackages)\n\t\tapi.DELETE(\"/snapshots/:name\", apiSnapshotsDrop)\n\t\tapi.GET(\"/snapshots/:name/diff/:withSnapshot\", apiSnapshotsDiff)\n\t\tapi.POST(\"/snapshots/merge\", apiSnapshotsMerge)\n\t}\n\n\t{\n\t\tapi.GET(\"/packages/:key\", apiPackagesShow)\n\t\tapi.GET(\"/packages\", apiPackages)\n\t}\n\n\t{\n\t\tapi.GET(\"/graph.:ext\", apiGraph)\n\t}\n\t{\n\t\tapi.POST(\"/db/cleanup\", apiDbCleanup)\n\t}\n\t{\n\t\tapi.GET(\"/tasks\", apiTasksList)\n\t\tapi.POST(\"/tasks-clear\", apiTasksClear)\n\t\tapi.GET(\"/tasks-wait\", apiTasksWait)\n\t\tapi.GET(\"/tasks/:id/wait\", apiTasksWaitForTaskByID)\n\t\tapi.GET(\"/tasks/:id/output\", apiTasksOutputShow)\n\t\tapi.GET(\"/tasks/:id/detail\", apiTasksDetailShow)\n\t\tapi.GET(\"/tasks/:id/return_value\", apiTasksReturnValueShow)\n\t\tapi.GET(\"/tasks/:id\", apiTasksShow)\n\t\tapi.DELETE(\"/tasks/:id\", apiTasksDelete)\n\t\tapi.POST(\"/tasks-dummy\", apiTasksDummy)\n\t}\n\n\treturn router\n}", "func main() {\n\tr := gin.Default()\n\tr.Use(cors.Default())\n\tr.Use(parseRequestMiddleware())\n\n\tapi := r.Group(\"/v1\")\n\n\t// all results\n\tapi.POST(\"/all_results\", func(c *gin.Context) {\n\t\texecuteRequest(c, allResults)\n\t})\n\n\t// price group\n\tprice := api.Group(\"/price\")\n\t{\n\t\tprice.POST(\"/by_profit_rate\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getSellPriceByProfitRate)\n\t\t})\n\t}\n\n\t// fees group\n\tfees := api.Group(\"/fees\")\n\t{\n\t\tfees.POST(\"/total\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getFeesTotal)\n\t\t})\n\t\tfees.POST(\"/sales_tax\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getSalesTaxFeesTotal)\n\t\t})\n\t\tfees.POST(\"/payment\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getPaymentFeesTotal)\n\t\t})\n\t\tfees.POST(\"/channel\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getChannelFeesTotal)\n\t\t})\n\t\tfees.POST(\"/other\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getOtherFeesTotal)\n\t\t})\n\t}\n\n\t// profit group\n\tprofit := api.Group(\"/profit\")\n\t{\n\t\tprofit.POST(\"/total\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, getProfitTotal)\n\t\t})\n\t\tprofit.POST(\"/is_valid\", func(c *gin.Context) {\n\t\t\texecuteRequest(c, isValidProfitRate)\n\t\t})\n\t}\n\n\tr.Run(\":9096\")\n}", "func getSageBucketGeneric(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\n\tsageBucketID := vars[\"bucket\"]\n\tif len(sageBucketID) != 36 {\n\t\trespondJSONError(w, http.StatusInternalServerError, \"bucket id (%s) invalid (%d)\", sageBucketID, len(sageBucketID))\n\t\treturn\n\t}\n\n\tusername := vars[\"username\"]\n\n\t// r.URL.Path example: /api/v1/objects/6dd46856-c871-4089-b1bc-a12b44e92c81\n\n\t//pathArray := strings.SplitN(r.URL.Path, \"/\", 6)\n\n\t//keyPath := pathArray[5]\n\n\t_, sagePath, err := getSagePath(r.URL.Path)\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\n\t}\n\n\t// bucket permission\n\trawQuery := strings.ToLower(r.URL.RawQuery) // this is ugle, .Values() does not handle ?permissions as it has no value\n\n\t//log.Printf(\"rawQuery: %s\", rawQuery)\n\tif sagePath == \"\" && strings.Contains(rawQuery, \"permissions\") {\n\n\t\tallowed, err := userHasBucketPermission(username, sageBucketID, \"READ_ACP\")\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\t\tif !allowed {\n\t\t\trespondJSONError(w, http.StatusUnauthorized, \"Access to bucket permissions denied (%s, %s)\", username, sageBucketID)\n\t\t\treturn\n\t\t}\n\n\t\tpermissions, err := ListBucketPermissions(sageBucketID)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\trespondJSON(w, http.StatusOK, permissions)\n\t\treturn\n\n\t}\n\n\t// bucket of directory listing\n\n\tallowed, err := userHasBucketPermission(username, sageBucketID, \"READ\")\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\tif !allowed {\n\t\trespondJSONError(w, http.StatusUnauthorized, \"Read access to bucket denied (username: \\\"%s\\\", sageBucketID: \\\"%s\\\")\", username, sageBucketID)\n\t\treturn\n\t}\n\n\tif sagePath == \"\" {\n\t\t// bucket listing\n\t\tbucket, err := GetSageBucket(sageBucketID)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\trespondJSON(w, http.StatusOK, bucket)\n\t\treturn\n\t}\n\n\t// directory listing\n\tif strings.HasSuffix(sagePath, \"/\") {\n\n\t\t// _, sagePath, err := getSagePath(r.URL.Path)\n\t\t// if err != nil {\n\t\t// \trespondJSONError(w, http.StatusBadRequest, err.Error())\n\t\t// \treturn\n\n\t\t// }\n\n\t\trecursive := false\n\t\tif strings.Contains(rawQuery, \"recursive\") {\n\t\t\tif !strings.Contains(rawQuery, \"recursive=false\") {\n\t\t\t\trecursive = true\n\t\t\t}\n\n\t\t}\n\t\tcontinuationToken, err := getQueryField(r, \"ContinuationToken\")\n\t\tif err != nil {\n\t\t\tcontinuationToken = \"\"\n\t\t}\n\n\t\tlimit, err := getQueryFieldInt64(r, \"limit\", 0)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusInternalServerError, \"error parsing query field limit: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tif false {\n\t\t\tfiles, directories, newContinuationToken, err := listSageBucketContentDepreccated(sageBucketID, sagePath, recursive, 0, \"\", continuationToken)\n\n\t\t\tif err != nil {\n\t\t\t\trespondJSONError(w, http.StatusInternalServerError, \"error listing bucket contents (sageBucketID: %s, sagePath: %s): %s\", sageBucketID, sagePath, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfiles = append(files, directories...)\n\n\t\t\t// Repsonse has some similiarity to https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html#API_ListObjectsV2_ResponseSyntax\n\n\t\t\tdata := make(map[string]interface{})\n\t\t\tdata[\"Contents\"] = files\n\n\t\t\tif newContinuationToken != \"\" {\n\t\t\t\tdata[\"NextContinuationToken\"] = newContinuationToken\n\t\t\t\tdata[\"IsTruncated\"] = true\n\t\t\t} else {\n\t\t\t\tdata[\"IsTruncated\"] = false\n\t\t\t}\n\n\t\t\trespondJSON(w, http.StatusOK, data)\n\t\t}\n\n\t\tlistObject, err := listSageBucketContent(sageBucketID, sagePath, recursive, limit, \"\", continuationToken)\n\t\tif err != nil {\n\t\t\trespondJSONError(w, http.StatusInternalServerError, \"error listing bucket contents (sageBucketID: %s, sagePath: %s): %s\", sageBucketID, sagePath, err.Error())\n\t\t\treturn\n\t\t}\n\t\trespondJSON(w, http.StatusOK, listObject)\n\n\t\treturn\n\t}\n\n\t// a file download\n\n\t//uuidStr := vars[\"bucket\"]\n\t//sageKey := vars[\"key\"]\n\n\t// convert SAGE specifiers to S3 specifiers\n\t//sageBucketID := s3BucketPrefix + sageBucketID[0:2]\n\n\ts3BucketID := getS3BucketID(sageBucketID) //s3BucketPrefix + sageBucketID[0:2]\n\n\ts3key := path.Join(sageBucketID, sagePath)\n\n\tsageFilename := path.Base(sagePath)\n\tif sageFilename == \".\" || sageFilename == \"/\" {\n\t\trespondJSONError(w, http.StatusInternalServerError, \"Invalid filename (%s)\", sageFilename)\n\t\treturn\n\t}\n\n\tobjectInput := s3.GetObjectInput{\n\t\tBucket: &s3BucketID,\n\t\tKey: &s3key,\n\t}\n\n\tout, err := svc.GetObject(&objectInput)\n\tif err != nil {\n\t\trespondJSONError(w, http.StatusInternalServerError, \"Error getting data, svc.GetObject returned: %s\", err.Error())\n\t\treturn\n\t}\n\tdefer out.Body.Close()\n\n\tw.Header().Set(\"Content-Disposition\", \"attachment; filename=\"+sageFilename)\n\t//w.Header().Set(\"Content-Length\", FileSize)\n\n\tbuffer := make([]byte, 1024*1024)\n\tw.WriteHeader(http.StatusOK)\n\tfor {\n\t\tn, err := out.Body.Read(buffer)\n\t\tif err != nil {\n\n\t\t\tif err == io.EOF {\n\t\t\t\tw.Write(buffer[:n]) //should handle any remainding bytes.\n\t\t\t\tfileDownloadByteSize.Add(float64(n))\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\trespondJSONError(w, http.StatusInternalServerError, \"Error getting data: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tw.Write(buffer[0:n])\n\t\tfileDownloadByteSize.Add(float64(n))\n\t}\n\n\treturn\n}", "func (g *Gateway) bucketHandler(c *gin.Context) {\n\tlog.Debugf(\"host: %s\", c.Request.Host)\n\n\tbuckName, err := bucketFromHost(c.Request.Host, g.bucketDomain)\n\tif err != nil {\n\t\tabort(c, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), handlerTimeout)\n\tdefer cancel()\n\trep, err := g.client.ListBucketPath(ctx, \"\", buckName, g.clientAuth)\n\tif err != nil {\n\t\tabort(c, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tfor _, item := range rep.Item.Items {\n\t\tif item.Name == \"index.html\" {\n\t\t\tc.Writer.WriteHeader(http.StatusOK)\n\t\t\tc.Writer.Header().Set(\"Content-Type\", \"text/html\")\n\t\t\tpth := strings.Replace(item.Path, rep.Root.Path, rep.Root.Name, 1)\n\t\t\tif err := g.client.PullBucketPath(ctx, pth, c.Writer, g.clientAuth); err != nil {\n\t\t\t\tabort(c, http.StatusInternalServerError, err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\n\t// No index was found, use the default (404 for now)\n\tg.render404(c)\n}", "func Router(clientRedis *services.RedisClient, gateWayClient *services.GateWayClient) *mux.Router {\n\n\t//Routing\n\trouter := mux.NewRouter()\n\tsubRouter := router.PathPrefix(\"/api/v1/\").Subrouter()\n\t//Cart routes\n\tsubRouter.HandleFunc(\"/carts/{ID}\", HandleCartGet(clientRedis)).Methods(\"GET\")\n\tsubRouter.HandleFunc(\"/carts\", HandleCartPost(clientRedis, gateWayClient)).Methods(\"POST\")\n\tsubRouter.HandleFunc(\"/carts\", HandleCartPut(clientRedis, gateWayClient)).Methods(\"PUT\")\n\tsubRouter.HandleFunc(\"/carts/{ID}\", HandleCartDelete(clientRedis)).Methods(\"DELETE\")\n\t//CartElment routes\n\tsubRouter.HandleFunc(\"/carts/{customerID}/elements/{elementID}\", HandleCartElementGet(clientRedis)).Methods(\"GET\")\n\tsubRouter.HandleFunc(\"/carts/elements\", HandleCartElementPost(clientRedis, gateWayClient)).Methods(\"POST\")\n\tsubRouter.HandleFunc(\"/carts/elements\", HandleCartElementPut(clientRedis, gateWayClient)).Methods(\"PUT\")\n\tsubRouter.HandleFunc(\"/carts/{customerID}/elements/{elementID}\", HandleCartElementDelete(clientRedis)).Methods(\"DELETE\")\n\n\treturn router\n\n}", "func routePath(w http.ResponseWriter, r *http.Request, trimURL string) {\n\n\t/***********************************************/\n\t//TODO: add your custom web API here:\n\t/**********************************************/\n\n\tif strings.HasPrefix(trimURL, \"login\") && webServer.IsPOST(r) { //>>>>authentication\n\t\tauthenticateHandler.HandleHTTPLogin(w, r)\n\t} else if strings.HasPrefix(trimURL, \"logout\") && webServer.IsPOST(r) {\n\t\tauthenticateHandler.HandleHTTPLogout(w, r)\n\t} else if strings.Compare(trimURL, \"current-user\") == 0 && webServer.IsGET(r) {\n\t\tauthenticateHandler.HandleCurrentUser(w, r)\n\t} else if strings.Compare(trimURL, \"role\") == 0 && webServer.IsPOST(r) { //>>>>authorization\n\t\tauthorizeHandler.HandleAddRole(w, r)\n\t} else if strings.Compare(trimURL, \"role\") == 0 && webServer.IsGET(r) {\n\t\tauthorizeHandler.HandleGetRole(w, r)\n\t} else if strings.Compare(trimURL, \"role-access\") == 0 && webServer.IsGET(r) {\n\t\tauthorizeHandler.HandleGetAccessRole(w, r)\n\t} else if strings.Compare(trimURL, \"role-access-count\") == 0 && webServer.IsGET(r) {\n\t\tauthorizeHandler.HandleGetAccessRoleCount(w, r)\n\t} else if strings.Compare(trimURL, \"access\") == 0 && webServer.IsGET(r) {\n\t\tauthorizeHandler.HandleGetAccess(w, r)\n\t} else if strings.HasPrefix(trimURL, \"meals\") { //>>>>sample return JSON\n\t\tw.Header().Set(\"Content-Type\", \"application/json\") //MIME to application/json\n\t\tw.WriteHeader(http.StatusOK) //status code 200, OK\n\t\tw.Write([]byte(\"{ \\\"msg\\\": \\\"this is meal A \\\" }\")) //body text\n\t\treturn\n\t} else if strings.HasPrefix(trimURL, \"img/\") { //>>>>sample return virtual JPG file to client\n\t\tlogicalFilePath := \"./logic-files/\"\n\t\tphysicalFileName := \"neon.jpg\"\n\n\t\t// try read file\n\t\tdata, err := ioutil.ReadFile(logicalFilePath + physicalFileName)\n\t\tif err != nil {\n\t\t\t// show error page if failed to read file\n\t\t\thandleErrorCode(500, \"Unable to retrieve image file\", w)\n\t\t} else {\n\t\t\t//w.Header().Set(\"Content-Type\", \"image/jpg\") // #optional HTTP header info\n\n\t\t\t// uncomment if image file is meant to download instead of display on web browser\n\t\t\t// clientDisplayFileName = \"customName.jpg\"\n\t\t\t//w.header().Set(\"Content-Disposition\", \"attachment; filename=\\\"\" + clientDisplayFileName + \"\\\"\")\n\n\t\t\t// write file (in binary format) direct into HTTP return content\n\t\t\tw.Write(data)\n\t\t}\n\t} else {\n\t\t// show error code 404 not found\n\t\t//(since the requested URL doesn't match any of it)\n\t\thandleErrorCode(404, \"Path not found.\", w)\n\t}\n\n}", "func (mh *RootHandler) Handler(w http.ResponseWriter, r *http.Request) {\n ref := DatasetRefFromCtx(r.Context())\n if ref == nil {\n WebappHandler(w, r)\n return\n }\n if ref.IsPeerRef() {\n p := &core.PeerInfoParams{\n Peername: ref.Peername,\n }\n res := &profile.Profile{}\n err := mh.ph.Info(p, res)\n if err != nil {\n util.WriteErrResponse(w, http.StatusInternalServerError, err)\n return\n }\n if res.ID == \"\" {\n util.WriteErrResponse(w, http.StatusNotFound, errors.New(\"cannot find peer\"))\n return\n }\n util.WriteResponse(w, res)\n return\n }\n res := &repo.DatasetRef{}\n err := mh.dsh.Get(ref, res)\n if err != nil {\n util.WriteErrResponse(w, http.StatusInternalServerError, err)\n return\n }\n if res.Name == \"\" {\n util.WriteErrResponse(w, http.StatusNotFound, errors.New(\"cannot find peer dataset\"))\n return\n }\n if res == nil {\n util.WriteErrResponse(w, http.StatusNotFound, errors.New(\"cannot find peer dataset\"))\n return\n }\n util.WriteResponse(w, res)\n return\n}", "func ProvisioningHandler(c *gin.Context) {\n\treqBody, err := ioutil.ReadAll(c.Request.Body)\n\tif err != nil {\n\t\tlog.Panic(fmt.Sprintf(\"Unable to read request body %s\", err))\n\t}\n\n\tvar serviceInstance model.ServiceInstance\n\terr = json.Unmarshal(reqBody, &serviceInstance)\n\tif err != nil {\n\t\tlog.Panicf(\"Unable to unmarshal the request body: %s. Request body %s\", err, string(reqBody))\n\t}\n\n\tinstanceID := c.Param(\"instanceID\")\n\tvar planInfo = model.PlanID{}\n\terr = json.Unmarshal([]byte(serviceInstance.PlanID), &planInfo)\n\tif err != nil {\n\t\tlog.Panic(fmt.Sprintf(\"Unable to unmarshal PlanID: %s\", err))\n\t}\n\tserviceName := planInfo.LibsServiceName\n\n\tvolumeSize := int64(8)\n\tif serviceInstance.Parameters.SizeInGB != \"\" {\n\t\tvolumeSize, err = strconv.ParseInt(serviceInstance.Parameters.SizeInGB, 10, 64)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"Invalid SizeInGB %s\", serviceInstance.Parameters.SizeInGB)\n\t\t}\n\t}\n\n\tvolumeCreateRequest, err := utils.CreateVolumeRequest(instanceID, serviceInstance.Parameters.StoragePoolName, int64(volumeSize))\n\tif err != nil {\n\t\tlog.Panic(fmt.Sprintf(\"Unable to create volume request: %s.\", err))\n\t}\n\n\t_, err = libstoragewrapper.CreateVolume(NewLibsClient(), serviceName, volumeCreateRequest)\n\tif err != nil {\n\t\tlog.Panic(fmt.Sprintf(\"Unable to create volume %+v using libstorage: %s.\", volumeCreateRequest, err))\n\t}\n\n\tc.JSON(http.StatusCreated, gin.H{})\n}", "func pharosHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.String()\n\tif strings.Contains(url, \"/item_state/\") {\n\t\tif r.Method == http.MethodGet {\n\t\t\tworkItemStateGetHandler(w, r)\n\t\t} else {\n\t\t\tworkItemStatePutHandler(w, r)\n\t\t}\n\t} else if strings.Contains(url, \"/items/\") {\n\t\tif r.Method == http.MethodGet {\n\t\t\tworkItemGetHandler(w, r)\n\t\t} else if r.Method == http.MethodPut {\n\t\t\tworkItemPutHandler(w, r)\n\t\t} else if r.Method == http.MethodPost {\n\t\t\tworkItemPostHandler(w, r)\n\t\t}\n\n\t} else if strings.Contains(url, \"/objects/\") {\n\t\tintellectualObjectGetHandler(w, r)\n\t} else if strings.Contains(url, \"/institutions/\") {\n\t\tinstitutionListHandler(w, r)\n\t} else if strings.Contains(url, \"/files/\") {\n\t\tgenericFileGetHandler(w, r)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"Don't know how to handle request for %s\", url))\n\t}\n}", "func innerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\n\t//group := e.Group(\"/openplatform/internal/anti/fraud\",idfSvc.Verify)\n\tgroup := e.Group(\"/openplatform/internal/antifraud\")\n\t{\n\n\t\tgroup.GET(\"/qusb/info\", qusBankInfo) //题库单条信息\n\t\tgroup.GET(\"/qusb/list\", qusBankList) //题库列表\n\t\tgroup.POST(\"/qusb/add\", qusBankAdd) //题库添加\n\t\tgroup.POST(\"/qusb/del\", qusBankDel) //题库删除\n\t\tgroup.POST(\"/qusb/update\", qusBankEdit) //题库修改\n\t\tgroup.POST(\"/qusb/check\", qusBankCheck) // 答题\n\n\t\tgroup.GET(\"/qs/info\", qusInfo) //题目信息\n\t\tgroup.GET(\"/qs/list\", qusList) //题目列表\n\t\tgroup.POST(\"/qs/add\", qusAdd) //题目添加\n\t\tgroup.POST(\"/qs/update\", qusUpdate) //题目更新\n\t\tgroup.POST(\"/qs/del\", qusDel) //题目删除\n\t\tgroup.GET(\"/qs/get\", getQuestion) //题目获取\n\t\tgroup.POST(\"/qs/answer\", answerQuestion) // 答题\n\n\t\tgroup.POST(\"/bind\", questionBankBind) // 绑定题库\n\t\tgroup.POST(\"/unbind\", questionBankUnbind) // 解绑题库\n\t\tgroup.POST(\"/bind/bank\", getBankBind) // 查询已绑定的题库\n\t\tgroup.GET(\"/bind/items\", getBindItems) // 查询绑定到题库的 items\n\n\t\tgroup.GET(\"/risk/check\", riskCheck) //风险检验\n\t\tgroup.POST(\"/risk/check/v2\", riskCheckV2) //风险检验v2\n\t\tgroup.GET(\"/graph/prepare\", graphPrepare) //拉起图形验证\n\t\tgroup.POST(\"/graph/check\", graphCheck) //图形验证\n\t}\n\n\tgroup2 := e.Group(\"/openplatform/admin/antifraud/shield\")\n\t{\n\t\tgroup2.GET(\"/risk/ip/list\", ipList) //ip列表\n\t\tgroup2.GET(\"/risk/ip/detail\", ipDetail) //ip详情列表\n\t\tgroup2.GET(\"/risk/uid/list\", uidList) //uid列表\n\t\tgroup2.GET(\"/risk/uid/detail\", uidDetail) //uid详情列表\n\t\tgroup2.POST(\"/risk/ip/black\", ipBlack) //设置ip黑名单\n\t\tgroup2.POST(\"/risk/uid/black\", uidBlack) //设置uid黑名单\n\n\t}\n}", "func Routes(r *gin.Engine) {\n\n\tv1 := r.Group(\"/v1\")\n\t{\n\t\t//// rutas publicas\n\t\tv1.GET(\"/testv1\", users.ServiceTest)\n\t\tv1.POST(\"/register\", users.Register)\n\t\tv1.POST(\"/login\", auth.HandleLogin)\n\t}\n\t//// rutas privadas\n\tv1.Use(middlewares.AuthHandler(\"\"))\n\t{\n\t\t// Companies\n\t\tcompaniesGroup := v1.Group(\"companies\")\n\t\tcompaniesGroup.GET(\"/\", company.GetAll)\n\t\tcompaniesGroup.POST(\"/create\", company.CreateNewCompany)\n\t\tcompaniesGroup.PUT(\"/changeStatus\", company.ChangeStatusCompany)\n\t\tcompaniesGroup.DELETE(\"/deleteCompany/:id\", company.DeleteCompany)\n\n\t\tcompaniesGroup.GET(\"/myCompany\", company.MyCompany)\n\t\tcompaniesGroup.GET(\"/myWorkShop\", company.MyWorkShop)\n\n\t\t// // Mechanic\n\t\tworkshops := v1.Group(\"workshop\")\n\t\tworkshops.GET(\"/\", workshop.Get)\n\t\tworkshops.GET(\"/search/:workshopID\", workshop.GetByID)\n\t\tworkshops.GET(\"/all\", workshop.GetAll)\n\t\tworkshops.POST(\"/create\", workshop.Create)\n\n\t\t// Mechanic\n\t\tmechanicGroup := v1.Group(\"mechanic\")\n\t\tmechanicGroup.POST(\"/create\", mechanic.Create)\n\t\tmechanicGroup.GET(\"/\", mechanic.Get)\n\t\tmechanicGroup.GET(\"/myMechanics\", mechanic.MyMechanics)\n\n\t\t// routines\n\t\troutine := v1.Group(\"routines\")\n\t\troutine.GET(\"\", routines.Get)\n\t\troutine.GET(\"/byWorkshop\", routines.GetByWorkshop)\n\t\troutine.GET(\"/byWorkshopID/:workshopID\", routines.GetByWorkshopID)\n\n\t\troutine.POST(\"/addRoutineByWorkshop\", routines.AddRoutineByWorkshop)\n\t\troutine.GET(\"/getTreatingMechanic/:workshopID/:vehicleID\", routines.GetTreatingMechanic)\n\n\t\tappointments := v1.Group(\"appointments\")\n\t\tappointments.GET(\"/\", appointment.GetAppointments)\n\n\t\t// users\n\t\tuser := v1.Group(\"user\")\n\t\tuser.GET(\"/\", users.GetDataUser)\n\t\tuser.GET(\"/myWorkShop\", users.GetDataWorkShopData)\n\t\tuser.PUT(\"/reset\", users.ResetPassword)\n\n\t\t// brands\n\t\tbrand := v1.Group(\"brands\")\n\t\tbrand.GET(\"\", brands.GetAll)\n\n\t\t// brands\n\t\tvehicle := v1.Group(\"vehicles\")\n\t\tvehicle.GET(\"\", vehicles.GetAllVehicles)\n\t\tvehicle.POST(\"\", vehicles.Create)\n\n\t}\n}", "func home(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tlog.Info(\"Request received.\")\n\tfmt.Fprintf(w, \"Processing URL %s...\\n\", r.URL.Path)\n}", "func paymentRequired(rw http.ResponseWriter, r *http.Request) {\n\n}", "func handleRequests() {\n r := mux.NewRouter()\n\n // Paths\n r.HandleFunc(\"/mine\", mineBlockHandler).Methods(\"POST\")\n r.HandleFunc(\"/{index}\", getBlockHandler)\n r.HandleFunc(\"/\", getBlockchainHandler)\n\n // Run the server\n port := \":10000\"\n fmt.Println(\"\\nListening on port \" + port[1:])\n log.Fatal(http.ListenAndServe(port, r))\n}", "func GasPrice(log logger.Logger) http.Handler {\n\t// build the handler function\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// get the gas price estimation\n\t\tval, err := repository.R().GasPriceExtended()\n\t\tif err != nil {\n\t\t\tlog.Critical(\"can not get gas price; %s\", err.Error())\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t// respond\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\terr = json.NewEncoder(w).Encode(val)\n\t\tif err != nil {\n\t\t\tlog.Critical(\"can not encode gas price structure; %s\", err.Error())\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t})\n}", "func main() {\n\tcfg := loadConfig()\n\tr := mux.NewRouter()\n\tdbCtrl, er := ctrl.CreateWalletMgrCluster(cfg.Db.User, cfg.Db.Password, cfg.Db.Name, cfg.Db.Addr, cfg.Db.DbPoolSize)\n\tif er != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Error: %v\", er.Error()))\n\t}\n\n\ts := accmamaging.CreateService(dbCtrl)\n\tr.Handle(\"/accmamaging/add/\", accmamaging.MakeHandler(s)).Methods(\"PUT\")\n\n\tb := browsing.CreateService(dbCtrl)\n\tr.Handle(\"/browsing/accounts\", browsing.MakeGetAccountsHandler(b)).Methods(\"GET\")\n\tr.Handle(\"/browsing/payments\", browsing.MakeGetPaymentsHandler(b)).Methods(\"GET\")\n\n\tp := payment.CreateService(dbCtrl)\n\tr.Handle(\"/payment/change_balance\", payment.MakeChangeBalanceHandler(p)).Methods(\"PUT\")\n\tr.Handle(\"/payment/send_money\", payment.MakeSendMoneyHandler(p)).Methods(\"PUT\")\n\n\thttp.Handle(\"/\", r)\n\taddress := cfg.Addr\n\tlog.Printf(\"Start listen: %v\", address)\n\tlog.Fatal(http.ListenAndServe(address, nil))\n}", "func LBRetrieveHandler(c interface{}, r *http.Request) service.Response {\n\tconfig := c.(*Config)\n\n\tvars := mux.Vars(r)\n\tlbID := vars[\"lb_id\"]\n\tdaolb, err := config.DBSession.LoadLoadBalancer(lbID)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"could not retrieve load balancer\")\n\t\treturn service.Response{Body: err, Status: 404}\n\t}\n\n\tlb := NewLoadBalancerFromDAO(*daolb, config.BaseDomain)\n\n\tagents, err := config.DBSession.LoadBalancerAgents(lbID)\n\tif err != nil {\n\t\tlogrus.WithError(err).Error(\"could not retrieve load balancer agents\")\n\t\treturn service.Response{Body: err, Status: 404}\n\t}\n\n\tfor _, a := range agents {\n\t\tlb.Agents = append(lb.Agents, NewAgentFromDAO(a))\n\t}\n\n\treturn service.Response{Body: lb, Status: http.StatusOK}\n}", "func main() {\n\tr := mux.NewRouter()\n\theaders := handlers.AllowedHeaders([]string{\"X-Requested-With\", \"Content-Type\", \"Authorization\"})\n\tmethods := handlers.AllowedMethods([]string{\"GET\", \"POST\", \"PUT\", \"HEAD\", \"OPTIONS\"})\n\torigins := handlers.AllowedOrigins([]string{\"*\"})\n\n\tr.HandleFunc(\"/assets\", get_list_assets).Methods(\"GET\")\n\tr.HandleFunc(\"/assets\", post_asset).Methods(\"POST\")\n\n\tr.HandleFunc(\"/coins\", get_list_coins).Methods(\"GET\")\n\tr.HandleFunc(\"/coins\", post_coin).Methods(\"POST\")\n\n\tif err := http.ListenAndServe(\":5555\", handlers.CORS(headers, methods, origins)(r)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}", "func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {\n\tpath := strings.ToLower(req.URL.Path)\n\tif strings.Compare(path, \"/aggregated/caseworkers/:uid/jurisdictions\") == 0 {\n\t\tfirst := fetchJsonArray(CcdHost, req)\n\t\tsecond := fetchJsonArray(IndependentHost, req)\n\t\tresult := append(first, second...)\n\t\tjson.NewEncoder(res).Encode(result)\n\t\treturn\n\t}\n\n\tif strings.Compare(path, \"/health\") == 0 {\n\t\tfmt.Fprintf(res, \"OK\")\n\t\treturn\n\t}\n\n\tif isIndie(req.URL) {\n\t\tserveReverseProxy(\"http://\" + IndependentHost, res, req)\n\t\treturn\n\t}\n\n\tserveReverseProxy(\"http://\" + CcdHost, res, req)\n}", "func (h *Handler) handleRequests() {\n\thttp.HandleFunc(\"/\", homePage)\n\thttp.HandleFunc(\"/customers\", h.returnAllCustomers)\n\tlog.Fatal(http.ListenAndServe(frontendPort, nil))\n}", "func HandlePub(r *gin.RouterGroup) {\n\tr.POST(\"/\", users.HandleRegister)\n}", "func handleTransfers(rw http.ResponseWriter, req *http.Request) {\n\n\tif req.URL.Path != \"/transfers\" {\n\t\trespondWithError(rw, invalidURLError)\n\t\treturn\n\t}\n\n\tif req.Method != http.MethodGet && req.Method != http.MethodPost {\n\t\trespondWithError(rw, invalidMethodError)\n\t\treturn\n\t}\n\n\ttoken := req.Header.Get(\"Authorization\")\n\n\tif token == \"\" {\n\t\trespondWithError(rw, noTokenError)\n\t\treturn\n\t}\n\n\tid, err := getUserByToken(token, true)\n\n\tif err != nil {\n\t\trespondWithError(rw, err)\n\t\treturn\n\t}\n\n\tif req.Method == http.MethodPost {\n\t\tdoTransfer(rw, req, id)\n\t} else if req.Method == http.MethodGet {\n\t\tgetTransfers(rw, req, id)\n\t} else {\n\t\trespondWithError(rw, invalidMethodError)\n\t}\n}", "func (g *Group) POST(path string, h Handler, gases ...Gas) {\n\tg.Air.POST(g.Prefix+path, h, append(g.Gases, gases...)...)\n}", "func (h *HandlersAdmin) JSONCarvesHandler(w http.ResponseWriter, r *http.Request) {\n\th.Inc(metricJSONReq)\n\tutils.DebugHTTPDump(r, h.Settings.DebugHTTP(settings.ServiceAdmin, settings.NoEnvironment), false)\n\t// Get context data\n\tctx := r.Context().Value(sessions.ContextKey(\"session\")).(sessions.ContextValue)\n\t// Check permissions\n\tif !h.Users.CheckPermissions(ctx[sessions.CtxUser], users.CarveLevel, users.NoEnvironment) {\n\t\tlog.Printf(\"%s has insuficient permissions\", ctx[sessions.CtxUser])\n\t\th.Inc(metricJSONErr)\n\t\treturn\n\t}\n\tvars := mux.Vars(r)\n\t// Extract environment\n\tenvVar, ok := vars[\"env\"]\n\tif !ok {\n\t\tlog.Println(\"environment is missing\")\n\t\th.Inc(metricJSONErr)\n\t\treturn\n\t}\n\t// Get environment\n\tenv, err := h.Envs.Get(envVar)\n\tif err != nil {\n\t\tlog.Printf(\"error getting environment %s - %v\", envVar, err)\n\t\th.Inc(metricJSONErr)\n\t\treturn\n\t}\n\t// Extract target\n\ttarget, ok := vars[\"target\"]\n\tif !ok {\n\t\th.Inc(metricJSONErr)\n\t\tlog.Println(\"error getting target\")\n\t\treturn\n\t}\n\t// Verify target\n\tif !CarvesTargets[target] {\n\t\th.Inc(metricJSONErr)\n\t\tlog.Printf(\"invalid target %s\", target)\n\t\treturn\n\t}\n\t// Retrieve carves for that target\n\tqs, err := h.Queries.GetCarves(target, env.ID)\n\tif err != nil {\n\t\th.Inc(metricJSONErr)\n\t\tlog.Printf(\"error getting query carves %v\", err)\n\t\treturn\n\t}\n\t// Prepare data to be returned\n\tcJSON := []CarveJSON{}\n\tfor _, q := range qs {\n\t\tc, err := h.Carves.GetByQuery(q.Name, env.ID)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting carves %v\", err)\n\t\t\th.Inc(metricJSONErr)\n\t\t\tcontinue\n\t\t}\n\t\tstatus := queries.StatusActive\n\t\tif len(c) > 0 {\n\t\t\tstatus = carves.StatusQueried\n\t\t}\n\t\tif q.Completed {\n\t\t\tstatus = queries.StatusComplete\n\t\t}\n\t\tprogress := make(CarveProgress)\n\t\tprogress[\"expected\"] = q.Expected\n\t\tprogress[\"executions\"] = q.Executions\n\t\tprogress[\"errors\"] = q.Errors\n\t\tdata := make(CarveData)\n\t\tdata[\"path\"] = q.Path\n\t\tdata[\"name\"] = q.Name\n\t\t// Preparing query targets\n\t\tts, _ := h.Queries.GetTargets(q.Name)\n\t\t_ts := []CarveTarget{}\n\t\tfor _, t := range ts {\n\t\t\t_t := CarveTarget{\n\t\t\t\tType: t.Type,\n\t\t\t\tValue: t.Value,\n\t\t\t}\n\t\t\t_ts = append(_ts, _t)\n\t\t}\n\t\t// Preparing JSON\n\t\t_c := CarveJSON{\n\t\t\tName: q.Name,\n\t\t\tCreator: q.Creator,\n\t\t\tPath: data,\n\t\t\tCreated: CreationTimes{\n\t\t\t\tDisplay: utils.PastFutureTimes(q.CreatedAt),\n\t\t\t\tTimestamp: utils.TimeTimestamp(q.CreatedAt),\n\t\t\t},\n\t\t\tStatus: status,\n\t\t\tProgress: progress,\n\t\t\tTargets: _ts,\n\t\t}\n\t\tcJSON = append(cJSON, _c)\n\t}\n\treturned := ReturnedCarves{\n\t\tData: cJSON,\n\t}\n\t// Serve JSON\n\tutils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)\n\th.Inc(metricJSONOK)\n}", "func restAPI(keyCollection *ED25519Keys) {\n\n\t// CORS\n\tcorsAllowedHeaders := []string{\n\t\t\"Access-Control-Allow-Headers\",\n\t\t\"Access-Control-Allow-Methods\",\n\t\t\"Access-Control-Allow-Origin\",\n\t\t\"Cache-Control\",\n\t\t\"Content-Security-Policy\",\n\t\t\"Feature-Policy\",\n\t\t\"Referrer-Policy\",\n\t\t\"X-Requested-With\"}\n\n\tcorsOrigins := []string{\n\t\t\"*\",\n\t\t\"127.0.0.1\"}\n\n\tcorsMethods := []string{\n\t\t\"GET\",\n\t\t\"HEAD\",\n\t\t\"POST\",\n\t\t\"PUT\",\n\t\t\"OPTIONS\"}\n\n\theadersCORS := handlers.AllowedHeaders(corsAllowedHeaders)\n\toriginsCORS := handlers.AllowedOrigins(corsOrigins)\n\tmethodsCORS := handlers.AllowedMethods(corsMethods)\n\n\t// Init API\n\tr := mux.NewRouter()\n\tapi := r.PathPrefix(\"/api/v1\").Subrouter()\n\n\t// Home\n\tapi.HandleFunc(\"/\", home).Methods(http.MethodGet)\n\n\t// Version\n\tapi.HandleFunc(\"/version\", returnVersion).Methods(http.MethodGet)\n\n\t// Stats\n\tapi.HandleFunc(\"/stats\", func(w http.ResponseWriter, r *http.Request) {\n\t\treturnStatsWeb(w, r, keyCollection)\n\t}).Methods(http.MethodGet)\n\n\t// Transaction by ID\n\tapi.HandleFunc(\"/transaction/{hash}\", func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\thash := vars[\"hash\"]\n\t\treturnSingleTransaction(w, r, hash)\n\t}).Methods(http.MethodGet)\n\n\t// Transaction by qty\n\tapi.HandleFunc(\"/transactions/{number}\", func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\tnumber := vars[\"number\"]\n\t\treturnNTransactions(w, r, number)\n\t}).Methods(http.MethodGet)\n\n\t// Channel Socket\n\tapi.HandleFunc(\"/channel\", func(w http.ResponseWriter, r *http.Request) {\n\t\tupgrader.CheckOrigin = func(r *http.Request) bool { return true }\n\t\tconn, _ := upgrader.Upgrade(w, r, nil)\n\t\tdefer conn.Close()\n\t\t// fmt.Printf(brightgreen+\"\\n[%s] [%s] Peer socket opened!\"+white, timeStamp(), conn.RemoteAddr())\n\t\tsocketAuthAgent(conn, keyCollection)\n\t})\n\n\t// Serve via HTTP\n\thttp.ListenAndServe(\":\"+strconv.Itoa(karaiAPIPort), handlers.CORS(headersCORS, originsCORS, methodsCORS)(api))\n}", "func outerRouter(e *bm.Engine) {\n\te.GET(\"/monitor/ping\", ping)\n\tg := e.Group(\"/x/web\", authSvc.UserWeb)\n\t{\n\t\twebDanmuRouter(g)\n\t\tacademyRouter(g)\n\t\tstaffRouter(g)\n\t\tswitchRouter(g)\n\t\twebElecRouter(g)\n\t\twebAssistRouter(g)\n\t\tnewcomerRouter(g)\n\t\tg.GET(\"/ugcpay/protocol\", webUgcPayProtocol)\n\t\t// mission\n\t\tg.GET(\"/mission/protocol\", webMissionProtocol)\n\t\t// netsafe\n\t\tg.POST(\"/ns/md5\", webNsMd5)\n\t\t//white\n\t\tg.GET(\"/white\", webWhite)\n\t\t// archive.\n\t\tg.GET(\"/archive/parts\", webArchVideos)\n\t\tg.GET(\"/archive/view\", webViewArc)\n\t\tg.GET(\"/archives\", webArchives)\n\t\tg.GET(\"/archive/staff/applies\", webStaffApplies)\n\t\tg.GET(\"/archive/pre\", webViewPre)\n\t\tg.GET(\"/archive/videos\", webVideos)\n\t\tg.POST(\"/archive/delete\", webDelArc)\n\t\tg.GET(\"/archive/tags\", webTags)\n\t\tg.GET(\"/archive/desc/format\", webDescFormat)\n\t\t// history\n\t\tg.GET(\"/archive/history/list\", webHistoryList)\n\t\tg.GET(\"/archive/history/view\", webHistoryView)\n\t\t// ad\n\t\tg.GET(\"/ad/game/list\", webAdGameList)\n\t\t// appeal.\n\t\tg.GET(\"/appeal/list\", webAppealList)\n\t\tg.GET(\"/appeal/detail\", webAppealDetail)\n\t\tg.GET(\"/appeal/contact\", webAppealContact)\n\t\tg.POST(\"/appeal/add\", webAppealAdd)\n\t\tg.POST(\"/appeal/reply\", antispamSvc.ServeHTTP, webAppealReply)\n\t\tg.POST(\"/appeal/down\", webAppealDown)\n\t\tg.POST(\"/appeal/star\", webAppealStar)\n\t\t// cover list.\n\t\tg.GET(\"/archive/covers\", coverList)\n\t\tg.GET(\"/archive/recovers\", webRecommandCover)\n\t\t// index.\n\t\tg.GET(\"/index/stat\", webIndexStat)\n\t\tg.GET(\"/index/tool\", webIndexTool)\n\t\tg.GET(\"/index/full\", webIndexFull) //collect_arc\n\t\tg.GET(\"/index/notify\", webIndexNotify)\n\t\tg.GET(\"/index/operation\", webIndexOper)\n\t\tg.GET(\"/index/version\", webIndexVersion)\n\t\tg.GET(\"/index/newcomer\", webIndexNewcomer)\n\t\t// data\n\t\tg.GET(\"/data/videoquit\", webVideoQuitPoints)\n\t\tg.GET(\"/data/archive\", webArchive)\n\t\tg.GET(\"/data/article\", webArticleData)\n\t\tg.GET(\"/data/base\", base)\n\t\tg.GET(\"/data/trend\", trend)\n\t\tg.GET(\"/data/action\", action)\n\t\tg.GET(\"/data/survey\", survey)\n\t\tg.GET(\"/data/pandect\", pandect)\n\t\tg.GET(\"/data/fan\", webFan)\n\t\tg.GET(\"/data/playsource\", webPlaySource)\n\t\tg.GET(\"/data/playanalysis\", webArcPlayAnalysis)\n\t\tg.GET(\"/data/article/thirty\", webArtThirtyDay)\n\t\tg.GET(\"/data/article/rank\", webArtRank)\n\t\tg.GET(\"/data/article/source\", webArtReadAnalysis)\n\t\t// water mark\n\t\tg.GET(\"/watermark\", waterMark)\n\t\tg.POST(\"/watermark/set\", waterMarkSet)\n\t\t// feedback\n\t\tg.GET(\"/feedbacks\", webFeedbacks)\n\t\tg.GET(\"/feedback/detail\", webFeedbackDetail)\n\t\tg.GET(\"/feedback/tags\", webFeedbackTags)\n\t\tg.GET(\"/feedback/newtags\", webFeedbackNewTags)\n\t\tg.POST(\"/feedback/add\", webFeedbackAdd)\n\t\tg.POST(\"/feedback/close\", webFeedbackClose)\n\t\t// reply\n\t\tg.GET(\"/replies\", replyList)\n\t\t// template.\n\t\tg.GET(\"/tpls\", webTemplates)\n\t\tg.POST(\"/tpl/add\", webAddTpl)\n\t\tg.POST(\"/tpl/update\", webUpdateTpl)\n\t\tg.POST(\"/tpl/delete\", webDelTpl)\n\t\t// fans medal\n\t\tg.GET(\"/medal/status\", webMedalStatus)\n\t\tg.GET(\"/medal/recent\", webRecentFans)\n\t\tg.POST(\"/medal/open\", webMedalOpen)\n\t\tg.POST(\"/medal/check\", webMedalCheck)\n\t\tg.GET(\"/medal/rank\", webMedalRank)\n\t\tg.POST(\"/medal/rename\", webMedalRename)\n\t\tg.GET(\"/medal/fans\", webFansMedal)\n\t\t// article.\n\t\tg.GET(\"/article/author\", webAuthor)\n\t\tg.GET(\"/article/view\", webArticle)\n\t\tg.GET(\"/article/list\", webArticleList)\n\t\tg.GET(\"/article/pre\", webArticlePre)\n\t\tg.POST(\"/article/submit\", webSubArticle)\n\t\tg.POST(\"/article/update\", webUpdateArticle)\n\t\tg.POST(\"/article/delete\", webDelArticle)\n\t\tg.POST(\"/article/withdraw\", webWithDrawArticle)\n\t\tg.POST(\"/article/upcover\", antispamSvc.ServeHTTP, webArticleUpCover)\n\t\tg.GET(\"/draft/view\", webDraft)\n\t\tg.GET(\"/draft/list\", webDraftList)\n\t\tg.POST(\"/draft/addupdate\", webSubmitDraft)\n\t\tg.POST(\"/draft/delete\", webDeleteDraft)\n\t\tg.POST(\"/article/capture\", antispamSvc.ServeHTTP, webArticleCapture)\n\t\t// cm\n\t\tg.GET(\"/cm/oasis/stat\", webCmOasisStat)\n\t\t// common\n\t\tg.GET(\"/user/mid\", webUserMid)\n\t\tg.GET(\"/user/search\", webUserSearch)\n\t\t//viewpoint\n\t\tg.GET(\"/viewpoints\", webViewPoints)\n\t\t//g.POST(\"/viewpoints/edit\", webViewPointsEdit)\n\t}\n\th5 := e.Group(\"/x/h5\")\n\t{\n\t\t// app h5 cooperate pager\n\t\th5.GET(\"/cooperate/pre\", authSvc.User, appCooperatePre)\n\t\t// bgm\n\t\th5.GET(\"/bgm/ext\", authSvc.User, appBgmExt)\n\t\t// faq\n\t\th5.GET(\"/faq/editor\", authSvc.User, appH5FaqEditor)\n\t\th5.POST(\"/bgm/feedback\", authSvc.User, appH5BgmFeedback)\n\t\th5.GET(\"/elec/bill\", authSvc.User, appElecBill)\n\t\th5.GET(\"/elec/rank/recent\", authSvc.User, appElecRecentRank)\n\t\th5.GET(\"/medal/status\", authSvc.User, appMedalStatus)\n\t\th5.POST(\"/medal/check\", authSvc.User, appMedalCheck)\n\t\th5.POST(\"/medal/open\", authSvc.User, appMedalOpen)\n\t\th5.POST(\"/medal/rename\", authSvc.User, appMedalRename)\n\t\t//academy\n\t\th5.POST(\"/academy/play/add\", authSvc.Guest, h5AddPlay) //添加播放\n\t\th5.POST(\"/academy/play/del\", authSvc.Guest, h5DelPlay) //删除播放\n\t\th5.GET(\"/academy/play/list\", authSvc.User, h5PlayList) //我的课程\n\t\th5.GET(\"/academy/play/view\", authSvc.User, h5ViewPlay) //查看我的课程\n\t\th5.GET(\"/academy/theme/dir\", h5ThemeDir) //主题课程目录 对应职业列表\n\t\th5.GET(\"/academy/newb/course\", h5NewbCourse) //新人课程\n\t\th5.GET(\"/academy/tag\", h5Tags) //标签目录\n\t\th5.GET(\"/academy/archive\", h5Archive) //课程列表\n\t\th5.GET(\"/academy/feature\", h5Feature) //精选课程\n\t\th5.GET(\"/academy/recommend/v2\", authSvc.Guest, h5RecommendV2) //推荐课程v2\n\t\th5.GET(\"/academy/theme/course/v2\", h5ThemeCousreV2) //技能树(主题课程)v2\n\t\th5.GET(\"/academy/keywords\", h5Keywords) //搜索关键词提示\n\t\t// data center\n\t\th5.GET(\"/data/archive\", authSvc.User, appDataArc)\n\t\th5.GET(\"/data/videoquit\", authSvc.User, appDataVideoQuit)\n\t\th5.GET(\"/data/fan\", authSvc.User, appFan) //粉丝用户信息分析总览\n\t\th5.GET(\"/data/fan/rank\", authSvc.User, appFanRank) //新粉丝排行榜\n\t\th5.GET(\"/data/overview\", authSvc.User, appOverView) //新数据概览\n\t\th5.GET(\"/data/archive/analyze\", authSvc.User, appArchiveAnalyze) //新稿件数据分析\n\t\th5.GET(\"/data/video/retention\", authSvc.User, appVideoRetention) //新视频播放完成度\n\t\th5.GET(\"/data/article\", authSvc.User, appDataArticle)\n\t\th5.GET(\"/archives/simple\", authSvc.User, appSimpleArcVideos)\n\t\t// watermark\n\t\th5.GET(\"/watermark\", authSvc.User, waterMark)\n\t\th5.POST(\"/watermark/set\", authSvc.User, waterMarkSet)\n\t\t// up weekly honor\n\t\th5.GET(\"/weeklyhonor\", authSvc.Guest, weeklyHonor)\n\t\t// switch weekly honor subscribe\n\t\th5.POST(\"/weeklyhonor/subscribe\", authSvc.User, weeklyHonorSubSwitch)\n\t\t// task system\n\t\th5.POST(\"/task/bind\", authSvc.User, h5TaskBind)\n\t\th5.GET(\"/task/list\", authSvc.User, h5TaskList)\n\t\th5.POST(\"/task/reward/receive\", authSvc.User, h5RewardReceive)\n\t\th5.POST(\"/task/reward/activate\", authSvc.User, h5RewardActivate)\n\t\th5.GET(\"/task/reward/list\", authSvc.User, h5RewardReceiveList)\n\t\th5.GET(\"/task/pub/list\", authSvc.User, taskPubList) //其他业务方查看任务列表\n\t}\n\tapp := e.Group(\"/x/app\")\n\t{\n\t\tappDanmuRouter(app)\n\t\t// h5\n\t\tapp.GET(\"/h5/pre\", authSvc.User, appH5Pre)\n\t\tapp.GET(\"/h5/mission/type\", authSvc.User, appH5MissionByType)\n\t\tapp.GET(\"/h5/archive/tags\", authSvc.User, appH5ArcTags)\n\t\tapp.GET(\"/h5/archive/tag/info\", authSvc.User, appH5ArcTagInfo)\n\t\tapp.GET(\"/banner\", authSvc.User, appBanner)\n\t\t// archive\n\t\tapp.GET(\"/mission/type\", authSvc.UserMobile, appMissionByType)\n\t\tapp.GET(\"/index\", authSvc.User, appIndex)\n\t\tapp.GET(\"/archives\", authSvc.UserMobile, appArchives)\n\t\tapp.GET(\"/archives/simple\", authSvc.UserMobile, appSimpleArcVideos)\n\t\tapp.GET(\"/up/info\", authSvc.UserMobile, appUpInfo)\n\t\t// main app features\n\t\tapp.GET(\"/pre\", authSvc.User, appPre)\n\t\tapp.GET(\"/archive/pre\", authSvc.User, appArchivePre)\n\t\tapp.GET(\"/archive/desc/format\", authSvc.UserMobile, appArcDescFormat)\n\t\tapp.GET(\"/archive/view\", authSvc.UserMobile, appArcView)\n\t\tapp.POST(\"/archive/delete\", authSvc.UserMobile, appArcDel)\n\t\t// reply.\n\t\tapp.GET(\"/replies\", authSvc.UserMobile, appReplyList)\n\t\t// data\n\t\tapp.GET(\"/data/archive\", authSvc.UserMobile, appDataArc)\n\t\tapp.GET(\"/data/videoquit\", authSvc.UserMobile, appDataVideoQuit)\n\t\tapp.GET(\"/data/fan\", authSvc.UserMobile, appFan)\n\t\tapp.GET(\"/data/fan/rank\", authSvc.UserMobile, appFanRank) //新粉丝排行榜\n\t\tapp.GET(\"/data/overview\", authSvc.UserMobile, appOverView) //新数据概览\n\t\tapp.GET(\"/data/archive/analyze\", authSvc.UserMobile, appArchiveAnalyze) //新稿件数据分析\n\t\tapp.GET(\"/data/video/retention\", authSvc.UserMobile, appVideoRetention) //新视频播放完成度\n\t\tapp.GET(\"/data/article\", authSvc.UserMobile, appDataArticle)\n\t\t// elec\n\t\tapp.GET(\"/elec/bill\", authSvc.UserMobile, appElecBill)\n\t\tapp.GET(\"/elec/rank/recent\", authSvc.UserMobile, appElecRecentRank)\n\t\t// fans medal\n\t\tapp.GET(\"/medal/status\", authSvc.UserMobile, appMedalStatus)\n\t\tapp.POST(\"/medal/check\", authSvc.UserMobile, appMedalCheck)\n\t\tapp.POST(\"/medal/open\", authSvc.UserMobile, appMedalOpen)\n\t\tapp.POST(\"/medal/rename\", authSvc.UserMobile, appMedalRename)\n\t\t// article\n\t\tapp.GET(\"/article/list\", authSvc.UserMobile, appArticleList)\n\t\t// material\n\t\tapp.GET(\"/material/pre\", authSvc.UserMobile, appMaterialPre)\n\t\tapp.GET(\"/material/view\", authSvc.UserMobile, appMaterial)\n\t\t// bgm\n\t\tapp.GET(\"/bgm/pre\", authSvc.UserMobile, appBgmPre)\n\t\tapp.GET(\"/bgm/list\", authSvc.UserMobile, appBgmList)\n\t\tapp.GET(\"/bgm/view\", authSvc.UserMobile, appBgmView)\n\t\tapp.GET(\"/bgm/search\", authSvc.UserMobile, appBgmSearch)\n\t\tapp.GET(\"/cooperate/view\", authSvc.User, appCooperate)\n\t\t// task\n\t\tapp.POST(\"/newcomer/task/bind\", authSvc.UserMobile, appTaskBind)\n\t}\n\tcli := e.Group(\"/x/client\", authSvc.User)\n\t{\n\t\t// archive.\n\t\tcli.GET(\"/archives\", clientArchives)\n\t\tcli.GET(\"/archive/search\", clientArchiveSearch)\n\t\tcli.GET(\"/archive/view\", clientViewArc)\n\t\tcli.POST(\"/archive/delete\", clientDelArc)\n\t\tcli.GET(\"/archive/pre\", clientPre)\n\t\tcli.GET(\"/archive/tags\", clientTags)\n\t\t// template.\n\t\tcli.GET(\"/tpls\", clientTemplates)\n\t\tcli.POST(\"/tpl/add\", clientAddTpl)\n\t\tcli.POST(\"/tpl/update\", clientUpdateTpl)\n\t\tcli.POST(\"/tpl/delete\", clientDelTpl)\n\t\t// cover list.\n\t\tcli.GET(\"/archive/covers\", coverList)\n\t}\n\tgeeg := e.Group(\"/x/geetest\", authSvc.UserWeb)\n\t{\n\t\t// geetest.\n\t\tgeeg.GET(\"/pre\", gtPreProcess)\n\t\tgeeg.POST(\"/validate\", gtValidate)\n\t\tgeeg.GET(\"/pre/add\", gtPreProcessAdd)\n\t}\n\tcreator := e.Group(\"/x/creator\", authSvc.UserMobile)\n\t{\n\t\t// index\n\t\tcreator.GET(\"/my\", creatorMy)\n\t\tcreator.GET(\"/index\", creatorIndex)\n\t\tcreator.GET(\"/earnings\", creatorEarnings)\n\t\tcreator.GET(\"/banner\", creatorBanner)\n\t\tcreator.GET(\"/replies\", creatorReplyList)\n\t\t//archive\n\t\tcreator.GET(\"/archives\", creatorArchives)\n\t\tcreator.GET(\"/archive/tag/info\", creatorArcTagInfo)\n\t\tcreator.GET(\"/archive/view\", creatorViewArc)\n\t\tcreator.GET(\"/archive/videoquit\", creatorVideoQuit)\n\t\tcreator.GET(\"/archive/data\", creatorArchiveData)\n\t\tcreator.POST(\"/archive/delete\", creatorDelArc)\n\t\tcreator.GET(\"/archive/pre\", creatorPre)\n\t\tcreator.GET(\"/archive/tags\", creatorPredictTag)\n\t\tcreator.GET(\"/archive/desc/format\", creatorDescFormat)\n\t\t// article\n\t\tcreator.GET(\"/article/pre\", creatorArticlePre)\n\t\tcreator.GET(\"/article/list\", creatorArticleList)\n\t\tcreator.GET(\"/article/view\", creatorArticle)\n\t\tcreator.POST(\"/article/delete\", creatorDelArticle)\n\t\tcreator.POST(\"/article/withdraw\", creatorWithDrawArticle)\n\t\tcreator.GET(\"/draft/list\", creatorDraftList)\n\t\t// danmu\n\t\tcreator.GET(\"/danmu/list\", creatorDmList)\n\t\tcreator.GET(\"/danmu/recent\", creatorDmRecent)\n\t\tcreator.POST(\"/danmu/edit\", creatorDmEdit)\n\t\tcreator.POST(\"/danmu/edit/batch\", creatorDmEditBatch)\n\t\t//data\n\t\tcreator.GET(\"/data/archive\", creatorDataArchive)\n\t\tcreator.GET(\"/data/article\", creatorDataArticle)\n\t}\n\n\ti := e.Group(\"/x/internal/creative\", verifySvc.Verify)\n\t{\n\t\t// TODO deprecated\n\t\ti.GET(\"/porder\", upPorder)\n\t\t// for main app\n\t\ti.GET(\"/app/pre\", appNewPre)\n\t\t// get order game info for app\n\t\ti.GET(\"/arc/commercial\", arcCommercial)\n\t\ti.POST(\"/watermark/set\", waterMarkSetInternal)\n\t\ti.GET(\"/order/game\", arcOrderGameInfo)\n\t\ti.POST(\"/upload/material\", uploadMaterial)\n\t\ti.POST(\"/join/growup/account\", growAccountStateInternal)\n\t\ti.GET(\"/video/viewpoints\", videoViewPoints)\n\t\ti.GET(\"/archive/bgm\", arcBgmList)\n\t\ti.GET(\"/archive/staff\", arcStaff)\n\t\ti.GET(\"/archive/vote\", voteAcsByTime)\n\n\t\t//联合投稿配置\n\t\ti.GET(\"/staff/config\", staffConfig)\n\n\t\t// data\n\t\ti.GET(\"/data/videoquit\", setContextMid, webVideoQuitPoints)\n\t\ti.GET(\"/data/archive\", setContextMid, webArchive)\n\t\ti.GET(\"/data/article\", setContextMid, webArticleData)\n\t\ti.GET(\"/data/base\", setContextMid, base)\n\t\ti.GET(\"/data/trend\", setContextMid, trend)\n\t\ti.GET(\"/data/action\", setContextMid, action)\n\t\ti.GET(\"/data/survey\", setContextMid, survey)\n\t\ti.GET(\"/data/pandect\", setContextMid, pandect)\n\t\ti.GET(\"/data/fan\", setContextMid, webFan)\n\t\ti.GET(\"/data/playsource\", setContextMid, webPlaySource)\n\t\ti.GET(\"/data/playanalysis\", setContextMid, webArcPlayAnalysis)\n\t\ti.GET(\"/data/article/thirty\", setContextMid, webArtThirtyDay)\n\t\ti.GET(\"/data/article/rank\", setContextMid, webArtRank)\n\t\ti.GET(\"/data/article/source\", setContextMid, webArtReadAnalysis)\n\n\t\t// archive\n\t\ti.GET(\"/archives\", setContextMid, webArchives)\n\t\t// videos\n\t\ti.GET(\"/archive/videos\", setContextMid, webVideos)\n\n\t\t// history\n\t\ti.GET(\"/archive/history/list\", setContextMid, webHistoryList)\n\n\t\t// danmu\n\t\ti.GET(\"/danmu/distri\", setContextMid, webDmDistri)\n\n\t\t// up weekly honor\n\t\ti.GET(\"/task/pub/list\", setContextMid, taskPubList) //其他业务方查看任务列表\n\t}\n}", "func main() {\n\trouter := mux.NewRouter().StrictSlash(true)\n\tsub := router.PathPrefix(\"/api/v1\").Subrouter()\n\tsub.Methods(\"GET\").Path(\"/companies\").HandlerFunc(handler.GetCompanies)\n\tsub.Methods(\"POST\").Path(\"/companies\").HandlerFunc(handler.SaveCompany)\n\tsub.Methods(\"GET\").Path(\"/companies/{name}\").HandlerFunc(handler.GetCompany)\n\tsub.Methods(\"PUT\").Path(\"/companies/{name}\").HandlerFunc(handler.UpdateCompany)\n\tsub.Methods(\"DELETE\").Path(\"/companies/{name}\").HandlerFunc(handler.DeleteCompany)\n\n\tlog.Fatal(http.ListenAndServe(\":3000\", router))\n}", "func (s *Server) handleAggregated(w http.ResponseWriter, req *http.Request) {\n\tif req.Method != http.MethodGet {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tsegmentParam, ok := req.URL.Query()[\"segment\"]\n\tif !ok || len(segmentParam) == 0 {\n\t\tsegmentParam = []string{\"1s\"}\n\t}\n\tsegmentDur, err := time.ParseDuration(segmentParam[0])\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tdurFn := func(total time.Duration) time.Duration {\n\t\treturn segmentDur\n\t}\n\ts.mu.Lock()\n\tif s.ops == nil {\n\t\ts.mu.Unlock()\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\tif s.agrr == nil || s.aggrDur != segmentDur {\n\t\taggr := aggregate.Aggregate(s.ops, aggregate.Options{\n\t\t\tDurFunc: durFn,\n\t\t\tSkipDur: 0,\n\t\t})\n\t\ts.agrr = &aggr\n\t\ts.aggrDur = segmentDur\n\t}\n\t// Copy\n\taggregated := *s.agrr\n\ts.mu.Unlock()\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tb, err := json.MarshalIndent(aggregated, \"\", \" \")\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tw.Write(b)\n}", "func init() {\n\n// Run App at 'release' mode in production.\n gin.SetMode(gin.ReleaseMode)\n\n// Starts a new Gin instance with no middle-ware\n router := gin.New()\n v1 := router.Group(\"/v1\")\n v1.GET(\"/orders/:UsrId/list\", OrdersListV1)\n v1.POST(\"/orders/:UsrId/place\", CreateOrderV1)\n v1.PUT(\"/orders/:OrdId/tranxn\", OrderTransactionV1)\n v1.PUT(\"/orders/:OrdId/ordstatus\", ChangeOrderStatusV1)\n v1.DELETE(\"/orders/:OrdId/remove\", DeleteOrderV1)\n\n v1.POST(\"/items/:UsrId\", CreateItemV1)\n v1.GET(\"/items/:UsrId/usrlist\", UserItemsV1)\n v1.PUT(\"/items/:UsrId\", UpdateItemsV1)\n v1.DELETE(\"/items/:ItmId\", DeleteItemV1)\n v1.GET(\"/orditems/:OrdId/ordlist\", OrderItemsV1)\n\n // Handle all requests using net/http\n http.Handle(\"/\", router)\n}", "func DataRetrievalHandler(reader fcrserver.FCRServerRequestReader, writer fcrserver.FCRServerResponseWriter, request *fcrmessages.FCRReqMsg) error {\n\tlogging.Debug(\"Handle data retrieval\")\n\t// Get core structure\n\tc := core.GetSingleInstance()\n\tc.MsgSigningKeyLock.RLock()\n\tdefer c.MsgSigningKeyLock.RUnlock()\n\n\t// Message decoding\n\tnonce, senderID, offer, accountAddr, voucher, err := fcrmessages.DecodeDataRetrievalRequest(request)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in decoding payload: %v\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Verify signature\n\tif request.VerifyByID(senderID) != nil {\n\t\t// Verify by signing key\n\t\tgwInfo := c.PeerMgr.GetGWInfo(senderID)\n\t\tif gwInfo == nil {\n\t\t\t// Not found, try sync once\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil {\n\t\t\t\terr = fmt.Errorf(\"Error in obtaining information for gateway %v\", senderID)\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t\tif request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t// Try update\n\t\t\tgwInfo = c.PeerMgr.SyncGW(senderID)\n\t\t\tif gwInfo == nil || request.Verify(gwInfo.MsgSigningKey, gwInfo.MsgSigningKeyVer) != nil {\n\t\t\t\terr = fmt.Errorf(\"Error in verifying request from gateway %v: %v\", senderID, err.Error())\n\t\t\t\tlogging.Error(err.Error())\n\t\t\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check payment\n\trefundVoucher := \"\"\n\treceived, lane, err := c.PaymentMgr.Receive(accountAddr, voucher)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error in receiving voucher %v:\", err.Error())\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tif lane != 1 {\n\t\terr = fmt.Errorf(\"Not correct lane received expect 1 got %v:\", lane)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\texpected := big.NewInt(0).Add(c.Settings.SearchPrice, offer.GetPrice())\n\tif received.Cmp(expected) < 0 {\n\t\t// Short payment\n\t\t// Refund money\n\t\tif received.Cmp(c.Settings.SearchPrice) <= 0 {\n\t\t\t// No refund\n\t\t} else {\n\t\t\tvar ierr error\n\t\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\t\tif ierr != nil {\n\t\t\t\t// This should never happen\n\t\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t\t}\n\t\t}\n\t\terr = fmt.Errorf(\"Short payment received, expect %v got %v, refund voucher %v\", expected.String(), received.String(), refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\n\t// Payment is fine, verify offer\n\tif offer.Verify(c.OfferSigningPubKey) != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer signature, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer merkle proof\n\tif offer.VerifyMerkleProof() != nil {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Fail to verify the offer merkle proof, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Verify offer expiry\n\tif offer.HasExpired() {\n\t\t// Refund money\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, big.NewInt(0).Sub(received, c.Settings.SearchPrice))\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Offer has expired, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Offer is verified. Respond\n\t// First get the tag\n\ttag := c.OfferMgr.GetTagByCID(offer.GetSubCID())\n\t// Second read the data\n\tdata, err := ioutil.ReadFile(filepath.Join(c.Settings.RetrievalDir, tag))\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in finding the content, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\t// Third encoding response\n\tresponse, err := fcrmessages.EncodeDataRetrievalResponse(nonce, tag, data)\n\tif err != nil {\n\t\t// Refund money, internal error, refund all\n\t\tvar ierr error\n\t\trefundVoucher, ierr = c.PaymentMgr.Refund(accountAddr, lane, received)\n\t\tif ierr != nil {\n\t\t\t// This should never happen\n\t\t\tlogging.Error(\"Error in refunding: %v\", ierr.Error())\n\t\t}\n\t\terr = fmt.Errorf(\"Internal error in encoding the response, refund voucher %v\", refundVoucher)\n\t\tlogging.Error(err.Error())\n\t\treturn writer.Write(fcrmessages.CreateFCRACKErrorMsg(nonce, err), c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n\t}\n\tc.OfferMgr.IncrementCIDAccessCount(offer.GetSubCID())\n\n\treturn writer.Write(response, c.MsgSigningKey, c.MsgSigningKeyVer, c.Settings.TCPInactivityTimeout)\n}", "func InitRouter() *gin.Engine {\r\n\trouter := gin.New()\r\n\t// router := gin.uuDefault()\r\n\trouter.Use(cors.New(cors.Config{\r\n\t\tAllowOrigins: []string{\"http://bri360.bri.co.id\", \"http://127.0.0.1:8240\"},\r\n\t\tAllowMethods: []string{\"POST\"},\r\n\t\tAllowHeaders: []string{\"Origin\", \"X-Requested-With\", \"Content-Type\", \"Accept\", \"Authorization\"},\r\n\t\tExposeHeaders: []string{\"Content-Length\"},\r\n\t\tAllowCredentials: true,\r\n\t\tAllowOriginFunc: func(origin string) bool {\r\n\t\t\treturn origin == \"https://github.com\"\r\n\t\t},\r\n\t\tMaxAge: 12 * time.Hour,\r\n\t}))\r\n\r\n\trouter.Use(apmgin.Middleware(router))\r\n\r\n\t//routers\r\n\r\n\trouter.POST(\"/bri360/summary-dashboard/churn\", handlerChurn)\r\n\trouter.POST(\"/bri360/summary-dashboard/fasitiltas-rekening\", FasilitasRekening)\r\n\trouter.POST(\"/bri360/summary-dashboard/segmentasi\", Segmentasi)\r\n\trouter.POST(\"/bri360/summary-dashboard/prediksi-rata-saldo\", Ratassaldo)\r\n\trouter.POST(\"/bri360/summary-dashboard/top-frekuensi-merchant\", TopFrekuensiMerchant)\r\n\trouter.POST(\"/bri360/summary-dashboard/top-nominal-merchant\", TopNominalFrekuensiMerchant)\r\n\trouter.POST(\"/bri360/summary-dashboard/posisi-saldo\", PosisiSaldo)\r\n\trouter.POST(\"/bri360/summary-dashboard/top-product\", TopProduct)\r\n\treturn router\r\n}", "func init() {\n\t// system.Router.HandleFunc(\"/app/get/list/{crud}\", HandleListGeneric)\n}", "func Router(resources di.Container) http.Handler {\n\tr := chi.NewRouter()\n\n\tsignUpService := resources.Get(\"sign_up-service\").(signup.Service)\n\tsignUpHandler := handler.SignUp(signUpService)\n\tauthorizeService := resources.Get(\"authorize-service\").(authorizing.Service)\n\tauthorizeMiddleware := middleware.AuthorizeReq(authorizeService)\n\tauthenticatingService := resources.Get(\"authenticating-service\").(authenticating.Service)\n\tauthenticatingHandler := handler.Authenticating(authenticatingService)\n\n\tcreatingRepoService := resources.Get(\"creating-repo-service\").(creating.Service)\n\tcreatingRepoHandler := handler.Creating(creatingRepoService)\n\tlistingUserReposMiddleware := middleware.FilterUserRepos()\n\tlistingRepoService := resources.Get(\"listing-repo-services\").(listing.RepoService)\n\tlistingUserReposHandler := handler.ListingUserRepos(listingRepoService)\n\tlistingPublicReposMiddleware := middleware.FilterPublicRepos()\n\tlistingPublicReposHandler := handler.ListingPublicRepos(listingRepoService)\n\tgettingRepoService := resources.Get(\"getting-repo-service\").(getting.RepoService)\n\tctxRepoMiddleware := middleware.RepoCtx(gettingRepoService)\n\trepoOwnerOrPublicMiddleware := middleware.RepoOwnerOrPublic()\n\trepoOwnerMiddleware := middleware.RepoOwner()\n\tgettingRepoHandler := handler.GettingRepo()\n\n\taddingCaptureService := resources.Get(\"adding-capture-service\").(adding.CaptureService)\n\taddingCaptureHandler := handler.AddingCapture(addingCaptureService)\n\taddingMultiCaptureService := resources.Get(\"adding-multi-capture-service\").(adding.MultiCaptureService)\n\taddingMultiCaptureHandler := handler.AddingMultiCapture(addingMultiCaptureService)\n\tlistingCapturesMiddleware := middleware.FilterCaptures()\n\tlistingCaptureService := resources.Get(\"listing-capture-services\").(listing.CaptureService)\n\tlistingCapturesHandler := handler.ListingRepoCaptures(listingCaptureService)\n\tgettingCaptureService := resources.Get(\"getting-capture-service\").(getting.CaptureService)\n\tctxCaptureMiddleware := middleware.CaptureCtx(gettingCaptureService)\n\tgettingCaptureHandler := handler.GettingCapture()\n\tremovingCaptureService := resources.Get(\"removing-capture-service\").(removing.CaptureService)\n\tremovingCaptureHandler := handler.RemovingCapture(removingCaptureService)\n\tupdatingCaptureService := resources.Get(\"updating-capture-service\").(updating.CaptureService)\n\tupdatingCaptureHandler := handler.UpdatingCapture(updatingCaptureService)\n\n\tr.Post(\"/sign/\", signUpHandler)\n\tr.Route(\"/auth/\", func(r chi.Router) {\n\t\tr.Post(\"/token-auth\", authenticatingHandler)\n\t})\n\tr.Route(\"/user/\", func(r chi.Router) {\n\t\tr.Use(authorizeMiddleware)\n\t\tr.Route(\"/repos/\", func(r chi.Router) {\n\t\t\tr.Post(\"/\", creatingRepoHandler)\n\t\t\tr.With(listingUserReposMiddleware).Get(\"/\", listingUserReposHandler)\n\n\t\t})\n\t})\n\tr.Route(\"/repositories/\", func(r chi.Router) {\n\t\tr.Use(authorizeMiddleware)\n\t\tr.With(listingPublicReposMiddleware).\n\t\t\tGet(\"/\", listingPublicReposHandler)\n\t\tr.Route(\"/{id}\", func(r chi.Router) {\n\t\t\tr.Use(ctxRepoMiddleware)\n\t\t\tr.With(repoOwnerOrPublicMiddleware).Get(\"/\", gettingRepoHandler)\n\t\t\tr.Route(\"/captures/\", func(r chi.Router) {\n\t\t\t\tr.With(repoOwnerMiddleware).Post(\"/\", addingCaptureHandler)\n\t\t\t\tr.With(repoOwnerMiddleware).Post(\"/multi\", addingMultiCaptureHandler)\n\t\t\t\tr.With(repoOwnerOrPublicMiddleware).With(listingCapturesMiddleware).Get(\"/\", listingCapturesHandler)\n\t\t\t\tr.Route(\"/{captureId}\", func(r chi.Router) {\n\t\t\t\t\tr.Use(ctxCaptureMiddleware)\n\t\t\t\t\tr.With(repoOwnerOrPublicMiddleware).Get(\"/\", gettingCaptureHandler)\n\t\t\t\t\tr.With(repoOwnerMiddleware).Delete(\"/\", removingCaptureHandler)\n\t\t\t\t\tr.With(repoOwnerMiddleware).Put(\"/\", updatingCaptureHandler)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n\n\treturn r\n}", "func badGateway(rw http.ResponseWriter, r *http.Request) {\n\n}", "func handleRequests() {\n\tmyRouter := mux.NewRouter().StrictSlash(true)\n\tmyRouter.HandleFunc(\"/twoSidePrime/{num}\", isTwoSidePrime)\n\tlog.Fatal(http.ListenAndServe(\":8082\", myRouter))\n}", "func (vs *VolumeServer) privateStoreHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tstats.ReadRequest()\n\t\tvs.GetOrHeadHandler(w, r)\n\tcase \"HEAD\":\n\t\tstats.ReadRequest()\n\t\tvs.GetOrHeadHandler(w, r)\n\tcase \"DELETE\":\n\t\tstats.DeleteRequest()\n\t\tvs.guard.WhiteList(vs.DeleteHandler)(w, r)\n\tcase \"PUT\":\n\t\tstats.WriteRequest()\n\t\tvs.guard.WhiteList(vs.PostHandler)(w, r)\n\tcase \"POST\":\n\t\tstats.WriteRequest()\n\t\tvs.guard.WhiteList(vs.PostHandler)(w, r)\n\t}\n}", "func Charge(c *gin.Context) {\n\t// Encode server key using base 64 string\n\tauthorization := base64.StdEncoding.EncodeToString([]byte(Token))\n\n\t// HTTP client is using app engine\n\tappEngine := appengine.NewContext(c.Request)\n\tclient := urlfetch.Client(appEngine)\n\n\trequest, err := http.NewRequest(\"POST\", VTBaseURL+\"/charge\", c.Request.Body)\n\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"status_code\": http.StatusBadRequest, \"status_message\": err.Error()})\n\t} else {\n\t\trequest.Header.Add(\"Content-Type\", \"application/json\")\n\t\trequest.Header.Add(\"Accept\", \"application/json\")\n\t\trequest.Header.Add(\"Authorization\", \"Basic \"+authorization)\n\t\tresponse, _ := client.Do(request)\n\n\t\tresponseBody, _ := ioutil.ReadAll(response.Body)\n\t\tvar respObj interface{}\n\t\tjson.Unmarshal(responseBody, &respObj)\n\t\tc.JSON(http.StatusOK, respObj)\n\t}\n}", "func Handler(d *common.Domain, w http.ResponseWriter, r *http.Request) {\n\n\t// Check to see if this request is for an advert.\n\tif r.URL.Path == \"/advert\" {\n\t\tHandlerAdvert(d, w, r)\n\t\treturn\n\t}\n\n\t// Try the URL path for the preference values.\n\tp, ae := newSWANDataFromPath(d, r)\n\tif ae != nil {\n\n\t\t// If the data can't be decrypted rather than another type of error then\n\t\t// redirect to the CMP dialog.\n\t\tif ae.StatusCode() >= 400 && ae.StatusCode() < 500 {\n\t\t\tif d.SwanPostMessage == false {\n\t\t\t\thttp.Redirect(w, r, getCMPURL(d, r, nil), 303)\n\t\t\t} else {\n\t\t\t\thandlerPublisherPage(d, w, r, p)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tcommon.ReturnServerError(d.Config, w, ae)\n\t\treturn\n\t}\n\tif p != nil {\n\t\tredirectToCleanURL(d.Config, w, r, p)\n\t\treturn\n\t}\n\n\t// If the path does not contain any values then get them from the cookies.\n\tif p == nil {\n\t\tvar err error\n\t\tp, err = newSWANDataFromCookies(r)\n\t\tif err != nil && d.Config.Debug {\n\t\t\tlog.Println(err.Error())\n\t\t}\n\t}\n\n\t// If the request is from a crawler than ignore SWAN.\n\tc, err := fod.GetCrawlerFrom51Degrees(r)\n\tif err != nil {\n\t\tcommon.ReturnServerError(d.Config, w, err)\n\t\treturn\n\t}\n\tif c {\n\t\thandlerPublisherPage(d, w, r, p)\n\t\treturn\n\t}\n\n\t// If there is valid SWAN data then display the page using the page handler.\n\t// If the SWAN data is not complete, valid, or needs revalidating because it\n\t// might be old then ask the user to verify or add the required data via the\n\t// User Interface Provider redirect action.\n\t// If the SWAN data is not present or invalid then redirect to SWAN to\n\t// get the latest data.\n\tif p != nil && len(p) > 0 {\n\t\tif isSet(p) {\n\n\t\t\t// Check to see if the values need to be revalidated.\n\t\t\tif d.SwanPostMessage == false &&\n\t\t\t\td.SwanJavaScript == false &&\n\t\t\t\trevalidateNeeded(p) {\n\t\t\t\tredirectToSWANFetch(d, w, r, p)\n\t\t\t} else {\n\t\t\t\thandlerPublisherPage(d, w, r, p)\n\t\t\t}\n\t\t} else if isPresent(p, \"pref\") || isPresent(p, \"swid\") {\n\n\t\t\t// Not all the values are present. Try fetching them again.\n\t\t\tredirectToSWANFetch(d, w, r, p)\n\n\t\t} else {\n\n\t\t\t// Call the CMP to ask the user to confirm values.\n\t\t\thttp.Redirect(w, r, getCMPURL(d, r, p), 303)\n\t\t}\n\t} else {\n\t\tif d.SwanPostMessage == false && d.SwanJavaScript == false {\n\t\t\tredirectToSWANFetch(d, w, r, p)\n\t\t} else {\n\t\t\thandlerPublisherPage(d, w, r, p)\n\t\t}\n\t}\n}", "func (h *handler) discharge(w http.ResponseWriter, req *http.Request) {\n\tdata, err := ioutil.ReadAll(req.Body)\n\tif err != nil {\n\t\twriteResponse(w, http.StatusBadRequest, \"bad request\")\n\t\treturn\n\t}\n\tvalues, err := url.ParseQuery(string(data))\n\tif err != nil {\n\t\twriteResponse(w, http.StatusBadRequest, \"bad request\")\n\t\treturn\n\t}\n\tid := values.Get(\"id\")\n\tif id == \"\" {\n\t\twriteResponse(w, http.StatusBadRequest, \"bad request\")\n\t\treturn\n\t}\n\n\tm, err := h.config.Bakery.Discharge(\n\t\tbakery.ThirdPartyCheckerFunc(\n\t\t\tfunc(cavId, cav string) ([]checkers.Caveat, error) {\n\t\t\t\treturn h.checkThirdPartyCaveat(req, cavId, cav)\n\t\t\t}),\n\t\tid)\n\tif err != nil {\n\t\twriteResponse(w, http.StatusInternalServerError, \"internal server error\")\n\t\treturn\n\t}\n\n\tresponse := struct {\n\t\tMacaroon *macaroon.Macaroon\n\t}{\n\t\tMacaroon: m,\n\t}\n\twriteResponse(w, http.StatusOK, response)\n}", "func main() {\n\t//Advertisement Handler\n\tadHandler := handler.NewAdHandler()\n\t//Regular Expression Handler for matching the pattern of restful type and fetching path params\n\tregexHnd := new(handler.RegexpHandler)\n\n\t//Chain Handlers\n\trequestValidatorHandler := handler.NewRequestValidatorHandler()\n\ttraceableHandler := handler.NewTraceableHandler()\n\theadersHandler := handler.NewResponseHeaderHandler()\n\n\t//Handler Chain configuration\n\thandlerChain := requestValidatorHandler.Next(\n\t\t\t\t\t\t\ttraceableHandler.Next(\n\t\t\t\t\t\t\theadersHandler.Next(regexHnd)))\n\n\tregexHnd.HandleFunc(\"/service$\", adHandler.FindAdByServiceHandler)\n\tregexHnd.HandleFunc(\"/service/[a-zA-Z_0-9]*$\", adHandler.FindAdByCategoryHandler)\n\tregexHnd.HandleFunc(\"/service/[a-zA-Z_0-9]*/[a-zA-Z._0-9]*$\", adHandler.SearchAdHandler)\n\tlog.Fatal(http.ListenAndServe(\":8080\", handlerChain))\n}", "func HandleRootReuest(w http.ResponseWriter, r *http.Request, store Storager) {\n\tcheckRequest(w, r)\n\t//var store Storager = new(storage.Storage)\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\thttp.Error(w, \"Internal server error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(body, store); err != nil {\n\t\thttp.Error(w, \"Error json format\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tHandleMethodRequest(w, store)\n}", "func (s *Server) handleDashboardPayments() http.HandlerFunc {\n\tvar o sync.Once\n\tvar tpl *template.Template\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx, logger := GetLogger(s.getCtx(r))\n\t\to.Do(func() {\n\t\t\ttpl = s.loadWebTemplateDashboard(ctx, \"payments.html\")\n\t\t})\n\t\tctx, provider, data, _, ok := s.createTemplateDataDashboard(w, r.WithContext(ctx), tpl, true)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t//setup the breadcrumbs\n\t\tbreadcrumbs := []breadcrumb{\n\t\t\t{\"Invoices\", \"\"},\n\t\t}\n\t\tdata[TplParamBreadcrumbs] = breadcrumbs\n\t\tdata[TplParamActiveNav] = provider.GetURLPayments()\n\t\tdata[TplParamFormAction] = provider.GetURLPayments()\n\n\t\t//read the form\n\t\tfilterStr := r.FormValue(URLParams.Filter)\n\n\t\t//prepare the data\n\t\tdata[TplParamFilter] = filterStr\n\n\t\t//validate the filter\n\t\tvar err error\n\t\tfilter := PaymentFilterAll\n\t\tif filterStr != \"\" {\n\t\t\tfilter, err = ParsePaymentFilter(filterStr)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorw(\"parse filter\", \"error\", err, \"filter\", filterStr)\n\t\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\t}\n\t\t}\n\n\t\t//load the payments\n\t\tctx, payments, err := ListPaymentsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, filter)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"load payments\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamPayments] = s.createPaymentUIs(payments)\n\n\t\t//load the count\n\t\tctx, countUnPaid, err := CountPaymentsByProviderIDAndFilter(ctx, s.getDB(), provider.ID, PaymentFilterUnPaid)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(\"count payments unpaid\", \"error\", err, \"id\", provider.ID)\n\t\t\tdata[TplParamErr] = GetErrText(Err)\n\t\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t\t\treturn\n\t\t}\n\t\tdata[TplParamCountUnPaid] = countUnPaid\n\t\ts.renderWebTemplate(w, r.WithContext(ctx), tpl, data)\n\t}\n}", "func deapex(w http.ResponseWriter, r *http.Request) {\n // Are we logging redirects?\n if config.Debug == true || config.LogRedirect == true {\n log.Print(\"Request Host: \", r.Host)\n log.Print(\"Request URI: \", r.RequestURI)\n }\n\n // Obtain our host and URI from request data.\n requestHost := r.Host\n requestURI := r.RequestURI\n\n // Create the regexp to match the port number\n rpPort := regexp.MustCompile(\":[0-9]+\")\n\n // Strip the port number out of request host\n hostName := rpPort.ReplaceAllString(requestHost, \"\")\n\n // Variable to contain our subdomain redirect.\n var redirectSubdomain string\n\n // Subdomain Redirect Key\n var oKey int\n\n // Variable to contain our path redirect.\n var redirectPath string\n\n // Iterate through all the overrides we are storing in memory.\n for i := 0 ; i < len(config.Overrides) ; i++ {\n // Does the hostname value match override hostname?\n if config.Overrides[i].Hostname == hostName {\n // Set our redirect subdomain to this override.\n redirectSubdomain = config.Overrides[i].Subdomain\n oKey = i\n break\n }\n }\n\n // If there is no redirect subdomain in overrides, use the default.\n if redirectSubdomain == \"\" {\n redirectSubdomain = config.DefaultSubdomain + \".\" + hostName\n } else {\n // Iterate through the path overrides for this hostname.\n for i := 0 ; i < len(config.Overrides[oKey].PathOverrides) ; i++ {\n // Does the request URI value match override path?\n if config.Overrides[oKey].PathOverrides[i].Source == requestURI {\n // Set our URI to this path.\n redirectPath = config.Overrides[oKey].PathOverrides[i].\n Destination\n break\n }\n }\n }\n\n // How are we going to redirect the path?\n if redirectPath == \"\" {\n if config.Overrides[oKey].DefaultPath != \"\" {\n requestURI = config.Overrides[oKey].DefaultPath\n }\n } else {\n requestURI = redirectPath\n }\n\n // Debug, where are we going?\n if config.Debug == true || config.LogRedirect == true {\n log.Print(\"New Host: \", redirectSubdomain)\n log.Print(\"New Request URI: \", requestURI)\n }\n\n // Build our forward address.\n forwardAddr := \"http://\" + redirectSubdomain + requestURI\n\n // Serve our 301 redirect.\n http.Redirect(w, r, forwardAddr, 301)\n}", "func (app *App) topContributorsHandler(w http.ResponseWriter, r *http.Request) {\n\tlogrus.Info(\"Serving topContributors Request\")\n\tctx := r.Context()\n\tselect {\n\tcase <-ctx.Done():\n\t\tlogrus.Debug(\"topContributorsHandler Context canceled\")\n\tdefault:\n\t\tlocation := mux.Vars(r)[\"location\"]\n\t\titems, err := strconv.Atoi(r.URL.Query().Get(\"items\"))\n\t\tif err != nil {\n\t\t\titems = 10\n\t\t} else if items > MaxItems { //Hard limit the users\n\t\t\titems = MaxItems\n\t\t}\n\t\tvar users = make([]*github.User, 0)\n\t\tcacheDisabled := false\n\t\tcacheHit := false\n\t\tcacheKey := strings.ToUpper(location)\n\n\t\t//[1] Get Data form the cache\n\t\t//users, err = app.getCacheItems(ctx, location, items)\n\t\tusers, cacheHit, cacheDisabled = app.getCacheItems(ctx, location, items)\n\t\tif cacheHit == false {\n\t\t\t// If system is under RateLimit, return\n\t\t\tif ok := app.ghClient.CheckRateLimit(); ok {\n\t\t\t\tlogrus.Debug(\"RateLimitError Set, Discarting API Requests until RateLimit expiration\")\n\t\t\t\tlogrus.Error(app.ghClient.GetRateLimitError())\n\t\t\t\thttp.Error(w, app.ghClient.GetRateLimitError().Error(), http.StatusTooManyRequests)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif cacheDisabled == false {\n\t\t\t\t// Set Cache Distributed Lock\n\t\t\t\tif err = app.cache.SetLock(ctx, \"mutex-\"+cacheKey); err == nil {\n\t\t\t\t\tlogrus.Debug(\"Cache Distributed lock acquired\")\n\t\t\t\t\tdefer app.releaseCacheLock(\"mutex-\" + cacheKey)\n\t\t\t\t}\n\n\t\t\t\t// Get data from the cache\n\t\t\t\t// Another goroutine might has set the data\n\t\t\t\tusers, cacheHit, cacheDisabled = app.getCacheItems(ctx, location, items)\n\t\t\t}\n\n\t\t\tif cacheHit == false { // Get users from the Github API\n\t\t\t\tif users, err = app.ghClient.GetUsersByLocation(ctx, location, items); err != nil {\n\t\t\t\t\tif serr, ok := err.(*github.RateLimitError); ok {\n\t\t\t\t\t\thttp.Error(w, serr.Error(), http.StatusTooManyRequests)\n\t\t\t\t\t} else {\n\t\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif cacheDisabled == false && cacheHit == false {\n\t\t\t\tlogrus.Debug(\"Setting cache value\")\n\t\t\t\tif err = app.setCacheItems(ctx, location, users); err != nil {\n\t\t\t\t\tlogrus.Debug(\"Error Setting cache value\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Encode users\n\t\tif len(users) > 0 {\n\t\t\tsort.SliceStable(users, func(i, j int) bool {\n\t\t\t\treturn *(users)[i].PublicRepos > *(users)[j].PublicRepos\n\t\t\t})\n\t\t}\n\t\tif items <= len(users) {\n\t\t\tjson.NewEncoder(w).Encode(users[:items])\n\t\t} else {\n\t\t\tjson.NewEncoder(w).Encode(users)\n\t\t}\n\n\t}\n}", "func fileTreeUploadGetHandler(w http.ResponseWriter, r *http.Request) {\n\tfileTreeUpDownGet(theCfg.uploadDir, w, r)\n}", "func provisioningHandler(s *state.State, w http.ResponseWriter, r *http.Request) {\n\t// query all provisionings\n\tlist, err := db.GetProvisioning(s)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// convert data to JSON\n\tbuff, err := json.Marshal(list)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"internal server error\"))\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(buff)\n}", "func (t *targetrunner) rebalanceHandler(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tcaller = r.Header.Get(cmn.HeaderCallerName)\n\t\tquery = r.URL.Query()\n\t\tgetRebData = cmn.IsParseBool(query.Get(cmn.URLParamRebData))\n\t)\n\tif !getRebData {\n\t\tt.invalmsghdlr(w, r, \"invalid request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tbody, status := t.rebManager.RebECDataStatus()\n\tif status != http.StatusOK {\n\t\tw.WriteHeader(status)\n\t\treturn\n\t}\n\n\tif ok := t.writeJSON(w, r, body, \"rebalance-data\"); !ok {\n\t\tglog.Errorf(\"Failed to send data to %s\", caller)\n\t}\n}", "func SpecificCourseHandler(w http.ResponseWriter, r *http.Request) {\n}", "func Handler(cs creating.Service, ls listing.Service, ds drawing.Service) http.Handler {\n\trouter := httprouter.New()\n\n\trouter.GET(\"/health\", health())\n\trouter.POST(\"/decks\", createDeck(cs))\n\trouter.GET(\"/decks/:id\", getDeck(ls))\n\trouter.PATCH(\"/decks/:id/draw/:amount\", drawCards(ds))\n\treturn router\n}", "func mapRoutes() {\n \n /*\n Add a pre-handler to save the referrer\n */\n goweb.MapBefore(func(c context.Context) error {\n \n // add a custom header\n c.HttpResponseWriter().Header().Set(\"X-Custom-Header\", \"Goweb\")\n \n return nil\n })\n \n /*\n Add a post-handler to log someBook\n */\n goweb.MapAfter(func(c context.Context) error {\n // TODO: log this\n return nil\n })\n \n /*\n Map the homepage...\n */\n goweb.Map(\"/\", func(c context.Context) error {\n return goweb.Respond.With(c, 200, []byte(\"Welcome to the Goweb example app - see the terminal for instructions.\"))\n })\n \n /*\n /status-code/xxx\n Where xxx is any HTTP status code.\n */\n goweb.Map(\"/status-code/{code}\", func(c context.Context) error {\n \n // get the path value as an integer\n statusCodeInt, statusCodeIntErr := strconv.Atoi(c.PathValue(\"code\"))\n if statusCodeIntErr != nil {\n return goweb.Respond.With(c, http.StatusInternalServerError, []byte(\"Failed to convert 'code' into a real status code number.\"))\n }\n \n // respond with the status\n return goweb.Respond.WithStatusText(c, statusCodeInt)\n })\n \n // /errortest should throw a system error and be handled by the\n // DefaultHttpHandler().ErrorHandler() Handler.\n\n goweb.Map(\"/errortest\", func(c context.Context) error {\n return errors.New(\"This is a test error!\")\n })\n \n /*\n Map a RESTful controller\n (see the BooksController for all the methods that will get\n mapped)\n */\n BooksController := new(BooksController)\n goweb.MapController(BooksController)\n \n goweb.Map(func(c context.Context) error {\n return goweb.API.RespondWithData(c, \"Just a number!\")\n }, goweb.RegexPath(`^[0-9]+$`))\n \n /*\n Catch-all handler for everything that we don't understand\n */\n goweb.Map(func(c context.Context) error {\n \n // just return a 404 message\n return goweb.API.Respond(c, 404, nil, []string{\"File not found\"})\n \n })\n \n}", "func pubsubPushHandler(c *router.Context) {\n\trc := requestContext(*c)\n\tbody, err := io.ReadAll(rc.Request.Body)\n\tif err != nil {\n\t\trc.fail(500, \"Failed to read the request: %s\", err)\n\t\treturn\n\t}\n\tif err = globalEngine.ProcessPubSubPush(rc.Context, body, rc.Request.URL.Query()); err != nil {\n\t\trc.err(err, \"Failed to process incoming PubSub push\")\n\t\treturn\n\t}\n\trc.ok()\n}", "func userRoutes(user *gin.RouterGroup) {\n // test routes\n user.GET(\"/redis\", func(c *gin.Context) {\n con := stores.redisPool.Get()\n defer con.Close()\n\n value, err := redis.String(con.Do(\"GET\", \"BOB1\"))\n if err != nil {\n c.JSON(500, gin.H{\"error\": \"Redis is DOWN\"})\n } else {\n c.JSON(200, gin.H{\"value\": value})\n }\n })\n\n user.GET(\"/pgsql\", func(c *gin.Context) {\n // check if connection valid\n _, err := stores.sqlPool.Query(\"SELECT * FROM webapp.user\")\n if err != nil {\n c.JSON(500, gin.H{\"error\": \"PG is DOWN\"})\n }\n\n c.JSON(200, gin.H{\"error\": \"PG is UP\"})\n })\n\n // handle user actions\n user.POST(\"/register\", handleRegistration)\n user.POST(\"/login\", handleLogin)\n user.POST(\"/logout\", handleLogout)\n user.GET(\"/profile\", handleProfile)\n user.GET(\"/progress/:family\", handleGetProgress)\n user.POST(\"/progress/:family\", handleSetProgress)\n}", "func main() {\n\trouter := mux.NewRouter().StrictSlash(true)\n\trouter.HandleFunc(\"/\", homeLink)\n\trouter.HandleFunc(\"/invoice\", createInvoice).Methods(\"POST\")\n\trouter.HandleFunc(\"/invoice\", getAllInvoices).Methods(\"GET\")\n\trouter.HandleFunc(\"/invoice/{id}\", getOneInvoice).Methods(\"GET\")\n\trouter.HandleFunc(\"/invoice/{id}\", payInvoice).Methods(\"POST\")\n\trouter.HandleFunc(\"/invoice/{id}\", deleteInvoice).Methods(\"DELETE\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", router))\n}", "func (d *Daemon) routeHandler(w *rest.ResponseWriter, r *rest.Request) {\n\t//id := strings.Split(r.URL.Path, \"/\")[2]\n\t//route := strings.Split(r.URL.Path, \"/\")[3]\n\n\tid, ok := r.PathParams[\"id\"]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"MISSING_BLOCK_ID\")\n\t\treturn\n\t}\n\n\troute, ok := r.PathParams[\"route\"]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"MISSING_ROUTE\")\n\t\treturn\n\t}\n\n\t_, ok = d.blockMap[id]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"BLOCK_ID_NOT_FOUND\")\n\t\treturn\n\t}\n\n\t_, ok = d.blockMap[id].Routes[route]\n\tif ok == false {\n\t\tApiResponse(w, 500, \"ROUTE_NOT_FOUND\")\n\t\treturn\n\t}\n\n\tmsg, err := ioutil.ReadAll(io.LimitReader(r.Body, READ_MAX))\n\n\tif err != nil {\n\t\tApiResponse(w, 500, \"BAD_REQUEST\")\n\t\treturn\n\t}\n\n\tvar outMsg interface{}\n\n\tif len(msg) > 0 {\n\t\terr = json.Unmarshal(msg, &outMsg)\n\t\tif err != nil {\n\t\t\tlog.Println(msg)\n\t\t\tApiResponse(w, 500, \"BAD_JSON\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tResponseChan := make(chan interface{})\n\tblockRouteChan := d.blockMap[id].Routes[route]\n\tblockRouteChan <- &blocks.BMsg{\n\t\tMsg: outMsg,\n\t\tResponseChan: ResponseChan,\n\t}\n\trespMsg := <-ResponseChan\n\n\trespJson, err := json.Marshal(respMsg)\n\tif err != nil {\n\t\tApiResponse(w, 500, \"BAD_RESPONSE_FROM_BLOCK\")\n\t\treturn\n\t}\n\n\tDataResponse(w, respJson)\n}", "func setupRouter() *gin.Engine {\n\t// Disable Console Color\n\t// gin.DisableConsoleColor()\n\tProductInController := new(controllers.ProductInController)\n\tProductOutController := new(controllers.ProductOutController)\n\tProductStockController := new(controllers.ProductStockController)\n\tReportController := new(controllers.ReportController)\n\n\tconfReader := new(config.ConfigReader)\n\tconfReader.Read()\n\tdb.InitSqlite() //ganti ke initsqlite\n\tr := gin.Default()\n\tc := cors.DefaultConfig()\n\tc.AllowAllOrigins = true\n\tr.Use(cors.New(c))\n\n\tr.GET(\"/get_barang_masuk\", ProductInController.GetBarangMasuk())\n\tr.POST(\"/submit_barang_masuk\", ProductInController.InsertBarangMasuk())\n\tr.POST(\"/update_barang_masuk\", ProductInController.UpdateBarangMasuk())\n\tr.POST(\"/delete_barang_masuk\", ProductInController.DeleteBarangMasuk())\n\n\tr.GET(\"/get_barang_keluar\", ProductOutController.GetBarangKeluar())\n\tr.POST(\"/submit_barang_keluar\", ProductOutController.InsertBarangKeluar())\n\tr.POST(\"/update_barang_keluar\", ProductOutController.UpdateBarangKeluar())\n\tr.POST(\"/delete_barang_keluar\", ProductOutController.DeleteBarangKeluar())\n\n\tr.GET(\"/get_stok_barang\", ProductStockController.GetStockBarang())\n\tr.POST(\"/update_stok_barang\", ProductStockController.UpdateStockBarang())\n\tr.POST(\"/submit_stok_barang\", ProductStockController.InsertStockBarang())\n\n\tr.GET(\"/laporan_nilai_barang\", ReportController.GetAveragePrice())\n\tr.GET(\"/laporan_penjualan\", ReportController.GetSellingReport())\n\tr.GET(\"/download_csv\", ReportController.DownloadCSV())\n\treturn r\n}", "func GETHandler(w http.ResponseWriter, r *http.Request) {\r\n\tquery := r.URL.Query()\r\n\t//pagination list using limit and offset query parameters\r\n\tlimit := query.Get(\"limit\")\r\n\toffset := query.Get(\"offset\")\r\n\tdb := OpenConnection()\r\n\tdefer db.Close()\r\n\tvar rows *sql.Rows\r\n\tvar err error\r\n\tmutex.Lock()\r\n\tdefer mutex.Unlock()\r\n\tswitch {\r\n\tcase limit == \"\" && offset != \"\":\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC OFFSET $1 \"\r\n\t\trows, err = db.Query(sqlstatement, offset)\r\n\tcase limit != \"\" && offset == \"\":\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC LIMIT $1 \"\r\n\t\trows, err = db.Query(sqlstatement, limit)\r\n\tcase limit == \"\" && offset == \"\":\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC\"\r\n\t\trows, err = db.Query(sqlstatement)\r\n\tdefault:\r\n\t\tsqlstatement := \"SELECT * FROM info1 ORDER BY creationtimestamp DESC LIMIT $1 OFFSET $2 \"\r\n\t\trows, err = db.Query(sqlstatement, limit, offset)\r\n\t}\r\n\tdefer rows.Close()\r\n\tif err != nil {\r\n\t\tw.Write([]byte(err.Error()))\r\n\t\tw.WriteHeader(http.StatusBadRequest)\r\n\t\treturn\r\n\t}\r\n\tvar all []Article\r\n\tfor rows.Next() {\r\n\t\tvar article Article\r\n\t\trows.Scan(&article.ID, &article.Title, &article.Subtitle, &article.Content, &article.CreationTimestamp)\r\n\t\tall = append(all, article)\r\n\t}\r\n\tpeopleBytes, err := json.MarshalIndent(all, \"\", \"\\t\")\r\n\tif err != nil {\r\n\t\tw.WriteHeader(http.StatusInternalServerError)\r\n\t\tw.Write([]byte(err.Error()))\r\n\t\treturn\r\n\t}\r\n\tw.Header().Set(\"Content-Type\", \"application/json\")\r\n\tw.WriteHeader(http.StatusOK)\r\n\tw.Write(peopleBytes)\r\n}", "func (*HttpParentProxys) GetPath() string { return \"/api/objects/http/parent_proxy/\" }", "func switchRouter(defaultHandler http.Handler, proxySrv *pServer.HttpServer) func(config dynamic.Configuration) {\n\treturn func(config dynamic.Configuration) {\n\t\tlog.Info(\"===Starting SwitchRouter====\")\n\t\trouterTemp, err := router.NewRouter()\n\t\tif err != nil {\n\t\t\tlog.Info(\"Failed to create router \", err)\n\t\t\t// return nil, err\n\t\t}\n\t\tlog.Infof(\"buildHandler : %v \\n\", config.Routers)\n\t\tfor name, value := range config.Routers {\n\t\t\tlog.Infof(\"Create Hypercloud proxy based on %v: %v \\n\", name, value)\n\t\t\tbackURL, err := url.Parse(value.Server)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(errors.Wrapf(err, \"URL Parsing failed for: %s\", value.Server))\n\t\t\t}\n\t\t\tdhconfig := &proxy.Config{\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t\tCipherSuites: crypto.DefaultCiphers(),\n\t\t\t\t},\n\t\t\t\tHeaderBlacklist: []string{\"X-CSRFToken\"},\n\t\t\t\tEndpoint: backURL,\n\t\t\t}\n\t\t\tdhproxy := proxy.NewProxy(dhconfig)\n\t\t\terr = routerTemp.AddRoute(value.Rule, 0, http.StripPrefix(value.Path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\ttoken := r.Header.Clone().Get(\"Authorization\")\n\t\t\t\ttemp := strings.Split(token, \"Bearer \")\n\t\t\t\tif len(temp) > 1 {\n\t\t\t\t\ttoken = temp[1]\n\t\t\t\t} else {\n\t\t\t\t\ttoken = temp[0]\n\t\t\t\t}\n\t\t\t\t// NOTE: query에 token 정보가 있을 시 해당 token으로 설정\n\t\t\t\tqueryToken := r.URL.Query().Get(\"token\")\n\t\t\t\tif queryToken != \"\" && token == \"\" {\n\t\t\t\t\tr.URL.Query().Del(\"token\")\n\t\t\t\t\ttoken = queryToken\n\t\t\t\t}\n\t\t\t\tr.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", token))\n\t\t\t\tdhproxy.ServeHTTP(w, r)\n\t\t\t})))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"failed to put proxy handler into Router\", err)\n\t\t\t}\n\t\t}\n\t\terr = routerTemp.AddRoute(\"PathPrefix(`/api/console/dynamic`)\", 0, http.HandlerFunc(\n\t\t\tfunc(rw http.ResponseWriter, r *http.Request) {\n\t\t\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\t\terr := json.NewEncoder(rw).Encode(config)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.NotFound(rw, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t},\n\t\t))\n\t\tif err != nil {\n\t\t\tlog.Error(\"/api/k8sAll/ has a problem\", err)\n\t\t}\n\n\t\terr = routerTemp.AddRoute(\"PathPrefix(`/`)\", 0, defaultHandler)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to put hypercloud proxy\", err)\n\t\t\t// return nil, err\n\t\t}\n\n\t\tlog.Info(\"===End SwitchRouter ===\")\n\t\tlog.Info(\"Call updateHandler --> routerTemp.Router\")\n\t\t// olderSrv:=proxySrv.Handler.Switcher.GetHandler()\n\n\t\tif proxySrv.Switcher.GetHandler() == nil {\n\t\t\tproxySrv.Switcher.UpdateHandler(http.NotFoundHandler())\n\t\t}\n\n\t\tproxySrv.Switcher.UpdateHandler(routerTemp)\n\n\t}\n}", "func RunGateway(address, confPath string, s *stat.Statistics) error {\r\n\tr := mux.NewRouter()\r\n\tr.Methods(http.MethodGet).Path(uploadBinPath).HandlerFunc(getFileUploadHandler(os.Args[0]))\r\n\tr.Methods(http.MethodGet).Path(uploadConfPath).HandlerFunc(getFileUploadHandler(confPath))\r\n\tr.Methods(http.MethodGet).Path(internalStatus).HandlerFunc(getServerStatus(s))\r\n\tr.Methods(http.MethodGet).Path(client + \"/{id}\").HandlerFunc(getClient)\r\n\tr.Methods(http.MethodPost).Path(client).HandlerFunc(insertClient)\r\n\tr.Methods(http.MethodGet).Path(client).HandlerFunc(getClients)\r\n\tr.Methods(http.MethodGet).Path(checkKeyURL).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\tp, err := getClientPermission(r.URL.Query().Get(\"key\"))\r\n\t\tif err != nil {\r\n\t\t\thttpError{http.StatusForbidden, err}.ServeHTTP(w, r)\r\n\t\t} else {\r\n\t\t\tif d, e := json.Marshal(p); e == nil {\r\n\t\t\t\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\r\n\t\t\t\tw.Header().Add(\"Content-Type\", \"application/json\")\r\n\t\t\t\tw.WriteHeader(http.StatusOK)\r\n\t\t\t\tw.Write(d)\r\n\t\t\t} else {\r\n\t\t\t\thttpError{http.StatusInternalServerError, errors.New(\"\")}.ServeHTTP(w, r)\r\n\t\t\t}\r\n\t\t}\r\n\t})\r\n\tr.Methods(http.MethodGet).Path(limits).HandlerFunc(getLimits)\r\n\tr.Methods(http.MethodPut, http.MethodPost).Path(limits).HandlerFunc(putLimitsHandler)\r\n\tr.Methods(http.MethodPost).Path(perm).HandlerFunc(addPerm)\r\n\tr.Use(mux.CORSMethodMiddleware(r))\r\n\tmaxRequestSize, err := strconv.ParseInt(cf.GetConfigValueOrDefault(\"MaxPacketSize\", \"128\"), 10, 32)\r\n\tif err != nil {\r\n\t\tmaxRequestSize = 128 * 1024 // 128 KB\r\n\t} else {\r\n\t\tmaxRequestSize *= 1024 // n KB\r\n\t}\r\n\tr.Use(\r\n\t\tfunc(next http.Handler) http.Handler {\r\n\t\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n\t\t\t\tif r.ContentLength < 0 || r.ContentLength > maxRequestSize {\r\n\t\t\t\t\thttpError{statusCode: http.StatusRequestEntityTooLarge, err: fmt.Errorf(\"Request more than %d\", maxRequestSize)}.ServeHTTP(w, r)\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\tnext.ServeHTTP(w, r)\r\n\t\t\t})\r\n\t\t})\r\n\tif pathToWeb, err := cf.GetConfigValue(\"PathToWeb\"); err == nil {\r\n\t\tvar expire time.Duration\r\n\t\tif expireDuration, err := strconv.ParseInt(cf.GetConfigValueOrDefault(\"ExpireMapCache\", \"0\"), 10, 32); err != nil {\r\n\t\t\texpire = 0\r\n\t\t} else {\r\n\t\t\texpire = time.Duration(expireDuration) * time.Second\r\n\t\t}\r\n\t\tr.HandleFunc(mapURL+\"/{z}/{x}/{y}\", getMapBoxHandler(pathToWeb+\"maps\",\r\n\t\t\t\"https://api.tiles.mapbox.com/v4/mapbox.streets/%s/%s/%s.png?access_token=%s\",\r\n\t\t\tmapBoxToken, expire)).Methods(http.MethodGet, http.MethodOptions)\r\n\r\n\t\tr.Methods(http.MethodGet).PathPrefix(\"/\").Handler(http.StripPrefix(\"\", http.FileServer(http.Dir(pathToWeb+\"build/\"))))\r\n\t}\r\n\tr.MethodNotAllowedHandler = httpError{err: errors.New(\"Method not allowed. Sorry\"), statusCode: http.StatusMethodNotAllowed}\r\n\tr.NotFoundHandler = httpError{err: errors.New(\"Method not exist. Sorry\"), statusCode: http.StatusNotExtended}\r\n\tgateway := http.Server{\r\n\t\tHandler: r,\r\n\t\tAddr: address,\r\n\t\tReadTimeout: 60 * time.Second,\r\n\t}\r\n\tcert, err := cf.GetConfigValue(\"CertificatePath\")\r\n\tkey, e := cf.GetConfigValue(\"PrivateKeyPath\")\r\n\tif err == nil && e == nil {\r\n\t\tlog.Info(\"Start https gateway on \", address)\r\n\t\treturn gateway.ListenAndServeTLS(cert, key)\r\n\t}\r\n\tlog.Info(\"Start http gateway on \", address)\r\n\treturn gateway.ListenAndServe()\r\n}", "func main() {\n\tr := gin.New()\n\tr.Use(cors.Default())\n\n\t//r.GET(\"/email\", ctrl.GenEmail)\n\tr.GET(\"/gentax\", ctrl.GenTaxData)\n\n\tr.Run(\":8099\")\n}", "func init() {\n//\tvar _r = net.GetRouter()\n//\tvar r = _r.PathPrefix(\"/v1\").Subrouter()\n\n var r = net.GetRouter()\n\t//route for test\n\t log.Print(\"cz init net_v1\")\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBGettokenizedcards, nil)).Methods(\"GET\") //logicbusiness.go\n r.Handle(\"/v3/processpayment\", netHandle(v4handleDBProcesspayment, nil)).Methods(\"GET\") //logicbusiness.go \n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBGeneratetokenized, nil)).Methods(\"GET\") //logicbusiness.go\n\tr.Handle(\"/v3/fetchtokenizedcards\", netHandle(handleDBPostGettokenizedcards, nil)).Methods(\"POST\") //logicbusiness.go\n\tr.Handle(\"/v3/processpayment\", netHandle(v4handleDBPostProcesspayment, nil)).Methods(\"POST\") //logicbusiness.go \t \n\n\tr.Handle(\"/v3/generatetokenized\", netHandle(handleDBPostGeneratetokenized, nil)).Methods(\"POST\") //logicbusiness.go\n\n\t \n}", "func HandlePerson(w http.ResponseWriter, r *http.Request) {\n\tkeys := r.URL.Query()[\"id\"]\n\tpersonID := keys[0]\n\n\ttmpl := template.Must(template.ParseFiles(\"views/detail-page.html\"))\n\tvar page model.DetailPageResponse\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tperson, pErr := model.GetInitialPerson(lib.BaseURL+\"people/\"+personID, &wg)\n\tif pErr != nil {\n\t\tfmt.Println(pErr.Error())\n\t}\n\twg.Wait()\n\n\tfmt.Println(\"person\", person)\n\tpage.PageTitle = \"Person\"\n\tpage.MainCard.Title = \"Name: \" + person.Name\n\tpage.MainCard.Body1 = \"Born: \" + person.BirthYear\n\tpage.MainCard.Body2 = \"Gender: \" + person.Gender\n\tpage.MainCard.Body3 = \"Height: \" + person.Height + \" CM\"\n\tpage.MainCard.Body4 = \"Mass: \" + person.Mass + \" KG\"\n\tpage.MainCard.Body5 = \"Eyes: \" + person.EyeColor + \" eyes\"\n\n\thomeworld, hErr := person.GetHomeworld()\n\tif hErr != nil {\n\t\tfmt.Println(hErr.Error())\n\t}\n\tpage.MainCard.SubTitle = \"Homeworld: \" + homeworld.Name\n\tfmt.Println(\"Homeworld\", homeworld)\n\n\t// vehicles\n\tif len(person.Vehicles) > 0 {\n\t\tvehicleChannel := make(chan []model.Vehicle)\n\t\tgo person.GetVehicles(vehicleChannel)\n\t\tvehicles := <-vehicleChannel\n\t\tpage.Cards1 = make([]model.SubCard, 0)\n\t\tfor _, vehicle := range vehicles {\n\t\t\tpage.Cards1 = append(page.Cards1, model.GetVehicleCard(vehicle))\n\t\t}\n\t}\n\n\tif len(person.Species) > 0 {\n\t\tspeciesChannel := make(chan []model.Species)\n\t\tgo person.GetSpecies(speciesChannel)\n\t\tspecies := <-speciesChannel\n\t\tpage.Cards2Title = \"Species\"\n\t\tpage.Cards2 = make([]model.SubCard, 0)\n\t\tfor _, specie := range species {\n\t\t\tpage.Cards2 = append(page.Cards2, model.GetSpeciesCard(specie))\n\t\t}\n\t}\n\n\t// starships\n\tif len(person.Starships) > 0 {\n\t\tstarshipChannel := make(chan []model.Starship)\n\t\tgo person.GetStarships(starshipChannel)\n\t\tstarships := <-starshipChannel\n\t\tpage.Cards3Title = \"Starships\"\n\t\tpage.Cards3 = make([]model.SubCard, 0)\n\t\tfor _, ship := range starships {\n\t\t\tpage.Cards3 = append(page.Cards3, model.GetStarshipCard(ship))\n\t\t}\n\t}\n\n\ttmpl.Execute(w, page)\n}", "func API(g *gin.Engine) {\n\tcatController := controllers.NewCat()\n\tgoodsController := controllers.NewGoods()\n\tgoodsGroupController := controllers.NewGoodsGroup()\n\tgoodsBrandController := controllers.NewGoodsBrand()\n\tgoodsCategoryController := controllers.NewGoodsCategory()\n\tgoodsSkuController := controllers.NewGoodsSku()\n\n\tapi := g.Group(\"/api\")\n\n\tv1 := api.Group(\"/v1\")\n\t{\n\t\tv1.GET(\"/\", catController.Home)\n\n\t\tv1.GET(\"/user/:name/:action\", func(c *gin.Context) {\n\t\t\tname := c.Param(\"name\")\n\t\t\taction := c.Param(\"action\")\n\t\t\tmessage := name + \" is \" + action\n\t\t\tc.String(http.StatusOK, message)\n\t\t})\n\t}\n\n\tgoods := v1.Group(\"/goods\")\n\t{\n\t\tgoods.GET(\"\", goodsController.Home)\n\t}\n\n\tgoodsGroup := v1.Group(\"/goods/group\")\n\t{\n\t\tgoodsGroup.GET(\"\", goodsGroupController.Home)\n\t}\n\n\tgoodsBrand := v1.Group(\"/goods/brand\")\n\t{\n\t\tgoodsBrand.GET(\"\", goodsBrandController.Home)\n\t}\n\n\tgoodsCategory := v1.Group(\"/goods/category\")\n\t{\n\t\tgoodsCategory.GET(\"\", goodsCategoryController.Home)\n\t}\n\n\tgoodsSku := v1.Group(\"/goods/sku\")\n\t{\n\t\tgoodsSku.GET(\"\", goodsSkuController.Home)\n\t}\n\n}", "func MakeMux(_ context.Context, endpoint Endpoints, authMethod domain.AuthHandler, logger log.Logger) http.Handler {\n var kt keytab.Keytab\n \n var krbconfig *service.Config\n krbconfig = nil\n //ktpath:=\"/home/build/file.keytab\"\n ktpath:=\"\"\n if ktpath != \"\" {\n kt, _ = keytab.Load(\"/home/build/file.keytab\")\n krbconfig = service.NewConfig(kt)\n }\n\n options := []httptransport.ServerOption{\n httptransport.ServerErrorEncoder(AuthErrorEncoder),\n httptransport.ServerErrorLogger(logger),\n }\n\n r := mux.NewRouter()\n\n addEndpoint(r, \"POST\",\"/items/add\",endpoint.AddItemEndpoint, DecodeAddItemRequest, EncodeStringResponse, logger, authMethod ,krbconfig)\n addEndpoint(r, \"DELETE\",\"/items/{id}\",endpoint.DelItemEndpoint, DecodeDelItemRequest, EncodeStringResponse, logger, authMethod, krbconfig)\n\n \n r.Methods(\"POST\").Path(\"/auth\").Handler(httptransport.NewServer(\n endpoint.AuthEndpoint,\n DecodeAuthRequest,\n EncodeAuthResponse,\n options...,\n ))\n\n r.Methods(\"GET\").Path(\"/items/get/{type}/{id}\").Handler(httptransport.NewServer(\n infrastructure.MakeSecureEndpoint(endpoint.GetItemEndpoint, authMethod),\n DecodeGetItemRequest,\n EncodeItemResponse,\n append(options, httptransport.ServerBefore(gokitjwt.HTTPToContext()))...,\n ))\n\n r.Methods(\"GET\").Path(\"/metrics\").Handler(promhttp.Handler())\n return r\n}", "func innerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\te.Register(register)\n\tg := e.Group(\"/x/job/creative\")\n\t{\n\t\tg.GET(\"/test\", sendMsg)\n\t}\n}", "func init() {\n\troot := controllers.Registry\n\tvar ok bool\n\tvar stock *controllers.Group\n\tstock, ok = root.GetGroup(\"/stock\")\n\tif !ok {\n\t\tstock = root.AddGroup(\"/stock\")\n\t}\n\tvar barcode *controllers.Group\n\tbarcode, ok = stock.GetGroup(\"/barcode\")\n\tif !ok {\n\t\tbarcode = stock.AddGroup(\"/barcode\")\n\t}\n\tif barcode.HasController(http.MethodGet, \"/\") {\n\t\tbarcode.ExtendController(http.MethodPost, \"/\", A)\n\t} else {\n\t\tbarcode.AddController(http.MethodPost, \"/\", A)\n\t}\n}", "func handleRequests() {\n\trouter := mux.NewRouter().StrictSlash(true)\n\tsubRouter := router.PathPrefix(\"/nobel/winners\").Subrouter()\n\n\t// Routes consist of a path and a handler function.\n\tsubRouter.HandleFunc(\"/fetch/all\", getNobelWinnersList).Methods(\"GET\")\n\tsubRouter.HandleFunc(\"/fetch/{id}\", getNobelWinnersByID).Methods(\"GET\")\n\n\tlog.Print(\"Listening port 8081...\")\n\t// Bind to a port and pass our router in\n\tlog.Fatal(http.ListenAndServe(\":8081\", router))\n}", "func main() {\n\n\t// use custom handler\n\n\txhandler := routes.RegexpHandler{}\n\n\txhandler.HandleRegexp(\"/abc\\\\=.+\", handleAbc)\n\n\txhandler.HandleRegexp(\"/\", handleRoot)\n\n\thttp.Handle(\"/\", xhandler)\n\n\t// use net/http handler\n\n\thttp.HandleFunc(\"/zzz/\", handleSpec)\n\n\thttp.HandleFunc(\"/sublvl\", func(w http.ResponseWriter, rq *http.Request) {\n\t\thandleRoot(w, rq)\n\t})\n\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n}", "func (s *server) routes() {\n\ts.router.HandleFunc(\"/payments\", s.paymentHandler())\n}", "func apihandler(w http.ResponseWriter, r *http.Request) {\n\tcatalogMatch := catalogRequestRegex.FindStringSubmatch(r.RequestURI)\n\tcoreMatch := coreRequestRegex.FindStringSubmatch(r.RequestURI)\n\n\tif len(catalogMatch) == 0 && len(coreMatch) == 0 {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(fmt.Sprintf(\"unexpected request %s %s doesn't match %q or %q\", r.Method, r.RequestURI, catalogRequestRegex, coreRequestRegex)))\n\t\treturn\n\t}\n\n\tif r.Method != http.MethodGet {\n\t\t// Anything more interesting than a GET, i.e. it relies upon server behavior\n\t\t// probably should be an integration test instead\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(fmt.Sprintf(\"unallowed method for request %s %s\", r.Method, r.RequestURI)))\n\t\treturn\n\t}\n\n\tvar match string\n\tif len(catalogMatch) > 0 {\n\t\tmatch = filepath.Join(\"catalog\", catalogMatch[1])\n\t} else {\n\t\tmatch = filepath.Join(\"core\", coreMatch[1])\n\t}\n\n\trelpath, err := url.PathUnescape(match)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(fmt.Sprintf(\"could not unescape path %s (%s)\", match, err)))\n\t\treturn\n\t}\n\tresponseFile := filepath.Join(\"responses\", relpath+\".json\")\n\t_, response, err := test.GetTestdata(responseFile)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(fmt.Sprintf(\"request %s has no matching testdata at %s (%s)\", r.RequestURI, responseFile, err)))\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(response)\n}", "func (c *controller) pipeline(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase http.MethodGet:\n\t\t_, err := fmt.Fprintf(w, \"please POST JSON to this endpoint!\\n\")\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"unable to write response to GET request: %s\", err.Error())\n\t\t}\n\tcase http.MethodHead:\n\t\tlogger.Info(\"HEAD Todo...\")\n\tcase http.MethodPost:\n\t\tc.handlePostRequest(r, w)\n\tdefault:\n\t\tlogger.Errorf(\"unsupported method %s for %s\", r.Method, c.path)\n\t\thttp.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)\n\t}\n}", "func handleRoot(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"hello from admission webhook server , you have hit : %q\", html.EscapeString(r.URL.Path))\n}", "func (h *Handler) serveDBUsers(w http.ResponseWriter, r *http.Request) {}", "func (r *Router) Setup(rg *gin.RouterGroup) {\n\trg.GET(\"/transfersInfo\", r.GetTransfersInfo)\n\trg.PUT(fmt.Sprintf(\"/files/:%s/transfer\", ParamFileID), r.CreateExternalShareRequest)\n\n\trg.GET(fmt.Sprintf(\"/users/:%s/canApproveToUser/:approverID\", ParamUserID), r.CanApproveToUser)\n\trg.GET(fmt.Sprintf(\"/users/:%s/approverInfo\", ParamUserID), r.GetApproverInfo)\n}", "func handleGetRequest(w http.ResponseWriter, r *http.Request) {\n\tapiPrefix := \"/api/\"\n\tmenuID := r.URL.Path[len(apiPrefix):]\n\tif menuID == \"\" {\n\t\thandleGetAllMenus(w, r)\n\t} else {\n\t\thandleGetMenu(w, r, menuID)\n\t}\n}", "func (app *App) retrieveHandler(w http.ResponseWriter, r *http.Request) {\n\tbaseErr := \"retrieveHandler fails: %v\"\n\n\tid, err := app.assets.Tokens.RetrieveAccountIDFromRequest(r.Context(), r)\n\tif err != nil {\n\t\tlog.Printf(baseErr, err)\n\t\tswitch {\n\t\tcase errors.Is(err, tokens.AuthHeaderError):\n\t\t\tapi.Error2(w, api.AuthHeaderError)\n\t\tcase errors.Is(err, tokens.ErrDoesNotExist):\n\t\t\tapi.Error2(w, api.NotExistError)\n\t\tdefault:\n\t\t\tapi.Error2(w, api.DatabaseError)\n\t\t}\n\t\treturn\n\t}\n\n\t// todo (rr): we need one query for retrieve account info\n\taccount, err := app.RetrieveByID(r.Context(), id)\n\tif err != nil {\n\t\tlog.Printf(baseErr, err)\n\t\tapi.Error2(w, api.DatabaseError)\n\t\treturn\n\t}\n\n\tapi.Response(w, account)\n}", "func webserver(gos *Gossiper, UIPort string) {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/nodes\", func(w http.ResponseWriter, r *http.Request) {\n\t\tnodeHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/messages\", func(w http.ResponseWriter, r *http.Request) {\n\t\tmessageHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/users\", func(w http.ResponseWriter, r *http.Request) {\n\t\tusersHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/private\", func(w http.ResponseWriter, r *http.Request) {\n\t\tprivateHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/id\", func(w http.ResponseWriter, r *http.Request) {\n\t\tidHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/round\", func(w http.ResponseWriter, r *http.Request) {\n\t\troundHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/upload\", func(w http.ResponseWriter, r *http.Request) {\n\t\tuploadHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/download\", func(w http.ResponseWriter, r *http.Request) {\n\t\tdownloadHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/search\", func(w http.ResponseWriter, r *http.Request) {\n\t\tsearchHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/fileSearched\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfileSearchedHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/confirmed\", func(w http.ResponseWriter, r *http.Request) {\n\t\tconfirmedHandler(w, r, gos)\n\t})\n\tmux.HandleFunc(\"/consensus\", func(w http.ResponseWriter, r *http.Request) {\n\t\tconsensusHandler(w, r, gos)\n\t})\n\tmux.Handle(\"/\", http.FileServer(http.Dir(DIR)))\n\n\tlog.Printf(\"Serving %s on HTTP port: %s\\n\", DIR, UIPort)\n\tlog.Fatal(http.ListenAndServe(\":\"+UIPort, mux))\n}", "func (network *Network) HTTPhandler(w http.ResponseWriter, r *http.Request){\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tbody, error := ioutil.ReadAll(r.Body) // Read Request\n\t\tdefer r.Body.Close() // Always CLOSE.\n\t\t// Check for errors or if body is empty.\n\t\tif error != nil || removeQuotationMarks(string(body)) == \"\" {\n\t\t\thttp.Error(w, \"ERROR\", http.StatusBadRequest)\n\t\t\tfmt.Println(\"Error when POST\")\n\t\t} else{\n\t\t\t// Same as in Cli.go Store\n\t\t\thashedFileString := NewKademliaIDFromData(string(body))\n\t\t\tnetwork.Store([]byte(body),hashedFileString)\n\t\t\thashSuffix := hashedFileString.String()\n\n\t\t\tmessage := map[string]string{ hashSuffix: string(body)} // JSON DATA FORMAT\n\t\t\tjsonValue,_ := json.Marshal(message)\n\n\t\t\tw.Header().Set(\"Location\", URLprefix+hashSuffix)\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\t\tw.WriteHeader(http.StatusCreated)\t// Status 201 as detailed\n\n\t\t\tw.Write(jsonValue)\n\t\t\tfmt.Println(\"HTTP Data Written. Hash = \", hashSuffix )\n\t\t}\n\tcase \"GET\":\n\t\t// Checks if there is something after the prefix. /objects/XXXXXXXXXXXXXX\n\t\tURLcomponents := strings.Split(r.URL.Path, \"/\")\t// [ \"\", \"objects\", \"hash\" ]\n\t\thashValue := URLcomponents[2]\n\t\t// Check if there is a hashvalue of correct size.\n\t\tif(len(hashValue) != 40){\n\t\t\thttp.Error(w, \"ERROR\", http.StatusLengthRequired)\n\t\t\tfmt.Println(\"Error when GET \", hashValue, \" is not of correct length. (40)\")\n\t\t}else{\n\t\t\t\t// Same as in Cli.go Get\n\t\t\t\thash := NewKademliaID(hashValue)\n\t\t\t\tdata, nodes := network.DataLookup(hash)\n\t\t\t\tif data != nil {\n\t\t\t\t\t// If data is not nil, send OK status and write.\n\t\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t\tw.Write(data)\n\t\t\t\t\tfmt.Println(\"HTTP Data Read. Input was = \", string(data) )\n\t\t\t\t} else if len(nodes) > 0{\n\t\t\t\t\thttp.Error(w, \"ERROR\", http.StatusNotFound)\n\t\t\t\t\tfmt.Println(\"Error when GET - DataLookUP (Length)\")\n\t\t\t\t} else {\n\t\t\t\t\thttp.Error(w, \"ERROR\", http.StatusNoContent)\n\t\t\t\t\tfmt.Println(\"Error when GET - DataLookUP\")\n\t\t\t\t}\n\t\t}\n\tdefault:\n\t\thttp.Error(w, \"Wrong. Use POST or GET\", http.StatusMethodNotAllowed)\n\t}\n}", "func (m *Messenger) handle(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\tm.verifyHandler(w, r)\n\t\treturn\n\t}\n\n\tvar rec Receive\n\n\t// consume a *copy* of the request body\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tr.Body = ioutil.NopCloser(bytes.NewBuffer(body))\n\n\terr := json.Unmarshal(body, &rec)\n\tif err != nil {\n\t\terr = xerrors.Errorf(\"could not decode response: %w\", err)\n\t\tfmt.Println(err)\n\t\tfmt.Println(\"could not decode response:\", err)\n\t\trespond(w, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif rec.Object != \"page\" {\n\t\tfmt.Println(\"Object is not page, undefined behaviour. Got\", rec.Object)\n\t\trespond(w, http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\n\tif m.verify {\n\t\tif err := m.checkIntegrity(r); err != nil {\n\t\t\tfmt.Println(\"could not verify request:\", err)\n\t\t\trespond(w, http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t}\n\n\tm.dispatch(rec)\n\n\trespond(w, http.StatusAccepted) // We do not return any meaningful response immediately so it should be 202\n}", "func outerRouter(e *bm.Engine) {\n\te.Ping(ping)\n\tr := e.Group(\"/x/resource\")\n\t{\n\t\tr.GET(\"/plugin\", plugin)\n\t\tr.GET(\"/sidebar\", authSvc.GuestMobile, sidebar)\n\t\tr.GET(\"/topbar\", topbar)\n\t\tr.GET(\"/abtest\", abTest)\n\t\tr.GET(\"/abtest/v2\", abTestV2)\n\t\tr.GET(\"/abtest/abserver\", authSvc.GuestMobile, abserver)\n\t\tm := r.Group(\"/module\")\n\t\t{\n\t\t\tm.POST(\"\", module)\n\t\t\tm.POST(\"/list\", list)\n\t\t}\n\t\tg := r.Group(\"/guide\", authSvc.GuestMobile)\n\t\t{\n\t\t\tg.GET(\"/interest\", interest)\n\t\t\tg.GET(\"/interest2\", interest2)\n\t\t}\n\t\tr.GET(\"/static\", getStatic)\n\t\tr.GET(\"/domain\", domain)\n\t\tr.GET(\"/broadcast/servers\", serverList)\n\t\tr.GET(\"/white/list\", whiteList)\n\t\tr.GET(\"/show/tab\", authSvc.GuestMobile, tabs)\n\t}\n\tv := e.Group(\"/x/v2/version\")\n\t{\n\t\tv.GET(\"\", getVersion)\n\t\tv.GET(\"/update\", versionUpdate)\n\t\tv.GET(\"/update.pb\", versionUpdatePb)\n\t\tv.GET(\"/so\", versionSo)\n\t\tv.GET(\"/rn/update\", versionRn)\n\t}\n\tp := e.Group(\"/x/v2/param\", authSvc.GuestMobile)\n\t{\n\t\tp.GET(\"\", getParam)\n\t}\n\tn := e.Group(\"/x/v2/notice\", authSvc.GuestMobile)\n\t{\n\t\tn.GET(\"\", getNotice)\n\t}\n\ts := e.Group(\"/x/v2/splash\")\n\t{\n\t\ts.GET(\"\", splashs)\n\t\ts.GET(\"/birthday\", birthSplash)\n\t\ts.GET(\"/list\", authSvc.GuestMobile, splashList)\n\t}\n\ta := e.Group(\"/x/v2/audit\")\n\t{\n\t\ta.GET(\"\", audit)\n\t}\n}", "func (g *GRPC) handler() http.Handler {\n\treturn http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tswitch r.Header.Get(\"Content-Type\") {\n\t\t\tcase \"application/grpc\":\n\t\t\t\tif r.ProtoMajor == 2 {\n\t\t\t\t\tg.serv.ServeHTTP(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thttp.Error(w, \"'application/grpc' content arrived, but HTTP protocol was not HTTP 2\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\tcase \"application/grpc-gateway\", \"application/jsonpb\":\n\t\t\t\tif g.gatewayHandler == nil {\n\t\t\t\t\thttp.Error(w, \"application/grpc-gateway received, but server is not setup for REST\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// g.httpRESTHandler(g.gatewayHandler).ServeHTTP(w, r)\n\t\t\t\tg.gatewayHandler.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\t// Special case where they are looking for the REST swagger docs.\n\t\t\t\tif strings.HasPrefix(r.URL.Path, \"/swagger-ui/\") {\n\t\t\t\t\tg.httpRESTHandler(g.gatewayHandler).ServeHTTP(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif g.httpMux == nil {\n\t\t\t\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tg.httpMux.ServeHTTP(w, r)\n\t\t\t}\n\t\t},\n\t)\n}", "func innerRouter(e *bm.Engine) {\n\t// health check\n\te.Ping(ping)\n\tspy := e.Group(\"/x/admin/spy\", vfySvc.Verify)\n\n\tscore := spy.Group(\"/score\")\n\tscore.GET(\"/query\", userInfo)\n\tscore.GET(\"/record\", historyPage)\n\tscore.POST(\"/base/reset\", resetBase)\n\tscore.POST(\"/base/refresh\", refreshBase)\n\tscore.POST(\"/event/reset\", resetEvent)\n\n\tspy.POST(\"/stat/clear\", clearCount)\n\n\tfactor := spy.Group(\"/factor\")\n\tfactor.GET(\"/list\", factors)\n\tfactor.POST(\"/add\", addFactor)\n\tfactor.POST(\"/modify\", updateFactor)\n\n\tspy.POST(\"/event/add\", addEvent)\n\tspy.POST(\"/event/modify\", updateEventName)\n\tspy.POST(\"/service/add\", addService)\n\tspy.POST(\"/group/add\", addGroup)\n\n\tsetting := spy.Group(\"/setting\")\n\tsetting.GET(\"/list\", settingList)\n\tsetting.POST(\"/add\", updateSetting)\n\n\tsin := spy.Group(\"/sin\")\n\tsin.POST(\"/state/update\", updateStatState)\n\tsin.POST(\"/quantity/update\", updateStatQuantity)\n\tsin.POST(\"/delete\", deleteStat)\n\tsin.POST(\"/remark/add\", addRemark)\n\tsin.GET(\"/remark/list\", remarkList)\n\tsin.GET(\"/page\", statPage)\n\n\tspy.GET(\"/report\", report)\n\n\tspyWithoutAuth := e.Group(\"/x/admin/spy/internal\")\n\tspyWithoutAuth.POST(\"/event/add\", addEvent)\n\tspyWithoutAuth.POST(\"/event/modify\", updateEventName)\n\n\tscoreWithoutAuth := spyWithoutAuth.Group(\"/score\")\n\tscoreWithoutAuth.GET(\"/query\", userInfo)\n\tscoreWithoutAuth.GET(\"/record\", historyPage)\n\tscoreWithoutAuth.POST(\"/base/reset\", resetBase)\n\tscoreWithoutAuth.POST(\"/base/refresh\", refreshBase)\n\tscoreWithoutAuth.POST(\"/event/reset\", resetEvent)\n\n\tfactorWithoutAuth := spyWithoutAuth.Group(\"/factor\")\n\tfactorWithoutAuth.GET(\"/list\", factors)\n\tfactorWithoutAuth.POST(\"/add\", addFactor)\n\tfactorWithoutAuth.POST(\"/modify\", updateFactor)\n}", "func UserCabV1Routes(router *gin.Engine) {\n\n loginRouter := router.Group(\"/v1/new\")\n {\n //for new user login\n loginRouter.POST(\"login\", newUserLogin)\n }\n\n\tuserRouter := router.Group(\"/v1/user\")\n\t{\n userRouter.Use(ValidateUserRequestAndFetchUser())\n\n //user can book a cab\n userRouter.POST(\"/book\", bookCab)\n\n //user's all past rides\n userRouter.GET(\"/rides\", getUserRides)\n }\n\n}", "func (rh *RegionHandler) NodeChangeHandler() {\n\t// log.Println(\"NodeChangeHandler started\")\n\tfor {\n\t\tncInfo := <-rh.RegionChange\n\n\t\tif ncInfo.PrevConn == nil && ncInfo.CurrConn == nil {\n\n\t\t\t// one node edge case: dump everything into primary\n\t\t\t// log.Println(\"one node edge case\")\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.BackupRegions {\n\t\t\t\trh.Regions[rid] = r \n\t\t\t\tr.SetReady()\n\t\t\t\tgo r.MaintainRegion()\n\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t}\n\t\t\t// log.Println(\"Number of reg handling: \")\n\t\t\trh.mux.Unlock()\n\n\n\t\t} else if ncInfo.Successor && ncInfo.Join {\n\n\t\t\t// onSuccessorJoin:\n\t\t\t// move regions on curr node that hash to curr region to joined node\n\t\t\t// log.Println(\"onSuccessorJoin\", ncInfo.Curr, ncInfo.Prev)\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trh.mux.RLock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id:rid, Foods:r.GetFood()}) \n\t\t\t}\n\t\t\trh.mux.RUnlock()\n\n\t\t\tconn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(conn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(conn)\n\t\t\t// \t_, err := regionClient.AddRegions(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// \t// conn := ncInfo.PrevConn\n\t\t\t// \t// _, err = regionClient.RemoveRegion(context.Background(), &region_pb.IdRegionRequest{Id: rid})\n\t\t\t// \t// if err != nil {\n\t\t\t// \t// \tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t// }\n\t\t\t// }\n\n\t\t} else if ncInfo.Successor && !ncInfo.Join {\n\n\t\t\t// onSuccessorLeave:\n\t\t\t// move regions on curr node that hash to curr region to new successor\n\t\t\t// log.Println(\"onSuccessorLeave\", ncInfo.Curr, ncInfo.Prev)\n\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trh.mux.RLock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id:rid, Foods:r.GetFood()}) \n\t\t\t}\n\t\t\trh.mux.RUnlock()\n\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\t\t\t// rh.mux.RLock()\n\t\t\t// for rid, r := range rh.Regions {\n\t\t\t// \tregionsCopy[rid] = r \n\t\t\t// }\n\t\t\t// rh.mux.RUnlock()\n\n\t\t\tconn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(conn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(conn)\n\t\t\t// \t_, err := regionClient.AddRegion(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Successor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// }\n\n\t\t} else if !ncInfo.Successor && ncInfo.Join {\n\n\t\t\t// on predecessor join:\n\t\t\t// remove regions on curr node that hash to prepredecessor\n\t\t\t// log.Println(\"on predecessor join\", ncInfo.Curr, ncInfo.Prev)\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, _ := range rh.BackupRegions {\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) != ncInfo.Curr {\n\t\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\t// remove region on successor for which now I'm backup\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\trmRegions := []*IdRegionRequest{}\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.Regions {\n\t\t\t\tlog.Println(\"Checking\", rid, rh.RegionHash[rid], rh.Router.Successor(rh.RegionHash[rid]), ncInfo.Curr, rh.Router.Hash)\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) == ncInfo.Curr {\n\t\t\t\t\t// regionsCopy[rid] = r\n\t\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id: rid, Foods:r.GetFood()}) \n\t\t\t\t\trmRegions = append(rmRegions, &IdRegionRequest{Id: rid})\n\t\t\t\t\tr.Quit <- true\n\t\t\t\t\tr.ClearAllBlobCache()\n\t\t\t\t\trh.BackupRegions[rid] = r\n\t\t\t\t\tdelete(rh.Regions, rid)\n\t\t\t\t\t// r.UnsetReady()\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\t// move regions that hash to joining node from curr node to joining node\n\t\t\t// remove regions on successor that hash to joining node\n\t\t\tsuccessorConn := rh.Router.GetSuccessor()\n\t\t\tPredcessorConn := rh.Router.GetPredecessor()\n\t\t\tregionClient := NewRegionClient(successorConn)\n\t\t\t_, err := regionClient.RemoveRegions(context.Background(), &RemoveRegionsRequest{Regions: rmRegions})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t}\n\t\t\tregionClient = NewRegionClient(PredcessorConn)\n\t\t\t_, err = regionClient.TransferPrimary(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t}\n\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(successorConn)\n\t\t\t// \t_, err := regionClient.RemoveRegion(context.Background(), &IdRegionRequest{Id: rid})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t// \t}\n\n\t\t\t// \tregionClient = NewRegionClient(PredcessorConn)\n\t\t\t// \t_, err = regionClient.TransferPrimary(context.Background(), &FoodRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor Join big no no: \", err)\n\t\t\t// \t}\n\t\t\t// \tr.UnsetReady()\n\t\t\t// }\n\n\t\t} else {\n\n\t\t\t// move regions that hashed to node that left to successor\n\t\t\t// log.Println(\"on predecessor leave\", ncInfo.Curr, ncInfo.Prev)\n\n\t\t\tregionsCopy := []*FoodRequest{}\n\t\t\t// regionsCopy := make(map[uint32]*RegionInfo)\n\n\t\t\trh.mux.Lock()\n\t\t\tfor rid, r := range rh.BackupRegions {\n\t\t\t\t// log.Println(\"Checking\", rid, rh.RegionHash[rid])\n\t\t\t\tif rh.Router.Successor(rh.RegionHash[rid]) == rh.Router.Hash {\n\t\t\t\t\t// log.Println(\"Moving\", rid, \"from bkup to prim\")\n\t\t\t\t\tregionsCopy = append(regionsCopy, &FoodRequest{Id: rid, Foods:r.GetFood()})\n\t\t\t\t\t//regionsCopy[rid] = r\n\t\t\t\t\trh.Regions[rid] = r\n\t\t\t\t\tr.SetReady()\n\t\t\t\t\tgo r.MaintainRegion()\n\t\t\t\t\tdelete(rh.BackupRegions, rid)\n\t\t\t\t}\n\t\t\t}\n\t\t\trh.mux.Unlock()\n\n\t\t\tsuccessorConn := rh.Router.GetSuccessor()\n\t\t\tregionClient := NewRegionClient(successorConn)\n\t\t\t_, err := regionClient.AddRegions(context.Background(), &AddRegionsRequest{Regions: regionsCopy})\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Predecessor leave big no no: \", err)\n\t\t\t}\n\t\t\t// for rid, r := range regionsCopy {\n\t\t\t// \tregionClient := NewRegionClient(successorConn)\n\t\t\t// \t_, err := regionClient.AddRegions(context.Background(), &AddRegionRequest{Id: rid, Foods: r.GetFood()})\n\t\t\t// \tif err != nil {\n\t\t\t// \t\tlog.Println(\"Predecessor leave big no no: \", err)\n\t\t\t// \t}\n\t\t\t// }\n\t\t}\n\t\t\n\t}\n}", "func igcHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tdecoder := json.NewDecoder(r.Body)\n\n\t\t// to map from \"url\": to \"<url>\"\n\t\turl := make(map[string]string)\n\t\terr := decoder.Decode(&url)\n\t\t// coulnd't parse POST data\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\ttrack, err := igc.ParseLocation(url[\"url\"])\n\t\t// coudln't get track from url, probably a bad URL in POST request\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t}\n\n\t\tid, err := tracks.add(Track{Hdate: track.Date, Pilot: track.Pilot, Glider: track.GliderType, GliderID: track.GliderID, TrackLength: track.Points[0].Distance(track.Points[len(track.Points)-1])})\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(id)\n\tcase \"GET\":\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tjson.NewEncoder(w).Encode(tracks.getIDs())\n\t}\n}" ]
[ "0.53979844", "0.5357035", "0.5331468", "0.52953714", "0.5275639", "0.5275639", "0.5273326", "0.5237795", "0.51973367", "0.51813775", "0.51783746", "0.5174104", "0.5167441", "0.5147928", "0.5087115", "0.5081987", "0.5057369", "0.5057227", "0.5027063", "0.50116813", "0.50044674", "0.500324", "0.49974245", "0.49969807", "0.49920073", "0.49579313", "0.49578744", "0.494567", "0.490699", "0.4895083", "0.48792246", "0.4877589", "0.48739782", "0.4873014", "0.4868166", "0.48260298", "0.4816153", "0.48159054", "0.4813349", "0.48112473", "0.4810802", "0.48100322", "0.480854", "0.4807178", "0.48012415", "0.47911042", "0.47902334", "0.47893718", "0.47772688", "0.47701362", "0.4760074", "0.47548148", "0.4754247", "0.4753336", "0.47480738", "0.47456327", "0.4745414", "0.47402242", "0.4739997", "0.47308955", "0.47274265", "0.47213674", "0.47203273", "0.47159365", "0.47130528", "0.47049743", "0.46981588", "0.46931884", "0.4690241", "0.46896067", "0.46866634", "0.46855405", "0.4685204", "0.46837443", "0.46828398", "0.46803135", "0.46768057", "0.46766266", "0.467629", "0.4674796", "0.46726385", "0.46714994", "0.46704465", "0.46703166", "0.4668746", "0.466807", "0.4666501", "0.46661836", "0.46608222", "0.46602854", "0.46593508", "0.46550843", "0.46548444", "0.46521056", "0.46513164", "0.46506625", "0.46425697", "0.4639545", "0.46315694", "0.4629042" ]
0.64442056
0
Save will convert the input interface (v) into a JSON formatted object on disk
func interfaceToFile(path string, structIn interface{}) error { // Create a lock and then defer the unlock until function exit filewritelock.Lock() defer filewritelock.Unlock() //Create os.File and defer close file, err := os.Create(string(path)) if err != nil { return err } defer file.Close() // Create a reader (via marshal) that we can use to copy into the writer reader, err := Marshal(structIn) if err != nil { return err } _, err = io.Copy(file, reader) return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Save(w io.Writer, v interface{}) error {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.WriteString(w, string(data))\n\treturn err\n}", "func Save(file string, v interface{}) error {\n\tf, err := gzipf.Create(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tenc := json.NewEncoder(f)\n\tenc.SetIndent(\"\", \" \")\n\treturn enc.Encode(v)\n}", "func Save(fromVar interface{}, toPath string) {\n\tdata, e := json.Marshal(fromVar)\n\terr.Panic(e)\n\te = ioutil.WriteFile(toPath, data, 0664)\n\terr.Panic(e)\n}", "func Save(path string, v interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.OpenFile(path, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\treturn formatter.Encode(file, v)\n}", "func Save(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tr, err := Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(f, r)\n\treturn err\n}", "func Save(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tr, err := Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(f, r)\n\treturn err\n}", "func Save(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tr, err := Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(f, r)\n\treturn err\n}", "func Save(path string, x interface{}) error {\n\tmtx.Lock()\n\tdefer mtx.Unlock()\n\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tdata, err := toJSON(x)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(file, data)\n\treturn err\n}", "func Save(name string, data interface{}) error {\n\tp := jsonPath(name)\n\tb, err := json.MarshalIndent(data, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(p, b, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"Saved %s\\n\", p)\n\treturn nil\n}", "func SaveJSON(f string, iface interface{}) error {\n\tif !PathExists(filepath.Dir(f)) {\n\t\treturn fmt.Errorf(\"Missing dir; %s\", f)\n\t}\n\n\tcontent, err := json.MarshalIndent(iface, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(f, content, 0644)\n}", "func (g *Generator) Save(w io.Writer) error {\n\tdata, err := json.MarshalIndent(g.spec, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (l Util) SaveJson(p string, value interface{}) error {\n\tbts, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(l.path(p), bts, os.ModePerm)\n}", "func Save(path string, v interface{}, opts Options) (err error) {\n\tvar (\n\t\tzw *lz4.Writer\n\t\tencoder *jsoniter.Encoder\n\t\th hash.Hash\n\t\tmw io.Writer\n\t\tprefix [prefLen]byte\n\t\toff, l int\n\t\tfile *os.File\n\t\ttmp = path + \".tmp.\" + cmn.GenTie()\n\t)\n\tif file, err = cmn.CreateFile(tmp); err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t\tif err != nil {\n\t\t\tos.Remove(tmp)\n\t\t}\n\t}()\n\tif opts.Signature {\n\t\toff = prefLen\n\t}\n\tif opts.Checksum {\n\t\th = xxhash.New64()\n\t\toff += h.Size()\n\t}\n\tif off > 0 {\n\t\tif _, err = file.Seek(int64(off), io.SeekStart); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif opts.Compression {\n\t\tif opts.Checksum {\n\t\t\tmw = io.MultiWriter(h, file)\n\t\t\tzw = lz4.NewWriter(mw)\n\t\t} else {\n\t\t\tzw = lz4.NewWriter(file)\n\t\t}\n\t\tencoder = jsoniter.NewEncoder(zw)\n\t} else {\n\t\tif opts.Checksum {\n\t\t\tmw = io.MultiWriter(h, file)\n\t\t\tencoder = jsoniter.NewEncoder(mw)\n\t\t} else {\n\t\t\tencoder = jsoniter.NewEncoder(file)\n\t\t}\n\t}\n\tencoder.SetIndent(\"\", \" \")\n\tif err = encoder.Encode(v); err != nil {\n\t\treturn\n\t}\n\tif opts.Compression {\n\t\t_ = zw.Close()\n\t}\n\tif opts.Signature {\n\t\tif _, err = file.Seek(0, io.SeekStart); err != nil {\n\t\t\treturn\n\t\t}\n\t\t// 1st 64-bit word\n\t\tcopy(prefix[:], signature)\n\t\tl = len(signature)\n\t\tcmn.Assert(l < prefLen/2)\n\t\tprefix[l] = version\n\n\t\t// 2nd 64-bit word as of version == 1\n\t\tvar packingInfo uint64\n\t\tif opts.Compression {\n\t\t\tpackingInfo |= 1 << 0\n\t\t}\n\t\tif opts.Checksum {\n\t\t\tpackingInfo |= 1 << 1\n\t\t}\n\t\tbinary.BigEndian.PutUint64(prefix[cmn.SizeofI64:], packingInfo)\n\n\t\t// write prefix\n\t\tfile.Write(prefix[:])\n\t}\n\tif opts.Checksum {\n\t\tif !opts.Signature {\n\t\t\tif _, err = file.Seek(0, io.SeekStart); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfile.Write(h.Sum(nil))\n\t}\n\tif err = file.Close(); err != nil {\n\t\treturn\n\t}\n\terr = os.Rename(tmp, path)\n\treturn\n}", "func Save(path string, v interface{}, opts Options) (err error) {\n\tvar (\n\t\tfile *os.File\n\t\ttmp = path + \".tmp.\" + cmn.GenTie()\n\t)\n\tif file, err = cmn.CreateFile(tmp); err != nil {\n\t\treturn\n\t}\n\tdefer func() {\n\t\t_ = file.Close()\n\t\tif err != nil {\n\t\t\tos.Remove(tmp)\n\t\t}\n\t}()\n\tif err = Encode(file, v, opts); err != nil {\n\t\treturn\n\t}\n\tif err = file.Close(); err != nil {\n\t\treturn\n\t}\n\terr = os.Rename(tmp, path)\n\treturn\n}", "func SaveFile(name string, v interface{}) error {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tp := filepath.Join(path, name)\n\terr = ioutil.WriteFile(p, data, 0740)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Save(path string, object interface{}) error {\n\tfile, err := os.Create(path)\n\tdefer file.Close()\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tencoder.Encode(object)\n\t}\n\treturn err\n}", "func (r *Recipe) Save(fname string) (err error) {\n\tb, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(fname, b, 0644)\n\treturn\n}", "func (app *service) Save(state State) error {\n\tjs, err := app.adapter.ToJSON(state)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchainHash := state.Chain()\n\tindex := state.Height()\n\tpath := filePath(chainHash, index)\n\treturn app.fileService.Save(path, js)\n}", "func (h *Homework) save() (err error) {\n\tbuf, err := json.MarshalIndent(h, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(h.path, buf, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Save(path string, object interface{}) error {\n\tfile, err := os.Create(path)\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tencoder.Encode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func (vc *VehicleContainer) SaveJSON(target string) (err error) {\n\tbuff, err := vc.MarshalJSON()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = os.WriteFile(target, buff, 0o666)\n\treturn\n}", "func (r *Recipes) Save() error {\n\tb, err := json.Marshal(r.values)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(\"recipes.json\", b, 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SaveToFile(fileName string, data interface{}) error {\n\tbytes, err := json.MarshalIndent(data, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(fileName, bytes, 0644)\n}", "func (tag *SwizzleTag) Save(file io.Writer) error {\n\tw := gzip.NewWriter(file)\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(tag)\n\tw.Close()\n\treturn err\n}", "func ToFile(path string, x interface{}) {\n\tbytes := ToJSON(x)\n\n\t// write byte array to file\n\tif err := ioutil.WriteFile(path, bytes, 0644); err != nil {\n\t\tlog.Fatalf(\"[common] error writing struct %T to file: %v\", x, err)\n\t}\n}", "func (o *Object) SaveToFile(filename string) {\n\tobjJson, _ := json.Marshal(o)\n\tioutil.WriteFile(filename, objJson, 0644)\n}", "func (fp *File) writeInterface(entry interface{}) error {\n\tdata, err := json.Marshal(entry)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata = append(data, byte('\\n'))\n\t_, err = fp.Writer.Write(data)\n\treturn err\n}", "func (app *service) Save(genesis Genesis) error {\n\tjs, err := app.adapter.ToJSON(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.fileService.Save(app.fileNameWithExt, js)\n}", "func save(object interface{}, c Configuration) error {\n\tfile, err := os.Create(c.StorageLocation + \"/index.gob\")\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tencoder.Encode(object)\n\t} else {\n\t\tpanic(err)\n\t}\n\n\tfile.Close()\n\treturn err\n}", "func (ns *NodeStore) save() error {\r\n\tb, err := json.Marshal(ns)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\terr = ioutil.WriteFile(\"nodestore.json\", b, 0660)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\treturn nil\r\n}", "func (ig *Instagram) Save() (string, error) {\n\n\tbytes, err := json.Marshal(&ig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(bytes), nil\n}", "func toJSON(v interface{}) string {\n\toutput, _ := json.Marshal(v)\n\treturn string(output)\n}", "func (self *JsonConfig) Save() (err error) {\n\tb, err := json.Marshal(self.Configurable.All())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := ioutil.WriteFile(self.Path, b, 0600); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (connection *Connection) Save(path string) error {\n\tjson, err := json.Marshal(connection)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(path, json, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (vr *vectorRenderer) Save(w io.Writer) error {\n\tvr.c.End()\n\t_, err := w.Write(vr.b.Bytes())\n\treturn err\n}", "func (c *ServiceController) Save() error {\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(c.filename, b, 0600)\n}", "func (ident *Identity) SaveJSON(path string) error {\n\tlogger.Info(\"Saving identity\")\n\n\tbs, err := ident.ToJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.WriteFile(path, bs, 0600)\n}", "func (c *ContainerBuilder) Save(writer io.Writer) error {\n\terr := json.NewEncoder(writer).Encode(c.Container)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (s *ServiceState) save() {\n\tlog.Lvl3(\"Saving service\")\n\tb, err := network.Marshal(s.Storage)\n\tif err != nil {\n\t\tlog.Error(\"Couldn't marshal service:\", err)\n\t} else {\n\t\terr = ioutil.WriteFile(s.path+\"/prifi.bin\", b, 0660)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Couldn't save file:\", err)\n\t\t}\n\t}\n}", "func (c *Controller) Save(name string, f file.Any) error {\n\tb, err := json.Marshal(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\tutil.Log(string(b))\n\n\tr := bytes.NewReader(b)\n\n\tinput := &s3.PutObjectInput{\n\t\tBody: aws.ReadSeekCloser(r),\n\t\tBucket: aws.String(c.bucket),\n\t\tKey: aws.String(name),\n\t\tServerSideEncryption: aws.String(\"AES256\"),\n\t}\n\n\tswitch f.(type) {\n\tcase file.BananasMon:\n\t\tinput.Tagging = aws.String(\"App Name=hit-the-bananas\")\n\tcase file.D2sVendorDays:\n\t\tinput.Tagging = aws.String(\"App Name=drive-2-sku\")\n\t}\n\n\tresult, err := c.c3svc.PutObject(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.verIDs[name] = result.VersionId\n\n\treturn nil\n}", "func (l Level) save(path string) error {\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0777)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open file to save level: %w\", err)\n\t}\n\tdefer f.Close()\n\tencoder := json.NewEncoder(f)\n\tencoder.SetIndent(\"\", \" \")\n\terr = encoder.Encode(l)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"save level: %w\", err)\n\t}\n\treturn nil\n}", "func toJson(v interface{}) string {\n\toutput, _ := json.Marshal(v)\n\treturn string(output)\n}", "func Save(jsonfile string, m map[string][]PimpMiner) {\n\tjson, err := json.Marshal(m)\n\tcheckErr(err)\n\tf, err := os.Create(jsonfile)\n\tcheckErr(err)\n\tdefer f.Close()\n\tout := []byte(PrettyPrint(string(json)))\n\tf.Write(out)\n}", "func Save(obj any, file string) error {\n\tfp, err := os.Create(file)\n\tdefer fp.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tbw := bufio.NewWriter(fp)\n\terr = Write(obj, bw)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\terr = bw.Flush()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}", "func (i *Index) SaveJSON() ([]byte, error) {\n\treturn json.Marshal(i.Objects)\n}", "func (p *ColorPlugin) Save() ([]byte, error) {\n\treturn json.Marshal(p)\n}", "func (m *FileBackend) Save(b BackendData) (err error) {\n\tvar f *os.File\n\tif f, err = os.OpenFile(m.path, os.O_RDWR, 0744); err != nil {\n\t\terr = fmt.Errorf(\"error opening json for saving FileBackend: %v\", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t// Set FileBackend index to 0\n\tif err = f.Truncate(0); err != nil {\n\t\terr = fmt.Errorf(\"error truncating FileBackend: %v\", err)\n\t\treturn\n\t}\n\n\t// Create flat store from store data\n\tfs := b.NewFlatRecords()\n\n\t// Encode flat store as JSON to disk\n\treturn json.NewEncoder(f).Encode(fs)\n}", "func Save() {\n\tdata := Savedata{\n\t\tName: GS.current.name,\n\t\tGamestate: GS.current,\n\t}\n\n\tf, err := json.MarshalIndent(data, \"\", \" \")\n\tcheck(err)\n\tioutil.WriteFile(\"data/savegame.json\", f, 0644)\n}", "func (m *Machine) Save(n string) error {\n\tf, err := os.Create(n)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create vm config file\")\n\t}\n\tdefer f.Close()\n\n\tif err := json.NewEncoder(f).Encode(m); err != nil {\n\t\treturn errors.Wrap(err, \"failed to serialize machine object\")\n\t}\n\n\treturn nil\n}", "func (d *Dirs) Save() {\n\tj, err := json.Marshal(*d)\n\tutils.HandleErr(err, \"marshal json\")\n\terr = ioutil.WriteFile(PathToFile, j, 0611)\n\tutils.HandleErr(err, \"write to file\")\n}", "func SaveJSON(filename string, thing interface{}, mode os.FileMode) error {\n\tdata, err := json.MarshalIndent(thing, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn SaveBinary(filename, data, mode)\n}", "func (r *Reserve) Save(s *Store) error {\n\tdata, _ := json.Marshal(s)\n\tif err := ioutil.WriteFile(r.path, data, 0644); err != nil {\n\t\treturn fmt.Errorf(\"Failed to set %s: %s\", r.name, err)\n\t}\n\treturn nil\n}", "func (p *ReminderPlugin) Save() ([]byte, error) {\n\treturn json.Marshal(p)\n}", "func (db *jsonDB) save() error {\n\tvar jsonData []byte\n\tdb.rwMutex.Lock()\n\tdefer db.rwMutex.Unlock()\n\tfile, err := os.OpenFile(db.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0220)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Cannot open DB File %v for Write\", db.path)\n\t}\n\tdefer func() {\n\t\terr = file.Close()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error closing DB file %v\\n%v\", db.path, err)\n\t\t}\n\t}()\n\terr = common.ToJSON(&db.data, &jsonData)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Cannot enncode JSON\")\n\t}\n\n\t_, err = file.Write(jsonData)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Cannot write to DB file %v\", db.path)\n\t}\n\n\treturn nil\n}", "func SaveJSONFile(v interface{}, testRelativePath string) {\n\tjsonText, _ := json.MarshalIndent(v, \"\", \"\\t\")\n\n\tfilePath := getFullPath(testRelativePath)\n\terr := ioutil.WriteFile(filePath, jsonText, 0644)\n\n\tthrow.OnError(err)\n}", "func (c *Container) Save(i interface{}) cipher.SHA256 {\n\treturn c.db.AddAutoKey(encoder.Serialize(i))\n}", "func toJSON(v interface{}) (io.Reader, error) {\n\tb, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bytes.NewReader(b), nil\n}", "func (a *Network) Save(path string) {\n\tioutil.WriteFile(path, []byte(a.outputFormat()), 0666)\n}", "func (settings *Settings) Save(path string) error {\n\tcontent, err := json.Marshal(settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(path, content, 0644)\n}", "func Save(v interface{}, saveTo string) error {\n\tkv, err := reflectutil.ToMapWithDefault(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// iterate over map setting key => value in ini file\n\tcfg := ini.Empty()\n\tfor k, v := range kv {\n\t\tvar data string\n\t\tswitch v.(type) {\n\t\tcase float64, float32:\n\t\t\tdata = strconv.FormatFloat(v.(float64), 'f', -1, 64)\n\t\tdefault:\n\t\t\tdata = fmt.Sprint(v)\n\t\t}\n\t\tcfg.Section(\"\").NewKey(k, data)\n\t}\n\treturn cfg.SaveTo(saveTo)\n}", "func (config *Config) Save(file string) error {\n\tbts, err := json.Marshal(*config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar out bytes.Buffer\n\tjson.Indent(&out, bts, \"\", \"\\t\")\n\n\treturn ioutil.WriteFile(file, out.Bytes(), 0600)\n}", "func (s *State) Save() error {\n\tf, err := os.Create(getPathForUsername(s.Username))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\treturn json.NewEncoder(f).Encode(s)\n}", "func (api *api) save() {\n\tr := map[string]string{}\n\tfor k, v := range api.Manager.pathes {\n\t\tr[k] = v.content\n\t}\n\tdata, err := json.MarshalIndent(r, \"\", \" \")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(api.ConfigFile, data, 0755)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (n *NetworkBuilder) Save(writer io.Writer) error {\n\terr := json.NewEncoder(writer).Encode(n.Network)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func (m *settings) saveToDisk() error {\n\tb, err := json.Marshal(m.redirects)\n\tif err != nil {\n\t\tlog.Printf(\"Error marshalling %s\", err)\n\t\treturn fmt.Errorf(\"error marshalling %s\", err)\n\t}\n\n\tif err := ioutil.WriteFile(m.filename, b, 0644); err != nil {\n\t\treturn fmt.Errorf(\"unable to open file %s\", err)\n\t}\n\tlog.Printf(\"saving to disk.\")\n\treturn nil\n}", "func (c *Config) save() {\n\tconst file = \"access.json\"\n\n\tc.logger.Printf(\"Save file %s\\n\", file)\n\n\tcfg := conf{\n\t\tIP: c.GetString(\"ip\"),\n\t\tPort: c.GetString(\"port\"),\n\t\tToken: c.GetString(\"token\"),\n\t\tWait: c.GetBool(\"wait\"),\n\t}\n\n\tb, err := json.Marshal(cfg)\n\tif err != nil {\n\t\tc.logger.Error(err)\n\t}\n\n\tif err = ioutil.WriteFile(file, b, 0644); err != nil {\n\t\tc.logger.Error(err)\n\t}\n}", "func (c *Config) Save(filename string) error {\n\tvar b bytes.Buffer\n\tenc := json.NewEncoder(&b)\n\tenc.SetIndent(\"\", \"\\t\")\n\tif err := enc.Encode(c); err != nil {\n\t\treturn fmt.Errorf(\"error encoding configuration: %w\", err)\n\t}\n\tif err := os.WriteFile(filename, b.Bytes(), 0600); err != nil {\n\t\treturn fmt.Errorf(\"error writing %q: %w\", filename, err)\n\t}\n\treturn nil\n}", "func Write(input interface{}) ([]byte, error) {\n\treturn json.Marshal(input)\n}", "func (r *LocalRegistry) save() {\n\tregBytes := core.ToJsonBytes(r)\n\tcore.CheckErr(ioutil.WriteFile(r.file(), regBytes, os.ModePerm), \"fail to update local registry metadata\")\n}", "func writeJson(v interface{}) (io.Reader, error) {\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn bytes.NewBuffer(b), nil\n}", "func (k KMP) Save(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\tf, err = os.Create(filepath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tdefer f.Close()\n\t\tout, err := json.Marshal(k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = f.Write(out)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid save format, %s\", format)\n\t}\n\treturn err\n}", "func (q *Queue) Save(dst io.Writer) error {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\n\tfor i := q.i; i < q.j; i++ {\n\t\tjsonData, err := json.Marshal(q.a[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintln(dst, string(jsonData))\n\t}\n\n\treturn nil\n}", "func (p *YouTubeJoinPlugin) Save() ([]byte, error) {\n\treturn json.Marshal(p)\n}", "func (s *Stash) Save(key string, value interface{}) error {\n\tswitch s.version {\n\tcase version1:\n\t\tmarshalledData, err := json.Marshal(value)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error marshalling value\")\n\t\t}\n\t\ts.mutex.Lock()\n\t\ts.data.(v1Data)[key] = marshalledData\n\t\ts.mutex.Unlock()\n\n\t\tif s.autoFlush {\n\t\t\treturn s.Flush()\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\tdefault:\n\t\treturn UnknownVersionError{s.version}\n\t}\n}", "func (f *FilePersist) Save(ctx context.Context, data map[string]string) error {\n\tfr, err := os.OpenFile(f.filename, os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to open file for persist: %w\", err)\n\t}\n\tdefer fr.Close()\n\tif err := json.NewEncoder(fr).Encode(data); err != nil {\n\t\treturn fmt.Errorf(\"unable to encode: %w\", err)\n\t}\n\treturn nil\n}", "func toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\tif err != nil {\n\t\t//return []byte{}, fmt.Errorf(\"Erro no json %v\", err)\n\t\treturn []byte{}, errors.New(fmt.Sprintf(\"Erro no json %v\", err))\n\t}\n\treturn bs, nil\n}", "func (c *MetaConfig) Save() error {\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(MetaConfigPath, data, 0644)\n}", "func (s *Session) Save() (err error) {\n\tvar (\n\t\tfile *os.File\n\t)\n\n\t// create the session directory\n\tif err = os.MkdirAll(s.Folder, 0600); err != nil {\n\t\treturn fmt.Errorf(\"could not create .clouditor in home directory: %w\", err)\n\t}\n\n\tif file, err = os.OpenFile(fmt.Sprintf(\"%s/session.json\", s.Folder), os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0600); err != nil {\n\t\treturn fmt.Errorf(\"could not save session.json: %w\", err)\n\t}\n\n\tdefer func(file *os.File) {\n\t\terr = file.Close()\n\t}(file)\n\n\tif err = json.NewEncoder(file).Encode(&s); err != nil {\n\t\treturn fmt.Errorf(\"could not serialize JSON: %w\", err)\n\t}\n\n\ts.dirty = false\n\n\treturn nil\n}", "func WriteToInterface(res interface{}, v interface{}) error {\n\tx := reflect.ValueOf(v)\n\tif x.Kind() == reflect.Ptr {\n\t\tx = x.Elem()\n\t}\n\treflect.ValueOf(res).Elem().Set(x)\n\treturn nil\n}", "func (p FilePersister) Save(v *viper.Viper, basename string) error {\n\tv.SetConfigType(\"json\")\n\tv.AddConfigPath(p.Dir)\n\tv.SetConfigName(basename)\n\n\tif _, err := os.Stat(p.Dir); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(p.Dir, os.FileMode(0755)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// WriteConfig is broken.\n\t// Someone proposed a fix in https://github.com/spf13/viper/pull/503,\n\t// but the fix doesn't work yet.\n\t// When it's fixed and merged we can get rid of `path`\n\t// and use viperConfig.WriteConfig() directly.\n\tpath := filepath.Join(p.Dir, fmt.Sprintf(\"%s.json\", basename))\n\treturn v.WriteConfigAs(path)\n}", "func (c *ConfigurationFile) Save() error {\n\tcontent, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(c.location.get(), content, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SaveJSONSafe(filename string, thing interface{}, mode os.FileMode) error {\n\tb, err := json.MarshalIndent(thing, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tflags := os.O_WRONLY | os.O_CREATE | os.O_EXCL\n\tf, err := os.OpenFile(filename, flags, mode)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tn, err := f.Write(b)\n\tif n != len(b) && err != nil {\n\t\terr = errors.New(\"Failed to save complete file\")\n\t}\n\tif err != nil {\n\t\tos.Remove(filename)\n\t}\n\treturn err\n}", "func toJSON(a interface{}) ([]byte, error) {\n\tbs, err := json.Marshal(a)\n\n\tif err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"Error caught by Onur Gurel\")\n\t}\n\n\treturn bs, nil\n}", "func Save() error {\n\treturn nil\n}", "func (t *ToyBrick) USave(v interface{}) (*Result, error) {\n\tvValue := LoopIndirect(reflect.ValueOf(v))\n\tif t.objMustAddr && vValue.CanAddr() == false {\n\t\tpanic(\"object must can addr\")\n\t}\n\tswitch vValue.Kind() {\n\tcase reflect.Slice:\n\t\trecords := NewRecords(t.Model, vValue)\n\t\treturn t.usave(records)\n\tdefault:\n\t\trecords := MakeRecordsWithElem(t.Model, vValue.Addr().Type())\n\t\trecords.Add(vValue.Addr())\n\t\treturn t.usave(records)\n\t}\n}", "func SaveGob(path string, object interface{}) error {\n\tfile, err := os.Create(path)\n\tdefer file.Close()\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tencoder.Encode(object)\n\t}\n\treturn err\n}", "func Save(fileName string, dst interface{}) error {\n\t// Create all directories\n\tif err := os.MkdirAll(filepath.Dir(fileName), os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tencoder := gob.NewEncoder(file)\n\t\tif err = encoder.Encode(dst); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func Serialize(v interface{}) ([]byte, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tif err := gob.NewEncoder(buf).Encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (viperConfig *Configurator) Save(sbConfig *config.SBConfiguration) error {\n\tviperConfig.viper.Set(\"url\", sbConfig.URL)\n\tviperConfig.viper.Set(\"authorization\", sbConfig.Authorization)\n\tviperConfig.viper.Set(\"room\", sbConfig.Room)\n\n\tif err := viperConfig.viper.WriteConfig(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func writeJSON(buf *bytes.Buffer, v interface{}, keyName string) error {\n\tenc, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, `failed to encode '%s'`, keyName)\n\t}\n\tbuf.Write(enc)\n\n\treturn nil\n}", "func (e GenericPersistable) ToJSON() []byte {\n\t\tresult, _ := json.Marshal(e)\n\t\treturn result\n\t}", "func (c *Config) Save(filename string) (err error) {\n\tlog.Println(\"[DEBUG] Save\", filename)\n\n\tbody, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.writeFile(filename, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (driver *S3Driver) Save(paste *shared.Paste) error {\n\t// Marshal the paste\n\tjsonBytes, err := json.Marshal(paste)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Put the object\n\treader := bytes.NewReader(jsonBytes)\n\t_, err = driver.client.PutObject(context.Background(), driver.bucket, paste.ID+\".json\", reader, reader.Size(), minio.PutObjectOptions{\n\t\tContentType: \"application/json\",\n\t})\n\treturn err\n}", "func (m *Model) Save(path string) error {\n\tdata, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"save model\")\n\t}\n\tif err := ioutil.WriteFile(path, data, 0755); err != nil {\n\t\treturn errors.Wrap(err, \"save model\")\n\t}\n\treturn nil\n}", "func Save() {\n\tc := Config{viper.GetString(\"email\"), viper.GetString(\"platform\"), viper.GetDuration(\"timeout\")}\n\tdata, err := json.MarshalIndent(c, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_ = ioutil.WriteFile(viper.GetString(\"file_config\"), data, 0600)\n}", "func ToJSON(i interface{}, w io.Writer) error {\n\te := json.NewEncoder(w)\n\n\treturn e.Encode(i)\n}", "func (r *historyRow) save(dir string) error {\n\trBytes, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thistoryFile := getLatestHistoryFile(dir)\n\n\tf, err := os.OpenFile(historyFile.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\t_, err = f.Write(append(rBytes, []byte(\"\\n\")...))\n\treturn err\n}", "func writeJSON(w http.ResponseWriter, v interface{}, status int) error {\n\t// set application/json header\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(status)\n\n\t// json encoder\n\tvar encoder = json.NewEncoder(w)\n\n\t// encodes interface to json\n\treturn encoder.Encode(v)\n}", "func writeBackup(filename string, contents interface{}) {\n\tfile, err := os.Create(filename)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't open %s: %#v\", filename, err)\n\t\treturn\n\t}\n\terr = json.NewEncoder(file).Encode(contents)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't write to %s: %#v\", filename, err)\n\t}\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't close %s: %#v\", filename, err)\n\t}\n}", "func Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (m *Drive) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetBundles() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetBundles())\n err = writer.WriteCollectionOfObjectValues(\"bundles\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"driveType\", m.GetDriveType())\n if err != nil {\n return err\n }\n }\n if m.GetFollowing() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetFollowing())\n err = writer.WriteCollectionOfObjectValues(\"following\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"owner\", m.GetOwner())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"quota\", m.GetQuota())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"root\", m.GetRoot())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharePointIds\", m.GetSharePointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSpecial() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSpecial())\n err = writer.WriteCollectionOfObjectValues(\"special\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}" ]
[ "0.79349977", "0.7603756", "0.7265592", "0.70981365", "0.6894807", "0.6894807", "0.6894807", "0.68806446", "0.6834804", "0.6746869", "0.67125416", "0.65770334", "0.65708554", "0.65669554", "0.6514774", "0.6461022", "0.64585143", "0.643517", "0.64074165", "0.63989145", "0.63707775", "0.63486105", "0.62861884", "0.6254463", "0.62468004", "0.623087", "0.6230097", "0.6230096", "0.6229652", "0.62224317", "0.62206733", "0.62032545", "0.61970973", "0.6177053", "0.61617666", "0.615428", "0.6153036", "0.61238", "0.611136", "0.6104034", "0.60972375", "0.6077416", "0.60478157", "0.604684", "0.60151434", "0.6013361", "0.6005007", "0.599249", "0.5981278", "0.5976789", "0.59764856", "0.59699637", "0.5969178", "0.59424055", "0.5939353", "0.5924375", "0.59104526", "0.590489", "0.589881", "0.5891083", "0.5888966", "0.58832633", "0.5865901", "0.58570313", "0.5855084", "0.5853124", "0.5837402", "0.5814953", "0.5805944", "0.5800581", "0.57924527", "0.57858807", "0.5783524", "0.5772756", "0.5765539", "0.57616204", "0.57511216", "0.57330847", "0.5732774", "0.5728791", "0.57008636", "0.56998444", "0.5699253", "0.5690705", "0.5683684", "0.56834245", "0.56809205", "0.56640357", "0.5662441", "0.5659503", "0.5652922", "0.56516075", "0.5633196", "0.5625026", "0.56233245", "0.5611196", "0.56079274", "0.5597465", "0.5595373", "0.55953014", "0.5593111" ]
0.0
-1
Load is used to convert a JSON (marshall output formatted) file to a struct (interface)
func fileToInterface(path string, structOut interface{}) error { // Lock and defer the unlock until function exit filewritelock.Lock() defer filewritelock.Unlock() log.Println("INFO: Loading " + path) fileOut, err := os.Open(path) if err != nil { log.Println("ERROR: fileToInterface() " + err.Error() + " while openning file " + path) return err } defer fileOut.Close() Unmarshal(fileOut, structOut) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*JSONStruct) Load(filename string, v interface{}) {\n\tdata, err := io.ReadFile(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\tjsonBytes := []byte(data)\n\n\terr = json.Unmarshal(jsonBytes, v)\n\tif err != nil {\n\t\treturn\n\t}\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tif err == nil {\n\t\tdecoder := json.NewDecoder(file)\n\t\terr = decoder.Decode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(r io.Reader, v interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, v)\n}", "func Load(fromPath string, toVar interface{}) {\n\tfile, e := ioutil.ReadFile(fromPath)\n\terr.Panic(e)\n\tfile = RemoveComment(file)\n\terr.Panic(json.Unmarshal(file, toVar))\n}", "func (c *Info) Load() error {\n\tb, err := ioutil.ReadFile(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Lock()\n\terr = json.Unmarshal(b, c)\n\tc.Unlock()\n\n\treturn err\n}", "func Load(file string, v interface{}) error {\n\tf, err := gzipf.Open(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn json.NewDecoder(f).Decode(v)\n}", "func Load(filename string, result interface{}) error {\n\tfile, err := os.Open(filename)\n\tdefer file.Close()\n\tif err != nil {\n\t\tcf, err := os.Create(filename)\n\t\tdefer cf.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tdata, err := json.MarshalIndent(result, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\t\tcf.Write(data)\n\t\tmsg := \"config file not exist, created\"\n\t\tlog.Println(msg)\n\t\treturn errors.New(msg)\n\t}\n\tdec := json.NewDecoder(file)\n\terr = dec.Decode(&result)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn err\n}", "func Load(fn string, f DataFmt) (interface{}, error) {\n\tif _, err := os.Stat(fn); os.IsNotExist(err) {\n\t\treturn nil, errors.New(\"file doesn't exist\")\n\t}\n\n\tb, err := ioutil.ReadFile(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td, err := Unmarshal(b, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (k *KMP) Load(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(b, k)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid load format, %s\", format)\n\t}\n\treturn err\n}", "func Load(name string, data interface{}) error {\n\tp := jsonPath(name)\n\t// Don't load anything if the file doesn't exist\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"File %s didn't exist, loading with fresh data\\n\", p)\n\t\treturn nil\n\t}\n\n\t// Read and unmarshal the json\n\tif b, err := ioutil.ReadFile(p); err != nil {\n\t\treturn err\n\t} else if len(b) == 0 {\n\t\tlog.Printf(\"File %s was empty, loading with fresh data\\n\", p)\n\t\treturn nil\n\t} else if err := json.Unmarshal(b, data); err != nil {\n\t\treturn fmt.Errorf(\"failed to load file %s error: %s\", p, err)\n\t}\n\n\tlog.Printf(\"Loaded %s\\n\", p)\n\treturn nil\n}", "func Load(b common.RawBytes) (*Topology, error) {\n\trt := &Topology{}\n\tif err := json.Unmarshal(b, rt); err != nil {\n\t\treturn nil, serrors.WrapStr(\"unable to parse topology from JSON\", err)\n\t}\n\treturn rt, nil\n}", "func LoadJSON(f string, iface interface{}) error {\n\traw, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(raw, iface)\n}", "func LoadFromFile(fileName string, data interface{}) error {\n\t// If data is not a pointer, return an error\n\tif reflect.TypeOf(data).Kind() != reflect.Ptr {\n\t\treturn errors.New(\"pointer expected\")\n\t}\n\n\t// Leemos el objeto json de un archivo.\n\tbytes, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Transformamos el objeto json a una estructura y la guardamos en la variable 'data'.\n\terr = json.Unmarshal(bytes, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(filename string, data any, validation bool) error {\n\tisJSON := strings.HasSuffix(filename, \".json\")\n\n\tbs, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif validation {\n\t\terr := validate(bs, data, isJSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn unmarshal(bs, data, isJSON)\n}", "func Load (path string, unsafe...bool) (*Parser, error) {\n if j, e := gjson.Load(path, unsafe...); e == nil {\n return &Parser{j}, nil\n } else {\n return nil, e\n }\n}", "func LoadJson(path string, target interface{}) error {\n f, err := os.Open(path)\n if err != nil {\n return err\n }\n defer f.Close()\n data, err := ioutil.ReadAll(f)\n if err != nil {\n return err\n }\n err = json.Unmarshal(data, target)\n return err\n}", "func Load(path string, unsafe...bool) (*Parser, error) {\n if j, e := gjson.Load(path, unsafe...); e == nil {\n return &Parser{j}, nil\n } else {\n return nil, e\n }\n}", "func Load(filename string, v interface{}) {\n\tParse(read(filename), v)\n}", "func Load(filename string) (*Params, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar params Params\n\tif err := json.Unmarshal(file, &params); err != nil {\n\t\tlog.Printf(\"failed to parse %s: %s\", file, string(file))\n\t\treturn nil, err\n\t}\n\treturn &params, nil\n}", "func (e *Definition) Load(path, entity string) error {\n\n\tfullPath := filepath.Join(path, entity)\n\n\tb, err := ioutil.ReadFile(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontent := string(b)\n\te.json = jsonutil.NewFromString(content)\n\te.byteRead = 0\n\n\ts, err := schema.Read(e)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read schema: %s\", err)\n\t\treturn err\n\t}\n\n\te.schema = s\n\tv := validator.New(s)\n\te.validator = v\n\treturn nil\n}", "func loadJSON(t *testing.T, filename string, output interface{}) {\n\tfile := filepath.Join(\"testdata\", filename)\n\tfd, err := os.Open(file)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to read file %s: %v\", file, err)\n\t}\n\tif err = json.NewDecoder(fd).Decode(&output); err != nil {\n\t\tt.Fatalf(\"failed to decode file %s: %v\", file, err)\n\t}\n}", "func FromFile(path string, x interface{}) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatalf(\"[common] error opening file %s: %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\t// read file as byte array\n\tbytes, _ := ioutil.ReadAll(file)\n\tif err := json.Unmarshal(bytes, x); err != nil {\n\t\tlog.Fatalf(\n\t\t\t\"[common] error unmarshaling json to output struct %T: %v (%s)\",\n\t\t\tx,\n\t\t\terr,\n\t\t\tpath,\n\t\t)\n\t}\n}", "func LoadJSON(filename string, thing interface{}) error {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tdec := json.NewDecoder(file)\n\tdec.UseNumber()\n\treturn dec.Decode(thing)\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func (m *Model) Load(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\tif err := json.Unmarshal(data, m); err != nil {\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\treturn nil\n}", "func (s *Schedule) Load() {\r\n\tb, _ := ioutil.ReadFile(s.fileName)\r\n\tjson.Unmarshal(b, &s.ScheduleMap)\r\n}", "func (s *DataStore) Load() error {\n\tfile, err := os.Open(s.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = json.NewDecoder(file).Decode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p *Parser) Load(filename string) (string, error) {\n\tdirectory := filepath.Dir(filename)\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvm := jsonnet.MakeVM()\n\tvm.Importer(&jsonnet.FileImporter{\n\t\tJPaths: []string{directory},\n\t})\n\n\treturn vm.EvaluateAnonymousSnippet(filename, string(data))\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(filename string) *contract.JSON {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tcontract, err := common.UnmarshalDFSSFile(data)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn contract\n}", "func Load(filename string) (*Beam, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treader := bufio.NewReader(f)\n\tdecoder := json.NewDecoder(reader)\n\tdecoder.DisallowUnknownFields()\n\tcfg := new(Beam)\n\t// This **Beam double-pointer appears to be required to detect an invalid\n\t// input of \"null\". See Test_Load/file_contains_null test.\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding JSON value in %v: %v\", filename, err)\n\t}\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"loading %v resulted in nil config\", filename)\n\t}\n\tif decoder.More() {\n\t\treturn nil, fmt.Errorf(\"found unexpected data after config in %v\", filename)\n\t}\n\treturn cfg, nil\n}", "func (j *JSONLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\tif j.Reader != nil {\n\t\tr = j.Reader\n\t} else if j.Path != \"\" {\n\t\tfile, err := getConfig(j.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\treturn json.NewDecoder(r).Decode(s)\n}", "func Load(fileName string, src interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tdecoder := gob.NewDecoder(file)\n\t\tif err = decoder.Decode(src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Restore parameters\n\tswitch src.(type) {\n\tcase Model:\n\t\tmodel := src.(Model)\n\t\tmodel.SetParams(model.GetParams())\n\tdefault:\n\t\treturn errors.New(\"the file is not a model dump\")\n\t}\n\treturn nil\n}", "func Load(fname string) (r *Recipe, err error) {\n\tb, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn\n\t}\n\tr = new(Recipe)\n\terr = json.Unmarshal(b, r)\n\treturn\n}", "func Open(filePath string) (obj *object, err error) {\n\tbuf, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(buf, &obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}", "func LoadStructure(name string) (*Structure, error) {\n\tvar err error\n\n\tcontent, err := ioutil.ReadFile(fmt.Sprintf(\"%s/%s.json\", structureName, name))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &Structure{}\n\terr = json.Unmarshal(content, s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s, nil\n}", "func (b *baseLoader) Load(ctx context.Context, src *url.URL) (*Schema, error) {\n\t// open IO\n\tvar r io.ReadCloser\n\tswitch src.Scheme {\n\tcase \"file\":\n\t\tvar err error\n\t\tif r, err = os.Open(src.Path); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q from %q: %w\", src.Path, src, err)\n\t\t}\n\tcase \"http\", \"https\":\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, src.String(), nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create request for %q: %w\", src, err)\n\t\t}\n\t\tresp, err := b.client.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed requesting %q: %w\", src, err)\n\t\t}\n\t\tr = resp.Body\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme: %v\", src.Scheme)\n\t}\n\tdefer func() {\n\t\t_ = r.Close()\n\t}()\n\n\t// read and init schema\n\tvar s Schema\n\tif err := json.NewDecoder(r).Decode(&s); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding %q failed: %w\", src, err)\n\t}\n\tif s.ID == nil {\n\t\treturn nil, fmt.Errorf(\"no ID set on %q\", src)\n\t}\n\ts.calculateID()\n\ts.setSrc(src)\n\n\treturn &s, nil\n}", "func Load(path string) (db DB, err error) {\n\tdb.filePath = path\n\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(b, &db)\n\n\treturn\n}", "func Load(filePath string, struc interface{}) error{\n\n\t//Build OS reader\n\treader := new(ReaderOS)\n\t\n\t//Reading File\n\tcontentBytes, err := reader.Read(filePath)\n\tif err != nil{\n\t\tlog.Println(TAG, err)\n\t\treturn err\n\t}\n\n\t//Get Parser\n\tparser := GetParser()\n\n\t//Parsing\n\tif err := parser.Parse(contentBytes, struc); err != nil {\n\t\tlog.Println(TAG, err)\n\t\treturn ErrParserFile\n\t}\n\n\treturn nil\n}", "func Load(path string) (*Config, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tconfig := new(Config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = json.Unmarshal(data, config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}", "func Load(filename string) (*RBM, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\trbm := &RBM{}\n\terr = decoder.Decode(rbm)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rbm, nil\n}", "func LoadJSON() *starlarkstruct.Struct {\n\treturn starlarkstruct.FromStringDict(\n\t\tstarlarkstruct.Default,\n\t\tstarlark.StringDict{\n\t\t\t\"ToJSON\": starlark.NewBuiltin(\"json\", ToJSON),\n\t\t\t\"FromJSON\": starlark.NewBuiltin(\"object\", FromJSON),\n\t\t},\n\t)\n}", "func (self *LSHforest) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn msgpack.Unmarshal(b, self)\n}", "func Load(aseJSONFilePath string) File {\n\tfile := readFile(aseJSONFilePath)\n\n\tase := LoadBytes(file)\n\n\t// Make path absolute\n\tif path, err := filepath.Abs(ase.ImagePath); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tase.ImagePath = path\n\t}\n\treturn ase\n}", "func Load(path string) (*OBJFile, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\treturn Decode(in)\n}", "func (db *jsonDB) Load() error {\n\tdb.rwMutex.Lock()\n\tdefer db.rwMutex.Unlock()\n\tfile, err := os.OpenFile(db.path, os.O_RDWR|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Cannot open DB File %v for Read\", db.path)\n\t}\n\tdefer func() {\n\t\terr = file.Close()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error closing DB file %v\\n%v\", db.path, err)\n\t\t}\n\t}()\n\tbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Cannot read from DB file %v\", db.path)\n\t}\n\tif len(bytes) > 0 {\n\t\terr = common.FromJSON(&db.data, bytes)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"Cannot decode JSON file %v\", db.path)\n\t\t}\n\t}\n\treturn nil\n}", "func Load(path string, target interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn load(formatter, data, target)\n}", "func (self *JsonConfig) Load() (err error) {\n\tvar data []byte = make([]byte, 1024)\n\tif data, err = ioutil.ReadFile(self.Path); err != nil {\n\t\treturn err\n\t}\n\tout, err := unmarshalJson(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tself.Configurable.Reset(out)\n\treturn nil\n}", "func (d *Dump) Load() error {\n\td.mutex.Lock()\n\tdefer d.mutex.Unlock()\n\n\tvar (\n\t\tdata []byte\n\t\terr error\n\t)\n\n\tif data, err = ioutil.ReadFile(d.filename); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.decodeGob(data)\n}", "func Load(path string) (*Config, error) {\n\tconfigFile, err := os.Open(path)\n\tdefer configFile.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar config Config\n\tjsonParser := json.NewDecoder(configFile)\n\tparseErr := jsonParser.Decode(&config)\n\n\tif parseErr != nil {\n\t\treturn nil, parseErr\n\t}\n\tconfig.fillFlags()\n\treturn &config, nil\n}", "func Load() error {\n\treturn def.Load()\n}", "func (d *Database) Load() error {\n\tb, err := ioutil.ReadFile(d.FilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(b, &d.State); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (l *tomlLoader) Load(out interface{}) error {\n\tif _, err := toml.DecodeReader(l.r, out); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load (content []byte, commands *map[string]Command) {\n // decode json\n var command_descriptor descriptor\n if err := json.Unmarshal(content, &command_descriptor); err != nil {\n log.Println(err)\n os.Exit(1)\n }\n\n // build command\n var new_command *Command = Build_command(command_descriptor)\n if (new_command == nil) {\n log.Printf(\"Command %s: not loaded!\", command_descriptor.Command_name)\n } else {\n (*commands)[command_descriptor.Command_name] = *new_command\n }\n}", "func (this *Manager) load() error{\n bytes, err := ioutil.ReadFile(this.filename())\n if err != nil {\n return err\n }\n mp := dynmap.NewDynMap()\n err = mp.UnmarshalJSON(bytes)\n if err != nil {\n return err\n }\n table,err := ToRouterTable(mp)\n if err != nil {\n return err\n }\n this.SetRouterTable(table) \n return nil\n}", "func Load(fileName string) (stu *StudentSet, err error) {\n\tbs, err := ioutil.ReadFile(fileName)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(bs, &stu)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (s *Startup) Load() error {\n\n\t// TODO: parameterize startup config file name\n\tjsonFile, err := ioutil.ReadFile(\"startup.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(jsonFile, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil // no error\n}", "func (c *Config) Load(filename string) (err error) {\n\tlog.Println(\"[DEBUG] Load\", filename)\n\n\terr = c.ensureFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := c.readFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(body, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}", "func LoadJSON(source interface{}, state data.Map) (interface{}, error) {\n\tlocation := toolbox.AsString(source)\n\tif location == \"\" {\n\t\treturn nil, errors.New(\"location was empty at LoadJSON\")\n\t}\n\tdata, err := ioutil.ReadFile(location)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to load: %v\", location)\n\t}\n\tJSON := string(data)\n\tif toolbox.IsNewLineDelimitedJSON(JSON) {\n\t\tslice, err := toolbox.NewLineDelimitedJSON(JSON)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar result = make([]interface{}, 0)\n\t\ttoolbox.ProcessSlice(slice, func(item interface{}) bool {\n\t\t\tif item == nil {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif toolbox.IsMap(item) && len(toolbox.AsMap(item)) == 0 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tresult = append(result, item)\n\t\t\treturn true\n\t\t})\n\t\treturn result, nil\n\t}\n\tvar result interface{}\n\terr = json.Unmarshal(data, &result)\n\treturn result, err\n}", "func Read(fn string) (o *Mesh) {\n\to = new(Mesh)\n\tb := io.ReadFile(fn)\n\terr := json.Unmarshal(b, o)\n\tif err != nil {\n\t\tchk.Panic(\"%v\\n\", err)\n\t}\n\to.CheckAndCalcDerivedVars()\n\treturn\n}", "func (d *Drawer) load() error {\n\tdata, err := ioutil.ReadFile(d.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(data) > 0 {\n\t\tvar payload interface{}\n\t\tpayload, err = d.serializer.Deserialize(data)\n\t\tif !isPointer(payload) {\n\t\t\tpanic(NonPointerErr)\n\t\t}\n\t\td.payload = payload\n\t} else {\n\t\td.payload = nil\n\t}\n\treturn err\n}", "func (reading_EntityInfo) Load(ob *objectbox.ObjectBox, bytes []byte) (interface{}, error) {\n\tif len(bytes) == 0 { // sanity check, should \"never\" happen\n\t\treturn nil, errors.New(\"can't deserialize an object of type 'Reading' - no data received\")\n\t}\n\n\tvar table = &flatbuffers.Table{\n\t\tBytes: bytes,\n\t\tPos: flatbuffers.GetUOffsetT(bytes),\n\t}\n\n\tvar propId = table.GetUint64Slot(4, 0)\n\n\treturn &Reading{\n\t\tId: propId,\n\t\tDate: fbutils.GetInt64Slot(table, 6),\n\t\tEventId: fbutils.GetUint64Slot(table, 8),\n\t\tValueName: fbutils.GetStringSlot(table, 10),\n\t\tValueString: fbutils.GetStringSlot(table, 12),\n\t\tValueInteger: fbutils.GetInt64Slot(table, 14),\n\t\tValueFloating: fbutils.GetFloat64Slot(table, 16),\n\t\tValueInt32: fbutils.GetInt32Slot(table, 18),\n\t\tValueFloating32: fbutils.GetFloat32Slot(table, 20),\n\t}, nil\n}", "func (d *Datastore) Load() (Object, error) {\n\td.localLock.Lock()\n\tdefer d.localLock.Unlock()\n\n\t// clear Object first, as mapstructure's decoder doesn't have ZeroFields set to true for merging purposes\n\td.meta.Object = d.meta.Object[:0]\n\n\terr := d.kv.LoadConfig(d.meta)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = d.meta.unmarshall()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.meta.object, nil\n}", "func Load(filename string) Config {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.WithField(`error`, err).Fatal(`Opening config file`)\n\t}\n\n\tdec := json.NewDecoder(file)\n\tconf := Config{}\n\tif err = dec.Decode(&conf); err != nil {\n\t\tlog.WithField(`error`, err).Fatal(`Parsing config file`)\n\t}\n\n\treturn conf\n}", "func (this *DmnList) Load(src interface{}) error {\n\treturn load(this, src, `json`)\n}", "func Load(filename string) (*Configuration, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// To allow comments in the json, we minify the file with js minifer before parsing\n\tm := minify.New()\n\tm.AddFunc(\"text/javascript\", js.Minify)\n\tfile, err = m.Bytes(\"text/javascript\", file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := Default()\n\terr = json.Unmarshal(file, d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, d.Validate()\n}", "func Load(fileName string) Configuration {\n\tvar config Configuration\n\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening configuration file from %s: %s\", fileName, err)\n\t}\n\tdefer file.Close()\n\n\tdecoder := json.NewDecoder(file)\n\tif err := decoder.Decode(&config); err != nil {\n\t\tlog.Fatalf(\"Error decoding JSON from %s: %s\", fileName, err)\n\t}\n\n\treturn config\n}", "func Load(filename string, prefs interface{}) error {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn json.NewDecoder(f).Decode(&prefs)\n}", "func Load(config interface{}, configPath string) error {\n\tswitch fileExtension(configPath) {\n\tcase \"yaml\":\n\t\treturn loadYaml(config, configPath)\n\tcase \"json\":\n\t\treturn loadJson(config, configPath)\n\tdefault:\n\t\treturn ero.Newf(\"Can not support load file %s\", configPath)\n\t}\n}", "func Load(filePath string, t Tomler) error {\n\ttomlValue := t.TOMLValue()\n\tvar err error\n\tif _, err = toml.DecodeFile(filePath, tomlValue); err != nil {\n\t\treturn err\n\t}\n\treturn t.FromTOML(tomlValue)\n}", "func loadFrom(r io.Reader) (*Config, error) {\n\tc := &Config{}\n\tdec := json.NewDecoder(r)\n\tif err := dec.Decode(c); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := c.General.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"config validation error: %v\", err)\n\t}\n\tif err := c.Service.Parameters.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"config validation error: %v\", err)\n\t}\n\tif err := c.Service.Input.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"config validation error: %v\", err)\n\t}\n\tif err := c.Service.Output.validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"config validation error: %v\", err)\n\t}\n\treturn c, nil\n}", "func (tag *SwizzleTag) Load(file io.Reader) error {\n\tw, err := gzip.NewReader(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenc := json.NewDecoder(w)\n\terr = enc.Decode(tag)\n\tw.Close()\n\n\treturn err\n}", "func Load(configFile string, p Parser) error {\n\t// Read the config file\n\tjsonBytes, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Parse the config\n\tif err := p.ParseJSON(jsonBytes); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Config) Load() error {\n\tif _, err := os.Stat(c.filePath); os.IsNotExist(err) {\n\t\treturn errors.New(\"pharos hasn't been configured yet\")\n\t}\n\traw, err := ioutil.ReadFile(c.filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif string(raw) == \"\" {\n\t\treturn errors.New(\"pharos hasn't been configured yet\")\n\t}\n\n\treturn json.Unmarshal(raw, c)\n}", "func (r *LocalRegistry) Load() {\n\tvar (\n\t\tregBytes []byte\n\t\terr error\n\t)\n\t// check if localRepo file exist\n\t_, err = os.Stat(r.file())\n\tif err != nil {\n\t\t// then assume localRepo.json is not there: try and create it\n\t\tr.save()\n\t} else {\n\t\tregBytes, err = ioutil.ReadFile(r.file())\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\terr = json.Unmarshal(regBytes, r)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func LoadJSON(fileName string, questions interface{}) {\n\tjsonFile, _ := os.Open(fileName)\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\tjson.Unmarshal([]byte(byteValue), &questions)\n\tdefer jsonFile.Close()\n}", "func Load(v interface{}, loadFrom string) error {\n\tcfg, err := ini.Load(loadFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.NameMapper = ini.TitleUnderscore\n\n\treturn cfg.MapTo(v)\n}", "func Load(fileName string) ([]Dog, error) {\n\tdata, _ := ioutil.ReadFile(fileName)\n\treturn DogsFromJSON(data)\n}", "func parseFile(t *testing.T, f string, s interface{}) {\n\tread, err := os.Open(f)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = json.NewDecoder(read).Decode(&s)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = read.Close()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func Loadjson(jobTemplate string) Info {\n\n\tdefer func() {\n\t\ts := recover()\n\t\tfmt.Println(s)\n\t}()\n\n\t// jsonFile, err := ioutil.ReadFile(\"/tmp/transcode.json\")\n\tjsonFile, err := ioutil.ReadFile(jobTemplate)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar info Info\n\t// save json content in data\n\tjson.Unmarshal(jsonFile, &info)\n\treturn info\n}", "func (gorilla Gorilla) Load(req *http.Request, key string, result interface{}) error {\n\tvalue := gorilla.Get(req, key)\n\tif value != \"\" {\n\t\treturn json.Unmarshal([]byte(value), result)\n\t}\n\treturn nil\n}", "func LoadJsonFile(path string, jsonObject interface{}) error {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(buf, jsonObject); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func FileToInterface(fileName string, data interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbyteValue, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(byteValue, &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a *AuthConfig) Load(fileName string) error {\n\tf, err := os.Open(fileName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\treturn json.Unmarshal(b, a)\n\n}", "func loadFromPath(path string, out interface{}) error {\n\tvar err error\n\n\tf, err := os.Open(path)\n\tif f != nil {\n\t\tdefer func() {\n\t\t\tferr := f.Close()\n\t\t\tif ferr != nil {\n\t\t\t\tlog.Println(ferr)\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn toml.Unmarshal(data, out)\n}", "func (f *FilePersist) Load(ctx context.Context) (map[string]string, error) {\n\tfr, err := os.Open(f.filename)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to open file: %w\", err)\n\t}\n\tdefer fr.Close()\n\n\tdb := make(map[string]string)\n\tif err := json.NewDecoder(fr).Decode(&db); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to decode file: %w\", err)\n\t}\n\treturn db, nil\n}", "func (b *Bolt) Load(id string, data interface{}) error {\n\terr := b.client.View(func(tx *bolt.Tx) error {\n\t\tbkt := tx.Bucket([]byte(b.bucket))\n\t\tv := bkt.Get([]byte(id))\n\t\tif v == nil {\n\t\t\treturn storage.ErrNotFound\n\t\t}\n\n\t\terr := json.Unmarshal(v, data)\n\t\treturn err\n\t})\n\n\treturn err\n}", "func Load(r io.Reader) (*MetaInfo, error) {\n\tvar mi MetaInfo\n\td := bencode.NewDecoder(r)\n\terr := d.Decode(&mi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mi, nil\n}", "func Load(r io.Reader) (*MetaInfo, error) {\n\tvar mi MetaInfo\n\td := bencode.NewDecoder(r)\n\terr := d.Decode(&mi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mi, nil\n}", "func Load(key string, data []byte) Entity {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tentity Entity\n\t)\n\n\tbuffer.Write(data)\n\tdecoder := gob.NewDecoder(&buffer)\n\tentityType := strings.Split(key, \".\")[0]\n\n\tswitch entityType {\n\tcase \"player\":\n\t\tentity = new(Player)\n\tcase \"planet\":\n\t\tentity = new(Planet)\n\tcase \"mission\":\n\t\tentity = new(Mission)\n\tcase \"sun\":\n\t\tentity = new(Sun)\n\tcase \"ss\":\n\t\tentity = new(SolarSlot)\n\tcase \"spy_report\":\n\t\tentity = new(SpyReport)\n\tdefault:\n\t\treturn nil\n\t}\n\tdecoder.Decode(entity)\n\treturn entity\n}", "func (s *Store) Load() error {\n\tfReader, err := os.Open(filepath.Join(s.rwDirPath, storeName))\n\tif err != nil {\n\t\treturn errors.Wrap(err, err.Error())\n\t}\n\tdefer fReader.Close()\n\n\tdec := gob.NewDecoder(fReader)\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = dec.Decode(&s.data)\n\tif err != nil {\n\t\treturn errors.Wrap(err, err.Error())\n\t}\n\treturn nil\n}", "func ConvertJSONFileToStruct(filename string, dataStore *Deck) error {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.NewDecoder(file).Decode(dataStore)\n\tif err != nil {\n\n\t\treturn err\n\t}\n\treturn err\n}", "func (conf *config) load(filename string) error {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tjdc := json.NewDecoder(file)\n\terr = jdc.Decode(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Reserve) Load() *Store {\n\tret := NewStore()\n\tdata, err := ioutil.ReadFile(r.path)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to load store %s: %s\\n\", r.name, err)\n\t\treturn &Store{}\n\t}\n\tjson.Unmarshal(data, &ret)\n\treturn ret\n}", "func Load() (cfg *Config, err error) {\n\tfile, err := Location()\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = os.Stat(file)\n\tif os.IsNotExist(err) {\n\t\tcfg = &Config{}\n\t\terr = nil\n\t\treturn\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't check if config file '%s' exists: %v\", file, err)\n\t\treturn\n\t}\n\t// #nosec G304\n\tdata, err := os.ReadFile(file)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't read config file '%s': %v\", file, err)\n\t\treturn\n\t}\n\tcfg = &Config{}\n\tif len(data) == 0 {\n\t\treturn\n\t}\n\terr = json.Unmarshal(data, cfg)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"can't parse config file '%s': %v\", file, err)\n\t\treturn\n\t}\n\treturn\n}" ]
[ "0.8062228", "0.7621891", "0.7608677", "0.7536772", "0.7311489", "0.7303192", "0.7233047", "0.71877", "0.71543425", "0.70984703", "0.70858276", "0.7059995", "0.7041795", "0.7030563", "0.70268375", "0.7012453", "0.7006991", "0.6945984", "0.68736225", "0.6873584", "0.6835881", "0.6831632", "0.6828245", "0.67842215", "0.6737249", "0.6660339", "0.6656424", "0.6645932", "0.66387975", "0.6622332", "0.66065955", "0.660255", "0.6599306", "0.65720373", "0.65622383", "0.6526265", "0.6484315", "0.64792436", "0.64666885", "0.64631826", "0.645435", "0.6446488", "0.64086384", "0.6395161", "0.6375173", "0.63624835", "0.6350566", "0.63381815", "0.63115734", "0.6295987", "0.628559", "0.6282073", "0.627624", "0.6248125", "0.6244832", "0.62275904", "0.62036204", "0.6187676", "0.6178283", "0.6153577", "0.61474097", "0.614164", "0.6110438", "0.6087839", "0.6079429", "0.6078063", "0.6072109", "0.606617", "0.6059033", "0.604181", "0.60412043", "0.60390323", "0.60299927", "0.60283154", "0.6013009", "0.60129714", "0.6009083", "0.60086", "0.6007792", "0.59918195", "0.5988103", "0.5980295", "0.5977717", "0.5967622", "0.59621024", "0.59595436", "0.5955752", "0.59225", "0.5907824", "0.5903486", "0.58914536", "0.5889019", "0.5884642", "0.5884642", "0.58778566", "0.5872064", "0.5856972", "0.58450544", "0.5840924", "0.5837814" ]
0.6021396
74
LoadTestEnv will load .env.test
func LoadTestEnv() error { _, b, _, _ := runtime.Caller(0) d := path.Join(path.Dir(b)) err := godotenv.Load(fmt.Sprintf("%s/.env.test", filepath.Dir(d))) if err != nil { log.Fatal("failed to load test env config: ", err) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LoadEnvFile(t *testing.T) error {\r\n\tenvFileName := os.Getenv(TestEnvFilePath)\r\n\terr := godotenv.Load(envFileName)\r\n\tif err != nil {\r\n\t\treturn fmt.Errorf(\"Can not read .env file: %s\", envFileName)\r\n\t}\r\n\treturn nil\r\n}", "func loadTestConfig() {\n\terr := godotenv.Load(\"../.env.testing\")\n\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env.testing file \"+\n\t\t\t\"not found, permission issues or a corrupted file\",\n\t\t\terr)\n\t}\n\n\terr = env.Parse(&cfg)\n\n\tif err != nil {\n\t\tlog.Fatal(\"The format is not valid\", err)\n\t}\n}", "func LoadDotEnv(t *testing.T) {\n\tLoadDotEnvFromFile(t, \".env\")\n}", "func LoadTestEnv() *core.Engine {\n\tengine := new(core.Engine)\n\n\t_, dir, _, _ := runtime.Caller(0)\n\tconfigJSON := filepath.Join(filepath.Dir(dir), \"../..\", \"env\", \"tdd.json\")\n\n\tjsonFile, err := os.Open(configJSON)\n\n\tif err != nil {\n\t\tlog.Fatalln(err, \"can't open the config file\", dir+\"/regularenvs.json\")\n\t}\n\n\tdefer jsonFile.Close()\n\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\terr = json.Unmarshal(byteValue, &engine.Env)\n\tif err != nil {\n\t\tlog.Fatalln(err, \"error in unmarshal JSON\")\n\t}\n\n\tif engine.Env.MachineID, err = machineid.ProtectedID(\"SigmaMono\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn engine\n}", "func TestEnvEmpty(t *testing.T) {\n\tenverr := pkg.LoadEnv()\n\n\tif _, err := os.Stat(\"../.env\"); os.IsNotExist(err) {\n\t\tif enverr != nil {\n\t\t\tt.Error(\"Env does not exist\")\n\t\t}\n\t}\n}", "func LoadEnv() {\n\tif err := env.Parse(&Env); err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func LoadEnv(filename string) error {\n\terr := godotenv.Load(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Conf) loadEnv() {\n\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\t\tk := strings.ToUpper(pair[0])\n\t\tv := strings.Join(pair[1:], \"=\")\n\t\tswitch k {\n\t\tcase \"HOME\":\n\t\t\tc.Env.Home = v\n\t\tcase \"USER\":\n\t\t\tc.Env.User = v\n\t\tcase \"PWD\":\n\t\t\tc.Env.PWD = v\n\t\tcase \"TRAVIS\":\n\t\t\tc.Env.Travis = true\n\t\t}\n\t}\n\tc.Parsed.Env = true\n\n}", "func LoadEnvVars() {\n\tenv := GetEnv(\"GIN_ENV\", \"development\")\n\n\tif env == \"production\" || env == \"staging\" {\n\t\tlog.Println(\"Not using .env file in production or staging.\")\n\t\treturn\n\t}\n\n\tfilename := \".env.\" + env\n\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\tfilename = \".env\"\n\t}\n\n\terr := godotenv.Load(filename)\n\tif err != nil {\n\t\tlog.Println(\".env file not loaded\")\n\t}\n}", "func LoadEnv() {\n\terr := godotenv.Load(\"/etc/logstv/.env\")\n\tif err != nil {\n\t\tpanic(\"Error loading .env file\")\n\t}\n}", "func loadDotEnv() {\n\tcwd, err := os.Getwd()\n\n\tif err != nil {\n\t\tlog.Fatal(\"Error getting current working directory\")\n\t}\n\tfmt.Println(filepath.Join(cwd, \".env\"))\n\terr = godotenv.Load(filepath.Join(cwd, \".env\"))\n\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env file\")\n\t}\n}", "func LoadEnv() {\n\tenv := os.Getenv(\"TEMPLATE_ENV\")\n\tif \"\" == env {\n\t\tenv = \"development\"\n\t}\n\n\tgodotenv.Load(\".env.\" + env + \".local\")\n\tif \"test\" != env {\n\t\tgodotenv.Load(\".env.local\")\n\t}\n\tgodotenv.Load(\".env.\" + env)\n\tgodotenv.Load() // The Original .env\n\tif vars := checkVars(); len(vars) != 0 {\n\t\tlog.Printf(\"ERROR: Variables de entorno necesarias no definidas: %v\", vars)\n\t\tpanic(fmt.Sprintf(\"ERROR: Variables de entorno necesarias no definidas: %v\", vars))\n\t}\n}", "func TestMain(m *testing.M) {\n\tif err := godotenv.Load(os.ExpandEnv(\"./../.env\")); err != nil {\n\t\tlog.Println(\"no env gotten\")\n\t}\n\tos.Exit(m.Run())\n}", "func LoadEnv() {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env file\")\n\t}\n}", "func TestENV(t *testing.T) {\n\tif confy.GetEnvironment() != \"test\" {\n\t\tt.Skipf(\"skipping test. Env should be test when running `go test`, instead env is %v\", confy.GetEnvironment())\n\t}\n\n\tos.Setenv(\"CONFY_ENV\", \"production\")\n\tdefer os.Setenv(\"CONFY_ENV\", \"\")\n\tconfy.DefaultConfy = confy.NewConfy()\n\tif confy.GetEnvironment() != \"production\" {\n\t\tt.Errorf(\"Env should be production when set it with CONFY_ENV\")\n\t}\n}", "func Load() error {\n\t// read .env\n\tcontents, fileErr := ioutil.ReadFile(\"./.env\")\n\tif fileErr != nil {\n\t\treturn fileErr\n\t}\n\n\t// parse .env conents\n\tenvs, parseErr := parse(string(contents))\n\tif parseErr != nil {\n\t\treturn parseErr\n\t}\n\n\t// set parsed environment variables\n\tfor k, v := range envs {\n\t\tos.Setenv(k, v)\n\t}\n\n\treturn nil\n}", "func LoadEnvFile(path string, panicOnFailure bool) error {\n\n\tif err := gotenv.Load(path); err != nil {\n\t\tif panicOnFailure {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\treturn NewLoadEnvFileError(\"Failed to load env file\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func LoadEnv() (err error) {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\".env file not found, reading configuration from ENV\")\n\t\terr = nil\n\t}\n\treturn err\n}", "func LoadEnv() error {\n\treturn godotenv.Load()\n}", "func LoadEnv(filenames ...string) error {\n\tfor _, filename := range setFilename(filenames) {\n\t\tlines, err := readFile(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsetEnv(lines)\n\t}\n\n\treturn nil\n}", "func TestEnviron(t *testing.T) {\n\ttests := map[string]string{\n\t\t\"KEY_0\": \"Abc\",\n\t\t\"KEY_1\": \"Def\",\n\t}\n\n\t// Set test data.\n\tos.Clearenv()\n\tfor key, value := range tests {\n\t\tif err := os.Setenv(key, value); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\t// Test function.\n\tfor i, str := range Environ() {\n\t\ttmp := strings.Split(str, \"=\")\n\t\tkey, value := tmp[0], tmp[1]\n\t\tif v, ok := tests[key]; v != value || !ok {\n\t\t\tif !ok {\n\t\t\t\tt.Errorf(\"test %v. extra key`%v`\", i, key)\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"test %v. expected `%v` but `%v`\", i, v, value)\n\t\t\t}\n\t\t}\n\t}\n}", "func LoadEnv(envFilePath string) (*Environment, error) {\n\tdata, err := ioutil.ReadFile(envFilePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tenv, err := NewEnvironment(string(data))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn env, nil\n}", "func LoadEnvs() {\n\tvar err error\n\n\tif err = godotenv.Load(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tPort, err = strconv.Atoi(os.Getenv(\"APP_PORT\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tAPIURL = os.Getenv(\"API_URL\")\n\tHashKey = []byte(os.Getenv(\"HASH_KEY\"))\n\tBlockKey = []byte(os.Getenv(\"BLOCK_KEY\"))\n}", "func (util *Utils) LoadEnvirontment(path string) *entity.Environment {\n\tif util.CheckEnvironment(path) != \"\" {\n\t\terr := godotenv.Load(path)\n\t\tutil.Check(err)\n\t} else {\n\t\thomeDir := util.ReadHome()\n\t\terr := godotenv.Load(homeDir + \"/.guppy\")\n\t\tutil.Check(err)\n\t}\n\n\tenvi := &entity.Environment{}\n\tenvi.DialTimeOut, _ = strconv.Atoi(os.Getenv(\"OS_DIAL_TIMEOUT\"))\n\tenvi.Urls = strings.Split(os.Getenv(\"OS_URLS\"), \",\")\n\treturn envi\n}", "func Load() {\n\tgodotenv.Load(\".env.local\", \".env\")\n}", "func LoadEnvFromFile(envFile string) error {\n\tif envFile == \"\" {\n\t\treturn nil\n\t}\n\n\tfile, err := os.Open(envFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tenvMap, err := ParseEnvFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor k, v := range envMap {\n\t\tif err := os.Setenv(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Load(envFile string) error {\n\t// Check file exists\n\tinfo, err := os.Stat(envFile)\n\tif os.IsNotExist(err) || info.IsDir() {\n\t\treturn errors.New(fmt.Sprintf(\"file %s not found\", envFile))\n\t}\n\tenvVars, err = godotenv.Read()\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"error loading %s file\", envFile))\n\t}\n\treturn nil\n}", "func TestEnvVars(t *testing.T) {\n\t// Arrange\n\tos.Setenv(snapEnv, \"/snap/testsnap/x1\")\n\tos.Setenv(snapCommonEnv, \"/snap/testsnap/common\")\n\tos.Setenv(snapDataEnv, \"/var/snap/testsnap/x1\")\n\tos.Setenv(snapInstNameEnv, \"testsnap\")\n\tos.Setenv(snapRevEnv, \"2112\")\n\n\t// Test\n\terr := getEnvVars()\n\n\t// Assert values\n\tassert.Nil(t, err)\n\tassert.Equal(t, Snap, \"/snap/testsnap/x1\")\n\tassert.Equal(t, SnapCommon, \"/snap/testsnap/common\")\n\tassert.Equal(t, SnapData, \"/var/snap/testsnap/x1\")\n\tassert.Equal(t, SnapInst, \"testsnap\")\n\tassert.Equal(t, SnapRev, \"2112\")\n\tassert.Equal(t, SnapConf, \"/snap/testsnap/x1/config\")\n\tassert.Equal(t, SnapDataConf, \"/var/snap/testsnap/x1/config\")\n}", "func LoadEnv() Env {\n\n\tvar env []string\n\tenv = os.Environ()\n\n\tmapped := make(map[string]string)\n\n\tfor _, pair := range env {\n\t\t// os.Environ returns a list of KEY=VALUE pairs\n\t\tsplitted := strings.Split(pair, \"=\")\n\t\tif len(splitted) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tk, v := splitted[0], splitted[1]\n\t\tmapped[k] = v\n\t}\n\n\treturn Env{mapped}\n}", "func TestEnvironment(t *testing.T) {\n\tvariables := []string{\n\t\t\"MONGO_URI\",\n\t\t\"SECRET_KEY\",\n\t\t\"MAGIC_LINK\",\n\t\t\"ROOT_LINK\",\n\t\t\"GITHUB_API\",\n\t\t\"GITHUB_OAUTH\",\n\t\t\"GITHUB_ORG\",\n\t\t\"DEBRICKED_API\",\n\t\t\"DEBRICKED_USER\",\n\t\t\"DEBRICKED_PASS\",\n\t}\n\tfor e := range variables {\n\t\tif _, present := os.LookupEnv(variables[e]); !present {\n\t\t\tt.Errorf(\"Expected environment variable %s to be set\", variables[e])\n\t\t}\n\t}\n}", "func LoadEnv(fn string) ([]string, error) {\n\tbuf, err := os.ReadFile(fn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlines := strings.Split(string(buf), \"\\n\")\n\tenv := []string{}\n\tfor _, x := range lines {\n\t\tif strings.Index(x, \"=\") == -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\ta := strings.SplitN(x, \"=\", 2)\n\t\tk := strings.TrimSpace(a[0])\n\t\tv := strings.TrimSpace(a[1])\n\t\te := fmt.Sprintf(\"%s=%s\", k, v)\n\t\tenv = append(env, e)\n\t}\n\treturn env, nil\n}", "func LoadEnv(l logger.ILog, prefix string) *Settings {\n\ts := new(Settings)\n\terr := env.Unmarshal(s, prefix)\n\tif err != nil {\n\t\tl.Fatalf(\"error getting environment variables: %v\", err.Error())\n\t}\n\n\treturn s\n}", "func initDotEnv() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Println(\"No .env file found\")\n\t}\n}", "func LoadEnvironment(object interface{}, metaDataKey string) error {\n\tvar values = func(key string) (string, bool) {\n\t\treturn os.LookupEnv(key)\n\t}\n\treturn commonLoad(values, object, metaDataKey)\n}", "func getTestEnv() *Env {\n\tdb := createMockDB()\n\n\toauthConf := &oauth2.Config{\n\t\tClientID: \"abcdef0123abcdef4567\",\n\t\tClientSecret: \"abcdef0123abcdef4567abcdef8901abcdef2345\",\n\t\tScopes: []string{\"user:email\"},\n\t\tEndpoint: githuboauth.Endpoint,\n\t}\n\n\tenv := &Env{\n\t\tdb: db,\n\t\tjwtSecretKey: \"keyForTesting\",\n\t\toauthConf: oauthConf,\n\t\toauthState: \"nonRandomStateString\",\n\t}\n\treturn env\n}", "func Init(env string) {\n\tif env == \"test\" {\n\t\terr := godotenv.Load(\"./.env.test\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error loading .env.test file\")\n\t\t}\n\t} else if env == \"development\" {\n\t\terr := godotenv.Load()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error loading .env file\")\n\t\t}\n\t}\n}", "func TestEnvVar(t *testing.T) {\n\tos.Setenv(\"TEST\", \"OK\")\n\n\tres := pkg.GetEnvVar(\"TEST\")\n\tif res != \"OK\" {\n\t\tt.Error(\"Env variable was wrongly read\")\n\t}\n}", "func setupTestEnv(t *testing.T) testEnv {\n\tdirPath, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get current working directory for testing - %s\", err.Error())\n\t}\n\n\t_, err = os.Stat(path.Join(dirPath, \"go.mod\"))\n\tif err != nil {\n\t\tt.Fatalf(\"current working directory is not repo - %s\", err.Error())\n\t}\n\n\ttestDataDir := path.Join(dirPath, \".testdata\")\n\n\terr = os.MkdirAll(testDataDir, 0700)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create test data directory - %s\", err.Error())\n\t}\n\n\tname := randStringBytesRmndr(10)\n\tresource := path.Join(testDataDir, name)\n\tif runtime.GOOS == \"windows\" {\n\t\tresource = name\n\t}\n\n\treturn testEnv{\n\t\tmutexConfig: MutexConfig{\n\t\t\tResource: resource,\n\t\t},\n\t\tdataDirPath: testDataDir,\n\t\tharnessSrcPath: path.Join(dirPath, \"cmd/testharness/main.go\"),\n\t}\n}", "func TestReadParseStoreVariables(t *testing.T) {\n\texpand := true\n\ttests := map[string]string{\n\t\t\"KEY_0\": \"value_0\",\n\t\t\"KEY_1\": \"value_1\",\n\t\t\"KEY_2\": \"value_001\",\n\t\t\"KEY_3\": \"value_001->correct value\",\n\t\t\"KEY_4\": \"value_0value_001\",\n\t}\n\n\t// Load env-file.\n\tos.Clearenv()\n\terr := readParseStore(\"./fixtures/variables.env\", expand, false, false)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t// Compare with sample.\n\tfor key, value := range tests {\n\t\tif v := os.Getenv(key); value != v {\n\t\t\tt.Errorf(\"incorrect value for `%s` key: `%s`!=`%s`\", key, value, v)\n\t\t}\n\t}\n}", "func EnvVar(key string, testing bool) string {\n\n var err error\n // load .env file\n if testing {\n err = godotenv.Load(\"../../.env\")\n } else {\n err = godotenv.Load()\n }\n\n if err != nil {\n log.Fatalf(\"Error loading .env file\")\n }\n\n return os.Getenv(key)\n}", "func LoadEnvFileAndReturnEnvVarValueByKey(key string) string {\n\terr := godotenv.Load(\".env\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading .env file\")\n\t}\n\treturn os.Getenv(key)\n}", "func importEnv() map[string]string {\r\n\tvar myEnv map[string]string\r\n\tmyEnv, err := godotenv.Read()\r\n\tif err != nil {\r\n\t\tlog.Fatal(\"Error loading .env file\")\r\n\t}\r\n\r\n\treturn myEnv\r\n}", "func loadFile(filename string) error {\n\tenvMap, err := readFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor key, value := range envMap {\n\t\tos.Setenv(key, value)\n\t}\n\n\treturn nil\n}", "func initEnv() {\n\terr := os.RemoveAll(TestDataDir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Load(f string) {\n\tfp := filepath.Join(\".\", f)\n\tif _, err := os.Stat(fp); os.IsNotExist(err) {\n\t\treturn\n\t}\n\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tlog.Fatal(\"Error while loading environment variables\", err)\n\t\tos.Exit(1)\n\t}\n}", "func InitEnv() error {\n\tfile, err := ioutil.ReadFile(envPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif errMarsh := codec.DecJson(file, &env); errMarsh != nil {\n\t\treturn fmt.Errorf(\"failed to parse %s. decode error: %v\", string(file), err)\n\t}\n\n\treturn nil\n}", "func LoadEnvs() {\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\tK8sCertFile = loadw(\"KUBERNETES_CERT_FILE\")\n\tK8sKeyFile = loadw(\"KUBERNETES_KEY_FILE\")\n\tK8sCAFile = loadw(\"KUBERNETES_CA_FILE\")\n\n\tEtcdEndpoints = loadw(\"ETCD_ENDPOINTS\")\n\tEtcdPath = loadw(\"ETCD_PATH\")\n}", "func LoadEnvVariable(key string) string {\n\tviper.SetConfigFile(\".env\")\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvalue, ok := viper.Get(key).(string)\n\tif !ok {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn value\n}", "func TestReadParseStoreExported(t *testing.T) {\n\ttests := map[string]string{\n\t\t\"KEY_0\": \"value 0\",\n\t\t\"KEY_1\": \"value 1\",\n\t\t\"KEY_2\": \"value_2\",\n\t\t\"KEY_3\": \"value_0:value_1:value_2:value_3\",\n\t}\n\n\t// Load env-file.\n\tos.Clearenv()\n\terr := readParseStore(\"./fixtures/exported.env\", false, false, false)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Compare with sample.\n\tfor key, value := range tests {\n\t\tif v := os.Getenv(key); value != v {\n\t\t\tt.Errorf(\"incorrect value for `%s` key: `%s`!=`%s`\", key, value, v)\n\t\t}\n\t}\n}", "func loadCCCEnv(file string) *CCCEnv {\n\tvar b []byte\n\tvar err error\n\n\tif b, err = ioutil.ReadFile(file); err != nil {\n\t\tpanic(fmt.Sprintf(\"Cannot read env file %s\\n\", err))\n\n\t}\n\n\tenv := &CCCEnv{}\n\terr = json.Unmarshal(b, &env)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error unmarshalling cccenv: %s\\n\", err))\n\t}\n\n\treturn env\n}", "func init() {\n\ttestEnv.Init()\n}", "func loadEnvironmentVariables() {\n\tpgDb = os.Getenv(\"PGDB\")\n\tif len(pgDb) == 0 {\n\t\tpanic(\"No pgDB environment variable\")\n\t}\n\n\tpgUser = os.Getenv(\"PGUSER\")\n\tif len(pgUser) == 0 {\n\t\tpanic(\"No pgUSER environment variable\")\n\t}\n\n\tpgPassword = os.Getenv(\"PGPASSWORD\")\n\tif len(pgPassword) == 0 {\n\t\tpanic(\"No pgPASSWORD environment variable\")\n\t}\n\n\tpgHost = os.Getenv(\"PGHOST\")\n\tif len(pgHost) == 0 {\n\t\tpanic(\"No pgHOST environment variable\")\n\t}\n\n\tuploadFolderPath = os.Getenv(\"UPLOAD_FOLDER_PATH\")\n\tif len(uploadFolderPath) == 0 {\n\t\tpanic(\"No UPLOAD_FOLDER_PATH environment variable\")\n\t}\n}", "func (ec *ExecutionContext) loadEnvfile() error {\n\tvar op errors.Op = \"cli.ExecutionContext.loadEnvfile\"\n\tenvfile := ec.Envfile\n\tif !filepath.IsAbs(ec.Envfile) {\n\t\tenvfile = filepath.Join(ec.ExecutionDirectory, ec.Envfile)\n\t}\n\terr := gotenv.Load(envfile)\n\tif err != nil {\n\t\t// return error if user provided envfile name\n\t\tif ec.Envfile != \".env\" {\n\t\t\treturn errors.E(op, err)\n\t\t}\n\t\tif !stderrors.Is(err, fs.ErrNotExist) {\n\t\t\tec.Logger.Warn(err)\n\t\t}\n\t}\n\tif err == nil {\n\t\tec.Logger.Debug(\"ENV vars read from: \", envfile)\n\t}\n\treturn nil\n}", "func init() {\n\t// if envFileName exists in the current directory, load it\n\tlocalEnvFile := fmt.Sprintf(\"./%s\", envFileName)\n\tif _, localEnvErr := os.Stat(localEnvFile); localEnvErr == nil {\n\t\tif loadErr := godotenv.Load(localEnvFile); loadErr != nil {\n\t\t\tstdErr.Printf(\"Could not load env file <%s>: %s\", localEnvFile, loadErr)\n\t\t}\n\t}\n\n\t// if envFileName exists in the user's home directory, load it\n\tif homeDir, homeErr := os.UserHomeDir(); homeErr == nil {\n\t\thomeEnvFile := fmt.Sprintf(\"%s/%s\", homeDir, \".xmcenv\")\n\t\tif _, homeEnvErr := os.Stat(homeEnvFile); homeEnvErr == nil {\n\t\t\tif loadErr := godotenv.Load(homeEnvFile); loadErr != nil {\n\t\t\t\tstdErr.Printf(\"Could not load env file <%s>: %s\", homeEnvFile, loadErr)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestFiletraceEnv(t *testing.T) {\n\tFileTrace(\"env > e.txt\", map[string]string{\"x\": \"y\"}, \"\")\n\tdefer func() {\n\t\tif err := os.Remove(\"e.txt\"); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}()\n\n\tdata, err := ioutil.ReadFile(\"e.txt\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdatastr := string(data)\n\tif !strings.Contains(datastr, \"x=y\") {\n\t\tt.Fatalf(\"environment x=y not found in %s\", datastr)\n\t}\n}", "func Load(filenames ...string) error {\n\treturn loadenv(false, filenames...)\n}", "func TestNullString(t *testing.T) {\n\terr := createEnv(\"TEST=null\")\n\tif err != nil {\n\t\tt.Errorf(\"expected nil, got %T\", err)\n\t}\n\n\tLoad()\n\tif os.Getenv(\"TEST\") != \"\" {\n\t\tt.Errorf(\"Expected nil, but got %s\", os.Getenv(\"TEST\"))\n\t}\n\n\tdeleteEnvFile()\n}", "func EnvVarTest(resourceName string, sourceType string, envString string) {\n\n\tif sourceType == \"git\" {\n\t\t// checking the values of the env vars pairs in bc\n\t\tenvVars := runCmd(\"oc get bc \" + resourceName + \" -o go-template='{{range .spec.strategy.sourceStrategy.env}}{{.name}}{{.value}}{{end}}'\")\n\t\tExpect(envVars).To(Equal(envString))\n\t}\n\n\t// checking the values of the env vars pairs in dc\n\tenvVars := runCmd(\"oc get dc \" + resourceName + \" -o go-template='{{range .spec.template.spec.containers}}{{range .env}}{{.name}}{{.value}}{{end}}{{end}}'\")\n\tExpect(envVars).To(Equal(envString))\n}", "func main() {\n\tpwd, _ := os.Getwd()\n\tenv.ReadEnv(path.Join(pwd, \".env\"))\n\tfor _, v := range os.Environ() {\n\t\tfmt.Println(v)\n\t}\n}", "func TestMain(m *testing.M) {\n\tvar err error\n\terr = godotenv.Load(os.ExpandEnv(\"../../.env\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error getting env %v\\n\", err)\n\t}\n\n\ttestutils.Database()\n\n\tos.Exit(m.Run())\n}", "func Load(lc *LoadConfig) error {\n\t// Configure Viper and read in the configuration file.\n\tviper.SetConfigName(lc.configName)\n\tviper.SetConfigType(lc.configType)\n\tviper.AddConfigPath(lc.configPath)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\treturn fmt.Errorf(\"loading env: %v\", err)\n\t}\n\n\t// Return only the variables for the target environment.\n\tenv.Lock()\n\tdefer env.Unlock()\n\tenv.vars = viper.Sub(lc.targetEnv)\n\tif env.vars == nil {\n\t\treturn ErrNoEnvKeys\n\t}\n\n\treturn nil\n}", "func CheckDotEnv() {\n\terr := godotenv.Load()\n\tif err != nil && os.Getenv(env) == local {\n\t\tlog.Println(\"Error loading .env file\")\n\t}\n}", "func LoadFromEnv(v interface{}, prefix string) (result []MarshalledEnvironmentVar) {\n\tpointerValue := reflect.ValueOf(v)\n\tstructValue := pointerValue.Elem()\n\tstructType := structValue.Type()\n\n\tfor i := 0; i < structValue.NumField(); i++ {\n\t\tstructField := structType.Field(i)\n\t\tfieldValue := structValue.Field(i)\n\n\t\tif fieldValue.CanSet() {\n\t\t\tenvKey := strings.ToUpper(prefix) + gocase.ToUpperSnake(structField.Name)\n\t\t\tenvVal := os.Getenv(envKey)\n\n\t\t\tif envVal != \"\" {\n\t\t\t\t// create a json blob with the env data\n\t\t\t\tjsonStr := \"\"\n\t\t\t\tif fieldValue.Kind() == reflect.String {\n\t\t\t\t\tjsonStr = fmt.Sprintf(`{\"%s\": \"%s\"}`, structField.Name, envVal)\n\t\t\t\t} else {\n\t\t\t\t\tjsonStr = fmt.Sprintf(`{\"%s\": %s}`, structField.Name, envVal)\n\t\t\t\t}\n\n\t\t\t\terr := json.Unmarshal([]byte(jsonStr), v)\n\t\t\t\tresult = append(result, MarshalledEnvironmentVar{envKey, envVal, structField.Name, err})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func init() {\n\t// if envFileName exists in the current directory, load it\n\tlocalEnvFile := fmt.Sprintf(\"./%s\", envFileName)\n\tif _, localEnvErr := os.Stat(localEnvFile); localEnvErr == nil {\n\t\tif loadErr := godotenv.Load(localEnvFile); loadErr != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Could not load env file <%s>: %s\", localEnvFile, loadErr)\n\t\t}\n\t}\n\n\t// if envFileName exists in the user's home directory, load it\n\tif homeDir, homeErr := os.UserHomeDir(); homeErr == nil {\n\t\thomeEnvFile := fmt.Sprintf(\"%s/%s\", homeDir, \".xmcenv\")\n\t\tif _, homeEnvErr := os.Stat(homeEnvFile); homeEnvErr == nil {\n\t\t\tif loadErr := godotenv.Load(homeEnvFile); loadErr != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Could not load env file <%s>: %s\", homeEnvFile, loadErr)\n\t\t\t}\n\t\t}\n\t}\n}", "func Test_Customized_Env(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Customized Env Svc Suite\")\n}", "func init() {\n\tif err := godotenv.Load(); err != nil {\n\t\tlog.Print(\"No .env file found\")\n\t}\n}", "func loadEnv() Configuration {\n\thistorySize := 10\n\thistorySizeStr := os.Getenv(\"HISTORY_SIZE\")\n\tif historySizeStr != \"\" {\n\t\thistorySize , _ = strconv.Atoi(historySizeStr)\n\t}\n\tthreads := 10\n\tthreadsStr := os.Getenv(\"THREADS\")\n\tif threadsStr != \"\" {\n\t\tthreads, _ = strconv.Atoi(threadsStr)\n\t}\n\tserverUrl := os.Getenv(\"SERVER_URL\")\n\tif serverUrl == \"\" {\n\t\tserverUrl = \":9000\"\n\t}\n\tclientUrl := os.Getenv(\"CLIENT_URL\")\n\tif clientUrl == \"\" {\n\t\tclientUrl = \":9001\"\n\t}\n\treturn Configuration{\n\t\tHistorySize: historySize,\n\t\tClientUrl: clientUrl,\n\t\tServerUrl: serverUrl,\n\t\tThreads: threads}\n}", "func loadConfig() {\n\terr := godotenv.Load()\n\n\tif err != nil {\n\t\tlog.Println(\"did not load any .env file\")\n\t}\n\n\terr = env.Parse(&cfg)\n\n\tif err != nil {\n\t\tlog.Fatal(\"The .env format is not valid\", err)\n\t}\n}", "func (receiver envVariable) Load() string {\n\treturn os.Getenv(string(receiver))\n}", "func (ctx *AppContext) Load(env string) {\n\tlog.Println(\"Load app context\")\n\n\t// Load env specific config\n\tenvConfig := viper.Sub(env)\n\tctx.Env = env\n\tctx.ProjectID = envConfig.GetString(\"project_id\")\n\tctx.SuffixOfKind = envConfig.GetString(\"datastore.kind_suffix\")\n\tctx.EtcdServers = envConfig.GetStringSlice(\"etcd\")\n\n\t// Load common config\n\tctx.CommonConfig = viper.Sub(\"common\")\n}", "func NewTestEnvSourcer(values map[string]string) Sourcer {\n\tnormalized := map[string]string{}\n\tfor key, value := range values {\n\t\tnormalized[strings.ToUpper(key)] = value\n\t}\n\n\treturn &testEnvSourcer{\n\t\tvalues: normalized,\n\t}\n}", "func Load(key string) string {\n\t// Gets the value of the map, if it exists returns the value\n\tenvironmentMutex.RLock()\n\tval := environment[key]\n\tenvironmentMutex.RUnlock()\n\n\tif environment[key] != \"\" {\n\t\treturn val\n\t}\n\n\t// If the value does not exist, it gets from the .env file\n\tval = os.Getenv(key)\n\tif val == \"\" || len(val) <= 0 {\n\t\treturn val\n\t}\n\n\t// If the value exists in .env file it is assigned to the map\n\tenvironmentMutex.Lock()\n\tenvironment[key] = val\n\tenvironmentMutex.Unlock()\n\n\treturn val\n}", "func TestSetup() {\n\tviper.Reset()\n\tviper.SetConfigType(\"yaml\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.AutomaticEnv()\n\tos.Setenv(\"RESTIC_PASSWORD\", ResticPassword)\n}", "func SetupTestCase(t *testing.T) {\r\n\t// setup code in here.\r\n\terr := LoadEnvFile(t)\r\n\tif err != nil {\r\n\t\t// even if we couldn't load the env file we won't fail the test\r\n\t\t// but if proper env variables aren't set, tests will fail on test data validation\r\n\t\t//t.Fatal(err)\r\n\t}\r\n}", "func (c *Config) LoadFromEnv() error {\n\terr := envconfig.Process(\"\", c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't process environment for config: %w\", err)\n\t}\n\n\treturn nil\n}", "func (in *Input) LoadFromEnv() {\n\tnum := reflect.ValueOf(in).Elem().NumField()\n\tfor i := 0; i < num; i++ {\n\t\ttField := reflect.TypeOf(in).Elem().Field(i)\n\t\tvField := reflect.ValueOf(in).Elem().Field(i)\n\t\tvalue, ok := os.LookupEnv(envPrefix + tField.Tag.Get(\"env\"))\n\t\tif ok {\n\t\t\tvField.Set(reflect.ValueOf(value))\n\t\t}\n\t}\n}", "func init() {\n\tsetUpConfig()\n\tsetUpUsingEnv()\n}", "func Load() (config *Config, err error) {\n\tconfig = &Config{}\n\n\tif err = env.Set(config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn\n}", "func ReadEnv(key string, defaultVal string) string {\n\tgodotenv.Load(\".env\")\n\tvalue := os.Getenv(key)\n\tif len(value) == 0 {\n\t\treturn defaultVal\n\t}\n\treturn value\n}", "func Load(env string) error {\n\tvar wd string\n\tvar yes bool\n\tvar err error\n\tif wd, err = os.Getwd(); err != nil {\n\t\treturn err\n\t}\n\n\tcwdConfig := filepath.Join(wd, DATA_DIR, CONFIG)\n\tif yes, err = paths.FileExists(cwdConfig); err != nil {\n\t\treturn err\n\t} else if yes {\n\t\treturn LoadFile(cwdConfig, env)\n\t}\n\n\tvar vcsRoot string\n\tif _, vcsRoot, err = paths.FindVCSRoot(wd); err != nil {\n\t\treturn err\n\t} else if len(vcsRoot) == 0 {\n\t\treturn errors.New(errVCSRoot)\n\t}\n\n\tvcsConfig := filepath.Join(vcsRoot, DATA_DIR, CONFIG)\n\tif yes, err = paths.FileExists(vcsConfig); err != nil {\n\t\treturn err\n\t} else if yes {\n\t\treturn LoadFile(vcsConfig, env)\n\t}\n\n\treturn errors.New(errConfig)\n}", "func TestEnvironmentGet(t *testing.T) {\n\tport := make(chan int, 1)\n\tdefer createTestServer(port, t).Close()\n\taddr := <-port\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost:%d/env/get\", addr))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tbodyContent, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(bodyContent) != \"Testing env.set function\" {\n\t\tt.Fatalf(\"Wrong env.get value. Expected 'Testing env.set function' but got '%s'\", string(bodyContent))\n\t}\n}", "func init() {\n // loads values from .env into the system\n if err := godotenv.Load(); err != nil {\n log.Print(\"No .env file found\")\n }\n}", "func Load() (Env, error) {\r\n\terr := godotenv.Load(\".env\")\r\n\tif err != nil {\r\n\r\n\t\tlogger.Fatal.Println(\"error in loading env file: \", err)\r\n\t\treturn Env{}, err\r\n\t}\r\n\tvar envVar = Env{}\r\n\tenvVar.Address = HostAddress()\r\n\tenvVar.Lat = os.Getenv(\"LAT\")\r\n\tenvVar.Lng = os.Getenv(\"LNG\")\r\n\tenvVar.DBHost = os.Getenv(\"DB_HOST\")\r\n\tenvVar.DBUser = os.Getenv(\"DB_USER\")\r\n\tenvVar.DBPwd = os.Getenv(\"DB_PWD\")\r\n\tenvVar.DBName = os.Getenv(\"DB_NAME\")\r\n\tenvVar.DBPointColl = os.Getenv(\"DB_POINTS_COLL\")\r\n\tenvVar.DBUserColl = os.Getenv(\"DB_USERS_COLL\")\r\n\tenvVar.DBVehicleColl = os.Getenv(\"DB_VEHICLES_COLL\")\r\n\tenvVar.DBChargerColl = os.Getenv(\"DB_CHARGERS_COLL\")\r\n\tenvVar.DBProviderColl = os.Getenv(\"DB_PROVIDERS_COLL\")\r\n\tenvVar.APIKey = os.Getenv(\"GOOGLE_API_KEY\")\r\n\tenvVar.LogFile = os.Getenv(\"LOGFILE\")\r\n\treturn envVar, nil\r\n}", "func init() {\n\t// Load Env vars\n\tgotenv.Load()\n}", "func newTestEnvr() *Envr {\n\tfor _, v := range testVars {\n\t\tif err := os.Unsetenv(v); err != nil {\n\t\t\tlog.Fatalf(\"os.Unsetenv() err = %s\", err)\n\t\t}\n\t}\n\treturn New(envName, testVars)\n}", "func LoadCfgFromEnv(e *Env) (*Cfg, error) {\n\tvar env Env\n\tvar err error\n\tif e == nil {\n\t\tif err = cli.SetEnvFields(&env); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\te = &env\n\t}\n\tc := &Cfg{\n\t\tSrc: \"Environment\",\n\t\tTenantID: e.TenantID,\n\t\tSubscriptionID: e.SubscriptionID,\n\t}\n\tif e.EnvName == \"\" || strings.EqualFold(e.EnvName, \"AzureCloud\") {\n\t\tc.Environment = azure.PublicCloud\n\t} else {\n\t\tc.Environment, err = azure.EnvironmentFromName(e.EnvName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif e.ClientSecret != \"\" {\n\t\terr = c.useClientSecret(e.ClientID, e.ClientSecret)\n\t} else if e.CertFile != \"\" {\n\t\terr = c.useClientCert(e.ClientID, e.CertFile, e.CertPass)\n\t} else {\n\t\terr = fmt.Errorf(\"az: client secret or cert file must be specified\")\n\t}\n\tif err != nil {\n\t\tc = nil\n\t}\n\treturn c, err\n}", "func ReadEnv(c interface{}) {\r\n\tfor _, value := range os.Environ() {\r\n\t\tif strings.HasPrefix(value, \"ENV_\") {\r\n\t\t\tkv := strings.SplitN(value,\"=\",2)\r\n\t\t\tkv[0] = strings.ToLower(strings.Replace(kv[0],\"_\",\".\",-1))[4:]\r\n\t\t\tSetData(c,strings.Join(kv,\"=\"))\r\n\t\t}\r\n\t}\r\n}", "func (envManager *TestEnvManager) GetEnv() TestEnv {\n\treturn envManager.testEnv\n}", "func loadEnvConfig(filenames ...string) bool {\n\tfor _, filename := range filenames {\n\t\tif util.Exists(filename) {\n\t\t\terr := godotenv.Load(filename)\n\n\t\t\t// if the config file cannot be read we want to know about it\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err.Error())\n\t\t\t} else {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func LoadEnv(filenames ...string) (RootCellarConfig, error) {\n\t//Load Env\n\terr := gotenv.Load(filenames...)\n\tif err != nil {\n\t\tlogging.Error(\"Error loading .env file: \", err)\n\t\treturn RootCellarConfig{}, err\n\t}\n\t//Setup global env variables\n\tconfig := RootCellarConfig{\n\t\tProduction: loadBoolEnv(\"PRODUCTION\"),\n\t\tBindPort: loadStringEnv(\"BIND_PORT\"),\n\t\tBindIP: loadStringEnv(\"BIND_IP\"),\n\t\tBindURL: loadStringEnv(\"BIND_URL\"),\n\t\tJWTSecret: loadStringEnv(\"JWT_SECRET\"),\n\t\tMongoURI: loadStringEnv(\"MONGO_URI\"),\n\t\t//SentryDSN: loadStringEnv(\"SENTRY_DSN\"),\n\t\t/*SMTPURI: loadStringEnv(\"SMTP_SERVER\"),\n\t\tSMTPPort: loadIntEnv(\"SMTP_PORT\"),\n\t\tSMTPSender: loadStringEnv(\"SMTP_SENDER\"),\n\t\tSMTPPass: loadStringEnv(\"SMTP_PASS\"),*/\n\t}\n\treturn config, nil\n}", "func LoadVars(filenames ...string) error {\n\tvar (\n\t\terr error\n\t\tenvFilePaths = make([]string, 0)\n\t)\n\tprojectPath, ok := os.LookupEnv(\"PROJECTPATH\")\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s no establecida\", \"PROJECTPATH\")\n\t}\n\n\tfmt.Printf(\"%s=%s\\n\", \"PROJECTPATH\", projectPath)\n\n\tif filenames == nil || len(filenames) < 1 {\n\t\tfilenames, err = getAllEnvFiles(projectPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tenvFiles = map[string]string{}\n\t}\n\n\tfor _, file := range filenames {\n\t\tfilePath, err := filepath.Abs(filepath.Join(projectPath, fmt.Sprintf(\"./.%s.env\", file)))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error al obtener la ruta del archivo .env: %v\", err)\n\t\t}\n\t\tenvFilePaths = append(envFilePaths, filePath)\n\t\tenvFiles[file] = filePath\n\t}\n\n\tfmt.Println(\"envFilePath\", envFilePaths)\n\terr = godotenv.Load(envFilePaths...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error al leer el archivo .env: %v\", err)\n\t}\n\treturn nil\n}", "func TestMultiEnvFiles(t *testing.T) {\n\tfiles := []struct {\n\t\tName string\n\t\tOutput error\n\t\tInput []string\n\t}{\n\t\t{\n\t\t\t\"No file provided\",\n\t\t\tnil,\n\t\t\t[]string{},\n\t\t},\n\t\t{\n\t\t\t\"One file provided\",\n\t\t\tnil,\n\t\t\t[]string{\".env\"},\n\t\t},\n\t\t{\n\t\t\t\"Two files provided\",\n\t\t\tnil,\n\t\t\t[]string{\".env\", \".env\"},\n\t\t},\n\t\t{\n\t\t\t\"Three files provided\",\n\t\t\tnil,\n\t\t\t[]string{\".env\", \".env\", \".env\"},\n\t\t},\n\t\t{\n\t\t\t\"Four files provided\",\n\t\t\tnil,\n\t\t\t[]string{\".env\", \".env\", \".env\", \".env\"},\n\t\t},\n\t}\n\n\tfor _, data := range files {\n\t\tt.Run(data.Name, func(t *testing.T) {\n\t\t\tif err := Load(data.Input...); err != nil {\n\t\t\t\tt.Errorf(\"Expected nil, but got %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}", "func GetENV(experimentDetails *experimentTypes.ExperimentDetails) {\n\texperimentDetails.ExperimentName = Getenv(\"EXPERIMENT_NAME\", \"\")\n\texperimentDetails.AppNS = Getenv(\"APP_NS\", \"\")\n\texperimentDetails.TargetContainer = Getenv(\"APP_CONTAINER\", \"\")\n\texperimentDetails.TargetPods = Getenv(\"APP_POD\", \"\")\n\texperimentDetails.AppLabel = Getenv(\"APP_LABEL\", \"\")\n\texperimentDetails.ChaosDuration, _ = strconv.Atoi(Getenv(\"TOTAL_CHAOS_DURATION\", \"30\"))\n\texperimentDetails.ChaosNamespace = Getenv(\"CHAOS_NAMESPACE\", \"litmus\")\n\texperimentDetails.EngineName = Getenv(\"CHAOS_ENGINE\", \"\")\n\texperimentDetails.ChaosUID = clientTypes.UID(Getenv(\"CHAOS_UID\", \"\"))\n\texperimentDetails.ChaosPodName = Getenv(\"POD_NAME\", \"\")\n\texperimentDetails.ContainerRuntime = Getenv(\"CONTAINER_RUNTIME\", \"\")\n\texperimentDetails.NetworkInterface = Getenv(\"NETWORK_INTERFACE\", \"eth0\")\n\texperimentDetails.TargetIPs = Getenv(\"TARGET_IPs\", \"\")\n}", "func TestStringCapture(t *testing.T) {\n\terr := createEnv(\"TEST=Arthur\")\n\tif err != nil {\n\t\tt.Errorf(\"Expected a .env file, but found none\")\n\t}\n\tLoad(\".env\")\n\n\tif os.Getenv(\"TEST\") != \"Arthur\" {\n\t\tt.Errorf(\"Expected Arthur, but got %s\", os.Getenv(\"TEST\"))\n\t}\n}", "func LoadConfig() {\n\terr := godotenv.Load(\".env\")\n\tif err != nil {\n\t\tlog.Fatal(\"Failed to load the .env file\")\n\t}\n}", "func getUrlFromEnv(t *testing.T, key string) string {\n\turl := os.Getenv(key)\n\tif url == \"\" {\n\t\tt.Fatalf(\"Please set the environment variable: %s\\n\", key)\n\t}\n\treturn url\n}", "func testGetenv(s string) string {\n\tswitch s {\n\tcase \"*\":\n\t\treturn \"all the args\"\n\tcase \"#\":\n\t\treturn \"NARGS\"\n\tcase \"$\":\n\t\treturn \"PID\"\n\tcase \"1\":\n\t\treturn \"ARGUMENT1\"\n\tcase \"HOME\":\n\t\treturn \"/usr/gopher\"\n\tcase \"H\":\n\t\treturn \"(Value of H)\"\n\tcase \"home_1\":\n\t\treturn \"/usr/foo\"\n\tcase \"_\":\n\t\treturn \"underscore\"\n\t}\n\treturn \"\"\n}", "func getTestCredsFromEnv() string {\n\treturn multiEnvSearch(credsEnvVars)\n}", "func TestLoadReadParseStoreOpen(t *testing.T) {\n\terr := readParseStore(\"./fixtures/nonexist.env\", false, false, false)\n\tif err == nil {\n\t\tt.Error(\"should be an error for open a nonexistent file\")\n\t}\n}", "func loadEnvVars(envars []string) []EnvVar {\n\tenvs := []EnvVar{}\n\tfor _, e := range envars {\n\t\tcharacter := \"\"\n\t\tequalPos := strings.Index(e, \"=\")\n\t\tcolonPos := strings.Index(e, \":\")\n\t\tswitch {\n\t\tcase equalPos == -1 && colonPos == -1:\n\t\t\tcharacter = \"\"\n\t\tcase equalPos == -1 && colonPos != -1:\n\t\t\tcharacter = \":\"\n\t\tcase equalPos != -1 && colonPos == -1:\n\t\t\tcharacter = \"=\"\n\t\tcase equalPos != -1 && colonPos != -1:\n\t\t\tif equalPos > colonPos {\n\t\t\t\tcharacter = \":\"\n\t\t\t} else {\n\t\t\t\tcharacter = \"=\"\n\t\t\t}\n\t\t}\n\n\t\tif character == \"\" {\n\t\t\tenvs = append(envs, EnvVar{\n\t\t\t\tName: e,\n\t\t\t\tValue: os.Getenv(e),\n\t\t\t})\n\t\t} else {\n\t\t\tvalues := strings.SplitN(e, character, 2)\n\t\t\t// try to get value from os env\n\t\t\tif values[1] == \"\" {\n\t\t\t\tvalues[1] = os.Getenv(values[0])\n\t\t\t}\n\t\t\tenvs = append(envs, EnvVar{\n\t\t\t\tName: values[0],\n\t\t\t\tValue: values[1],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn envs\n}" ]
[ "0.7706625", "0.76327944", "0.7433559", "0.7390404", "0.6782704", "0.673599", "0.671696", "0.67095554", "0.67051566", "0.66891676", "0.6651732", "0.6646073", "0.6565774", "0.656104", "0.6542334", "0.6491168", "0.64808255", "0.64760107", "0.6458198", "0.63961804", "0.63782704", "0.63709074", "0.63696265", "0.6337787", "0.63216776", "0.6311889", "0.6277387", "0.62260115", "0.622445", "0.62118196", "0.620689", "0.6175296", "0.6164871", "0.61431533", "0.61349773", "0.61073405", "0.60927254", "0.60844475", "0.6053946", "0.6050013", "0.59896755", "0.5984517", "0.5982952", "0.59729695", "0.5968714", "0.5959991", "0.59535646", "0.5916499", "0.5899076", "0.5895009", "0.5883472", "0.5879982", "0.58656", "0.5861392", "0.5856273", "0.5855057", "0.5843775", "0.58424634", "0.58197904", "0.581517", "0.580049", "0.57762736", "0.57711226", "0.5759692", "0.57466596", "0.57392395", "0.5737893", "0.5731478", "0.57281554", "0.5713234", "0.57062125", "0.5703636", "0.5703091", "0.5690905", "0.567578", "0.56747586", "0.5661889", "0.5656923", "0.5637595", "0.5633355", "0.56312525", "0.5630162", "0.5624171", "0.5617993", "0.56144863", "0.5612508", "0.5608234", "0.56065065", "0.5593165", "0.55792654", "0.5568848", "0.5557037", "0.5551339", "0.55465364", "0.55458665", "0.55362695", "0.55345905", "0.55314386", "0.55247587", "0.5523105" ]
0.8625285
0
InitTestDB will migrate db tables
func InitTestDB() (*gorm.DB, error) { if err := LoadTestEnv(); err != nil { panic(err) } config := configs.New() db := database.New(&config.Database, false) database.AutoMigrate(db) if conn, ok := db.DB(); ok != nil { defer conn.Close() } return db, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (db *DbCtxt) InitDatabase() error {\n\tvar models []interface{}\n\tmodels = append(models,\n\t\t&Hotel{},\n\t\t&Room{},\n\t\t&RatePlan{},\n\t)\n\tfor _, model := range models {\n\t\terr := db.client.AutoMigrate(model)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func InitTestDB() error {\n\tif db == nil {\n\t\treturn errors.New(\"database not initialized\")\n\t}\n\n\tfor i := 0; i < 1000; i++ {\n\t\tkey := intToByteArray(i)\n\t\tvalue := GetByteArray(\"hello from \"+strconv.Itoa(i), \"string\")\n\t\terr := Insert(key, value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func TestInitSchemaWithMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, migrations)\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"people\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\n\t\tassert.NoError(t, m.Migrate())\n\t\tassert.True(t, m.hasTable(\"people\"))\n\t\tassert.False(t, m.hasTable(\"pets\"))\n\t\tassert.Equal(t, 3, tableCount(t, db, \"migrations\"))\n\t})\n}", "func SetUp() {\n\n\tvar err error\n\n\tdsn := fmt.Sprintf(\"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local\",\n\t\tconfigs.GetSetting().Database.DBUser,\n\t\tconfigs.GetSetting().Database.DBPassword,\n\t\tconfigs.GetSetting().Database.DBHost + \":\" + configs.GetSetting().Database.DBPort,\n\t\tconfigs.GetSetting().Database.DBName)\n\n\n\tdb, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})\n\n\tif err != nil {\n\t\tzap.L().Panic(\"database connect error:\" + err.Error())\n\t}\n\n\tif err = db.AutoMigrate(&User{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\t(&User{}).CreateDefaultUser()\n\tif err = db.AutoMigrate(&Token{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\t(&Token{}).CreateDefaultToken()\n\tif err = db.AutoMigrate(&Baits{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&Probes{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&HoneypotServers{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&VirusRecord{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&Honeypot{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&Protocols{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\t(&Protocols{}).CreateDefaultProtocol()\n\tif err = db.AutoMigrate(&ProtocolProxy{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&TransparentProxy{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&Images{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\t(&Images{}).CreateDefaultImage()\n\tif err = db.AutoMigrate(&HoneypotBaits{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&ProbeBaits{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&HoneypotToken{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&ProbeToken{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&AttackEvent{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&ProtocolEvent{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&TransparentEvent{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&FalcoAttackEvent{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&TokenTraceLog{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&Setting{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n\tif err = db.AutoMigrate(&CounterEvent{}); err != nil{\n\t\tzap.L().Panic(\"AutoMigrate error:\" + err.Error())\n\t}\n}", "func TestInitSchemaNoMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, []*Migration{})\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"animals\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\n\t\tassert.NoError(t, m.Migrate())\n\t\tassert.True(t, m.hasTable(\"animals\"))\n\t\tassert.Equal(t, 1, tableCount(t, db, \"migrations\"))\n\t})\n}", "func TestInitSchemaExistingMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, migrations)\n\n\t\t// Migrate without initialisation\n\t\tassert.NoError(t, m.Migrate())\n\n\t\t// Then migrate again, this time with a non empty initialisation\n\t\t// This initialisation should not happen!\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"cars\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\tassert.False(t, m.hasTable(\"cars\"))\n\t\tassert.Equal(t, 2, tableCount(t, db, \"migrations\"))\n\t})\n}", "func InitDb(){\r\n\tconnectionURL:=os.Getenv(\"CONNECTION_URL\")\r\n\tvar err error\r\n\tDBConn, err = gorm.Open(\"postgres\",connectionURL)\r\n\tif err!= nil{\r\n\t\tpanic(\"failed to connect to db\")\r\n\t}\r\n\tfmt.Println(\"db is connected lets go.........\")\r\n\tDBConn.AutoMigrate(&models.GoItems{})\r\n\tfmt.Println(\"db has been migrated\")\r\n}", "func setupTestDB(t *testing.T, version int64) *sql.DB {\n\tis := is.New(t)\n\tdb, err := newDockerDB(t)\n\tis.NoErr(err)\n\n\t// Create goose table.\n\tcurrent, err := in.EnsureDBVersion(db)\n\tis.NoErr(err)\n\tis.True(current == int64(0))\n\t// Collect first 5 migrations.\n\tmigrations, err := in.CollectMigrations(migrationsDir, 0, version)\n\tis.NoErr(err)\n\tis.True(int64(len(migrations)) == version)\n\t// Apply n migrations manually.\n\tfor _, m := range migrations {\n\t\terr := m.Up(db)\n\t\tis.NoErr(err)\n\t}\n\t// Verify the current DB version is the Nth migration. This will only\n\t// work for sqeuentially applied migrations.\n\tcurrent, err = in.GetDBVersion(db)\n\tis.NoErr(err)\n\tis.True(current == int64(version))\n\n\treturn db\n}", "func InitDb(appConfig *AppConfig) {\n\tlog.Info(\"Initialize database connection\")\n\tDbs = fmt.Sprintf(\"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s\",\n\t\tappConfig.Db.Host,\n\t\tappConfig.Db.Port,\n\t\tappConfig.Db.User,\n\t\tappConfig.Db.Password,\n\t\tappConfig.Db.DbName,\n\t\tappConfig.Db.SSLMode,\n\t)\n\tlog.Info(\"Successfully initialize database connection\")\n\tdb := GetDB()\n\tlog.Info(\"Start table migrations\")\n\tdb.AutoMigrate(\n\t\t&Session{},\n\t)\n\tlog.Info(\"Table migrations achieved\")\n}", "func InitDatabase(dbName *string, dst ...interface{}) {\n\tlog.Info().Msgf(\"Loading database %v\", *dbName)\n\tvar err error\n\tdbFile = sqlite.Open(fmt.Sprintf(\"%v.db\", *dbName))\n\tdatastore, err = gorm.Open(dbFile, &gorm.Config{\n\t\tDisableForeignKeyConstraintWhenMigrating: true,\n\t})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\t// Migrate the schema\n\terr = datastore.AutoMigrate(dst...)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Migration failed! Please check the logs!\")\n\t}\n}", "func TestCreateMigrationsTable(t *testing.T) {\n\twithEachTestDB(t, func(t *testing.T, tdb *TestDB) {\n\n\t\tdb := tdb.Connect(t)\n\t\tdefer func() { _ = db.Close() }()\n\n\t\tmigrator := makeTestMigrator(WithDialect(tdb.Dialect))\n\t\terr := tdb.Dialect.CreateMigrationsTable(migrator.ctx, db, migrator.QuotedTableName())\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error occurred when creating migrations table: %s\", err)\n\t\t}\n\n\t\t// Test that we can re-run it again with no error\n\t\terr = tdb.Dialect.CreateMigrationsTable(migrator.ctx, db, migrator.QuotedTableName())\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Calling createMigrationsTable a second time failed: %s\", err)\n\t\t}\n\t})\n}", "func TestDBInit() *Sqlite {\n\ttestdb := &Sqlite{}\n\ttestdb.OpenDB(\"./../gorm_test.db\")\n\ttestdb.setMaxIdleConns(3)\n\ttestdb.logMode(true)\n\treturn testdb\n}", "func TestInitSchemaAlreadyInitialised(t *testing.T) {\n\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, []*Migration{})\n\n\t\t// Migrate with empty initialisation\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\treturn nil\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\t// Then migrate again, this time with a non empty initialisation\n\t\t// This second initialisation should not happen!\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"cars\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\t\tassert.NoError(t, m.Migrate())\n\n\t\tassert.False(t, m.hasTable(\"cars\"))\n\t\tassert.Equal(t, 1, tableCount(t, db, \"migrations\"))\n\t})\n}", "func InitDb() *gorm.DB {\n\tdb := openConnection()\n\n\tmodels.RunMigrations(db)\n\treturn db\n}", "func InitializeDB(models ...interface{}) *gorm.DB {\n\tdb, err := ConnectDB()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tdb.DB()\n\tfor _, model := range models {\n\t\tdb.AutoMigrate(model)\n\t}\n\n\treturn db\n}", "func InitDatabase() {\n\tvar err error\n\tdsn := \"root:@tcp(127.0.0.1)/test_server?charset=utf8mb4&parseTime=True&loc=Local\"\n\tDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})\n\n\tif err != nil {\n\t\tpanic(\"database is error\")\n\t}\n\n\tDB.AutoMigrate(&model.User{})\n\n\tfmt.Println(\"Database Connected\")\n}", "func Init() {\n\tcreateDB(\"backendtest\")\n\tuseDB(\"backendtest\")\n\tCreateUserTable()\n\tCreateEventTable()\n\tCreateAddFriendTable()\n}", "func (db *Postgres) initDB() error {\n\t// Create the schema\n\t// @afiune Can we rename this library?\n\tif err := migrator.Migrate(db.URI, db.SchemaPath); err != nil {\n\t\treturn errors.Wrapf(err, \"Unable to create database schema. [path:%s]\", db.SchemaPath)\n\t}\n\n\t// Add the tables to the database mappings\n\tdb.AddTableWithName(deployment{}, \"deployment\").SetKeys(true, \"id\")\n\tdb.AddTableWithName(supervisor{}, \"supervisor\").SetKeys(true, \"id\")\n\tdb.AddTableWithName(serviceGroup{}, \"service_group\").SetKeys(true, \"id\")\n\tdb.AddTableWithName(service{}, \"service\").SetKeys(true, \"id\")\n\n\t//return db.CreateTablesIfNotExists() // I don't think we can ensure the foreign keys\n\treturn nil\n}", "func InitDatabase(c *config.ConfigToml) *Test {\n\ttest := Test{}\n\ttest.cfg = c\n\treturn &test\n}", "func initialMigration() {\n\tdb, err := gorm.Open(\"sqlite3\", \"test.db\")\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\tdefer db.Close()\n\n\t// Migrate the schema\n\tdb.AutoMigrate(&User{})\n}", "func InitDb() {\n\tdbConnection.MustExec(schema)\n}", "func (test *Test) SetupDatabase() error {\n\treturn errors.New(\"Not implemented yet\")\n}", "func InitDB() *DB {\n\tdb, err := gorm.Open(dbEngine, dbName)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to initialize database: \", err.Error())\n\t}\n\n\tdb.AutoMigrate(&inventory.Stock{}, &inventory.StockIn{}, &inventory.StockOut{}, &inventory.StockValue{}, &inventory.SaleReport{})\n\n\treturn &DB{db}\n}", "func setupSingleTableDatabase(f *testhelpers.TestFerry, sourceDB, targetDB *sql.DB) {\n\tmaxId := 20\n\ttesthelpers.SeedInitialData(sourceDB, \"gftest\", \"table1\", maxId)\n\n\tfor i := 0; i < 4; i++ {\n\t\tquery := \"DELETE FROM gftest.table1 WHERE id = ?\"\n\t\t_, err := sourceDB.Exec(query, rand.Intn(maxId-1)+1)\n\t\ttesthelpers.PanicIfError(err)\n\t}\n\n\ttesthelpers.SeedInitialData(targetDB, \"gftest\", \"table1\", 0)\n}", "func setupDatabase(driver string, db *sql.DB) error {\n\treturn ddl.Migrate(driver, db)\n}", "func InitDB() {\n\tvar err error\n\tdb, err = gorm.Open(sqlite.Open(\"./test.db\"), &gorm.Config{})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\treturn\n}", "func autoMigrate(db *gorm.DB) {\n\tif os.Getenv(\"DROP_TABLES\") == \"yes\" {\n\t\t_ = db.Migrator().DropTable(&models.User{})\n\t\t_ = db.Migrator().DropTable(&models.Date{})\n\t\t_ = db.Migrator().DropTable(&models.DailyText{})\n\t}\n\n\tif os.Getenv(\"CREATE_TABLE\") == \"yes\" {\n\t\tif err := db.AutoMigrate(&models.User{}); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tif err := db.AutoMigrate(&models.Date{}); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tif err := db.AutoMigrate(&models.DailyText{}); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n}", "func InitTestDB() *sql.DB {\n\t// TODO: Read test info from config file\n\tvar err error\n\n\tvar conf = map[string]string{\n\t\t\"db_user\": \"taquilla\",\n\t\t\"db_passwd\": \"secret\",\n\t\t\"db_name\": \"taquillatest\",\n\t\t\"db_host\": \"localhost\",\n\t\t\"listen\": \"127.0.0.1:8080\",\n\t\t\"secret\": \"secretkeyVerySecret\",\n\t}\n\n\tdbConf := fmt.Sprintf(\n\t\t\"user=%s dbname=%s password=%s\",\n\t\tconf[\"db_user\"], conf[\"db_name\"], conf[\"db_passwd\"],\n\t)\n\n\tConn, err = sql.Open(\"postgres\", dbConf)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error connecting to the database\", err)\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn Conn\n}", "func DBInit() {\n\t// Mode = \"PRODUCTION\"\n\t// if Mode == \"PRODUCTION\" {\n\t// \tDatabaseURL = \"test.sqlite3\"\n\t// \tDatabaseName = \"sqlite3\"\n\t// } else if Mode == \"DEPLOY\" {\n\tDatabaseURL = os.Getenv(\"DATABASE_URL\")\n\tDatabaseName = \"postgres\"\n\t// }\n\n\tdb, err := gorm.Open(DatabaseName, DatabaseURL)\n\tif err != nil {\n\t\tpanic(\"We can't open database!(dbInit)\")\n\t}\n\t//残りのモデルはまだ入れてない。\n\tdb.AutoMigrate(&model.Post{})\n\tdb.AutoMigrate(&model.User{})\n\tdb.AutoMigrate(&model.Room{})\n\tdefer db.Close()\n}", "func InitTable(rebuildFlag bool) {\n\t// create a database connection\n\tengine, err := ConnectDB()\n\tif err != nil {\n\t\tlog.Errorf(\"database connect error: %s\", err)\n\t\treturn\n\t}\n\n\tif rebuildFlag {\n\t\t// recreating the tables.\n\t\tfor _, m := range db_models.TableLists {\n\t\t\t// table drop\n\t\t\terr := engine.DropTables(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"droptable error: %s\", err)\n\t\t\t}\n\t\t\t// table create\n\t\t\terr = engine.CreateTables(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"createtable error: %s\", err)\n\t\t\t}\n\t\t\terr = engine.CreateIndexes(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"createindex error: %s\", err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// create new tables, if they don't exist on the DB.\n\t\tfor _, m := range db_models.TableLists {\n\t\t\t// If the table has not been created, create it\n\t\t\tif exists, _ := engine.IsTableExist(m); !exists {\n\t\t\t\terr := engine.CreateTables(m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"createtable error: %s\", err)\n\t\t\t\t}\n\t\t\t\terr = engine.CreateIndexes(m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"createindex error: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func PrepareTests() (*pop.Connection, Env, error) {\n\n\tvar err error\n\tvar db *pop.Connection\n\tvar migrator pop.FileMigrator\n\n\tenv := make(map[string]string)\n\tenv[\"migrations\"] = os.Getenv(\"migrations_path\")\n\tenv[\"targetdb\"] = os.Getenv(\"database\")\n\tenv[\"pwd\"], err = os.Getwd()\n\t//env[\"new_key\"] = \"\" for every new env to be taken into consideration\n\n\tif err != nil {\n\t\treturn nil, env, err\n\t}\n\n\tdb, err = pop.Connect(env[\"targetdb\"])\n\n\tmigrator, err = pop.NewFileMigrator(env[\"migrations\"], db)\n\tif err != nil {\n\t\treturn nil, env, err\n\t}\n\n\terr = migrator.Reset()\n\tif err != nil {\n\t\treturn nil, env, err\n\t}\n\n\terr = migrator.Status()\n\tif err != nil {\n\t\treturn nil, env, err\n\t}\n\n\treturn db, env, err\n}", "func (d *DB) InitDB() {\n\tdb, err := gorm.Open(\"mysql\", \"root@/users?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tpanic(\"failed to connect to the database :(\")\n\t}\n\t// defer db.Close()\n\n\tdb.AutoMigrate(&User{})\n\n\td.db = db\n\td.CodeMap = make(map[string]CodeItem)\n\td.CodeMap[\"\"] = CodeItem{Code: -1}\n}", "func (c *PostgresClient) InitDB(models []interface{}) (*gorm.DB, error) {\n\tc.LogConfig()\n\terr := c.Connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.DB.LogMode(c.LogMode)\n\tc.CreateDBExtensions()\n\tc.Migrate(models)\n\treturn c.DB, nil\n}", "func InitDB() {\n\tvar err error\n\tdatabase.DBConn, err = gorm.Open(sqlite.Open(\"books.db\"), &gorm.Config{})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\tfmt.Println(\"Database successfully connected\")\n\tdatabase.DBConn.AutoMigrate(&book.Book{})\n}", "func initDb(db *sql.DB) error {\n\n\t_, err := db.Exec(`CREATE TABLE IF NOT EXISTS resource_metadata (\n\t\t\tid TEXT NOT NULL,\n\t\t\ttype TEXT NOT NULL,\n\t\t\tcreated_at TIMESTAMP NOT NULL,\n\t\t\tupdated_at TIMESTAMP NOT NULL,\n\t\t\tdeleted_at TIMESTAMP,\n\t\t\tparams JSONB NOT NULL,\n\t\t\tdata JSONB NOT NULL,\n\t\t\tPRIMARY KEY (id)\n\t)`)\n\tif err != nil {\n\t\tlog.Println(\"Unable to create resource_metadata table.\")\n\t\treturn fmt.Errorf(\"create resource_metadata table: %w\", err)\n\t}\n\n\treturn nil\n}", "func Initialize(dbDriver *sql.DB) {\n\tstatement, driverError := dbDriver.Prepare(trainTable)\n\tif driverError != nil {\n\t\tlog.Println(driverError)\n\t}\n\tstatement.Exec()\n\tstatement, _ = dbDriver.Prepare(stationTable)\n\tstatement.Exec()\n\tstatement, _ = dbDriver.Prepare(scheduleTable)\n\tstatement.Exec()\n\tlog.Println(\"All tables created/initialized successfully!\")\n}", "func InitialMigration() {\r\n\tdb, err = gorm.Open(\"sqlite3\", \"collegiateCS.db\")\r\n\tif err != nil {\r\n\t\tfmt.Println(err.Error())\r\n\t\tpanic(\"Failed to connect to db\")\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t//db.AutoMigrate(&dbStats{})\r\n\t//db.AutoMigrate(&dbPlayer{})\r\n\t//db.AutoMigrate(&dbRoster{})\r\n\t//db.AutoMigrate(&dbGame{})\r\n\t//db.AutoMigrate(&dbSet{})\r\n}", "func before(t *testing.T, db *storage.DB, sm *storage.SchemaManager) {\n\tv, dirty, err := sm.GetSchemaVersion(context.Background())\n\tif dirty {\n\t\tt.Fatalf(\"schema is marked dirty, refusing to proceed\")\n\t}\n\tif err != nil { //the migrations mechanism was not initialized yet\n\t\trequire.NoError(t, sm.MigrateSchemaToVersion(context.Background(), testWithSchemaVersion))\n\t\tv = testWithSchemaVersion\n\t}\n\t// wipe the database\n\tfor version := v; version > storage.EmptySchemaVersion; {\n\t\tversion, err = sm.MigrateSchemaDown(context.Background())\n\t\tassert.NoError(t, err)\n\t}\n\t// re-create the tables with supported schema\n\tassert.NoError(t, sm.MigrateSchemaToVersion(context.Background(), testWithSchemaVersion))\n\tassert.NoError(t, db.GeneratePartition(context.Background(), time.Date(2019, time.August, 1, 0, 0, 0, 0, time.UTC), 0))\n}", "func InitDb(dbConfig Config) (*sql.DB, error) {\n\tconnectionURL := newSQLServerConnectionURL(\n\t\tdbConfig.User, dbConfig.Pass, dbConfig.Host, dbConfig.Name, dbConfig.Port)\n\tcreateTableQuery := sqlServerTableCreationQuery\n\n\tlog.Debugf(\"Establishing connection with '%s'. Connection string: '%q'\", dbDriverName,\n\t\tstrings.Replace(connectionURL.String(), connectionURL.User.String() + \"@\", \"***:***@\", 1))\n\n\tdb, err := sql.Open(dbDriverName, connectionURL.String())\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while establishing connection to '%s'\", dbDriverName)\n\t}\n\n\tlog.Debug(\"Testing connection\")\n\tif err := db.Ping(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"while testing DB connection\")\n\t}\n\n\tq := strings.Replace(createTableQuery, \"{name}\", SanitizeSQLArg(dbConfig.DbOrdersTableName), -1)\n\tlog.Debugf(\"Ensuring table exists. Running query: '%q'.\", q)\n\tif _, err := db.Exec(q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"while initiating DB table\")\n\t}\n\n\treturn db, nil\n}", "func DBInit() *gorm.DB {\n\t//db, err := gorm.Open(\"mysql\", \"root:@tcp(128.199.211.144:3306)/godb?charset=utf8&parseTime=True&loc=Local\")\n\tdb, err := gorm.Open(\"mysql\",\"root:orion2402@tcp(localhost:3306)/popfren?charset=utf8&parseTime=True&loc=Local\")\n\tif err != nil {\n\t\tpanic(\"failed to connect to database\")\n\t}\n\n\tdb.AutoMigrate(structs.Person{})\n\treturn db\n}", "func (db *EdDb) initDbSchema() (err error) {\n\n\t// First, the persistent parts of the database (main.), then the\n\t// ephemeral parts (mem.)\n\t_, err = db.dbConn.Exec(`\n\n CREATE TABLE IF NOT EXISTS main.person (\n id INTEGER PRIMARY KEY,\n name TEXT NOT NULL,\n numUpdates INTEGER DEFAULT 0\n );\n\n CREATE TABLE mem.sessionActivity (\n id INTEGER PRIMARY KEY,\n personId INTEGER NOT NULL,\n dateTime DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n `)\n\treturn\n}", "func InitPostgresTest() *gorm.DB {\n\tconf := fmt.Sprintf(\n\t\t\"host=%s port=%s dbname=%s user=%s password=%s\",\n\t\tos.Getenv(\"SKYNET_TEST_DB_HOST\"),\n\t\tos.Getenv(\"SKYNET_TEST_DB_PORT\"),\n\t\tos.Getenv(\"SKYNET_TEST_DB_DBNAME\"),\n\t\tos.Getenv(\"SKYNET_TEST_DB_USER\"),\n\t\tos.Getenv(\"SKYNET_TEST_DB_PASSWORD\"),\n\t)\n\tdb, err := gorm.Open(\"postgres\", conf)\n\tif err != nil {\n\t\tpanic(\"failed to connect to database\")\n\t}\n\n\tdb.DropTableIfExists(\n\t\t&types.Unit{},\n\t\t&types.Prototype{},\n\t)\n\tdb.AutoMigrate(\n\t\t&types.Unit{},\n\t\t&types.Prototype{},\n\t)\n\n\treturn db\n}", "func (ctx *TestContext) populateDatabase() error {\n\t// We cannot run this for older tests because we're computing the tables permissions_generated and item_ancestors.\n\t// Older tests define those tables manually with inconsistencies, and then check that the content of those tables is\n\t// still in the same inconsistent state.\n\t// If we want this to be run everywhere, we would have to fix those tests first.\n\t// We would then just have to remove the ctx.needPopulateDatabase boolean completely.\n\tif !ctx.needPopulateDatabase {\n\t\treturn nil\n\t}\n\n\tdb, err := database.Open(ctx.db())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// add all the defined table rows in the database.\n\terr = database.NewDataStore(db).InTransaction(func(store *database.DataStore) error {\n\t\tstore.Exec(\"SET FOREIGN_KEY_CHECKS=0\")\n\t\tdefer store.Exec(\"SET FOREIGN_KEY_CHECKS=1\")\n\n\t\terr = ctx.addUsersIntoAllUsersGroup()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor tableName, tableRows := range ctx.dbTables {\n\t\t\tfor _, tableRow := range tableRows {\n\t\t\t\terr = database.NewDataStoreWithTable(store.DB, tableName).InsertOrUpdateMap(tableRow, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"populateDatabase %s %+v: %v\", tableName, tableRow, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ctx.DBItemsAncestorsAndPermissionsAreComputed()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ctx.DBGroupsAncestorsAreComputed()\n}", "func setupDatabase(i int) string {\n\t// Indicate that this is the prod database and not the test.\n\tdbDir := filepath.Join(os.TempDir(), \"test\")\n\t// Create the directory if it doesn't exist.\n\tif _, err := os.Stat(dbDir); os.IsNotExist(err) {\n\t\tos.Mkdir(dbDir, 0755)\n\t}\n\n\tdb := filepath.Join(dbDir, fmt.Sprintf(\"tracer-test-db-%d.db\", i))\n\t// Delete any existing database entries.\n\tconfigure.DeleteDatabase(db)\n\n\treturn db\n}", "func InitializeDB(connection *gorm.DB) {\n\tconnection.AutoMigrate(&ent.City{})\n\tconnection.AutoMigrate(&ent.CityCollection{})\n\n\tvar initialContent []ent.CityCollection\n\n\t// populate the database with initial fixtures if it is empty\n\tconnection.Find(&initialContent)\n\tif len(initialContent) == 0 {\n\t\tpopulateDatabase(connection)\n\t}\n}", "func SetupDB() {\n\tdb := OpenDB()\n\n\tmodels.AutoMigrate(db)\n\n\tif config.EnvRunSeeds {\n\t\trunSeeds(db)\n\t}\n}", "func SetupDatabase() {\n\tu := helper.GetEnv(\"DATABASE_USER\", \"golang\")\n\tp := helper.GetEnv(\"DATABSE_PASSWORD\", \"golang\")\n\th := helper.GetEnv(\"DATABASE_HOST\", \"localhost:3306\")\n\tn := helper.GetEnv(\"DATABASE_NAME\", \"go_test\")\n\tq := \"charset=utf8mb4&parseTime=True&loc=Local\"\n\n\t// Assemble the connection string.\n\tdsn := fmt.Sprintf(\"%s:%s@tcp(%s)/%s?%s\", u, p, h, n, q)\n\n\t// Connect to the database.\n\tdb, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})\n\n\t// Migrate the schema\n\tdb.AutoMigrate(&User{})\n\n\tif err != nil {\n\t\tpanic(\"Could not open database connection\")\n\t}\n\n\tDB = db\n}", "func InitDatabase(db *sql.DB) {\n\tcreateLinksTableSQL := `CREATE TABLE IF NOT EXISTS links (\n\t\t\"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n\t\t\"url\" TEXT,\n\t\t\"created_at\" TEXT\n\t);`\n\n\tstatement, err := db.Prepare(createLinksTableSQL)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating links table: %v\\n\", err)\n\t}\n\tstatement.Exec()\n}", "func InitDb(conf config.Config, reset bool) error {\n\tif !IsOpen() {\n\t\tif err := openAdapter(conf); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn adp.CreateDb(reset)\n}", "func InitModel(config std.ConfigMySQL) {\n\tdb = std.CreateDB(config)\n\tstd.LogInfoLn(\"start init mysql model\")\n\n\tdb.AutoMigrate(&AssertionResult{}, &Watcher{}, &WatcherSnapshot{})\n\tstd.LogInfoLn(\"end init mysql model\")\n}", "func SetupDB() {\n\n\t// sqlite \"gorm.io/driver/sqlite\"\n\t//database, err := gorm.Open(sqlite.Open(\"database.db\"), &gorm.Config{})\n\n\t// mysql \"gorm.io/driver/mysql\"\n\t// dsn := \"root:@tcp(127.0.0.1:3306)/cmgostock?charset=utf8mb4&parseTime=True&loc=Local\"\n\t// database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})\n\n\t// postgresql \t\"gorm.io/driver/postgres\"\n\tdsn := \"host=10.82.69.121 user=postgres password=1234 dbname=cmgostock port=5432 sslmode=disable TimeZone=Asia/Bangkok\"\n\t//dsn := \"host=localhost user=postgres password=1234 dbname=cmgostock port=5432 sslmode=disable TimeZone=Asia/Bangkok\"\n\t database, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\tdatabase.AutoMigrate(&model.User{})\n\tdatabase.AutoMigrate(&model.Product{})\n\tdatabase.AutoMigrate(&model.Transaction{})\n\n\tdb = database\n}", "func (b *DatabaseTestSuiteBase) SetupTest() {\n\tassert := require.New(b.T())\n\n\ttx, err := storage.DB().Beginx()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tb.tx = tx\n\n\tstorage.RedisClient().FlushAll(context.Background())\n\tassert.NoError(storage.MigrateDown(storage.DB().DB))\n\tassert.NoError(storage.MigrateUp(storage.DB().DB))\n}", "func (b *bot) migrateDB() {\n\tif _, err := b.DB().Exec(`create table if not exists variables (\n\t\t\tid integer primary key,\n\t\t\tname string,\n\t\t\tvalue string\n\t\t);`); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Initial db migration create variables table\")\n\t}\n\tif _, err := b.DB().Exec(`create table if not exists pluginBlacklist (\n\t\t\tchannel string,\n\t\t\tname string,\n\t\t\tprimary key (channel, name)\n\t\t);`); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Initial db migration create blacklist table\")\n\t}\n\tif _, err := b.DB().Exec(`create table if not exists pluginWhitelist (\n\t\t\tname string primary key\n\t\t);`); err != nil {\n\t\tlog.Fatal().Err(err).Msgf(\"Initial db migration create whitelist table\")\n\t}\n}", "func TestDebugMigrateDatabase(t *testing.T) {\n\tassert := asrt.New(t)\n\n\torigDir, _ := os.Getwd()\n\n\tsite := TestSites[0]\n\t_ = os.Chdir(site.Dir)\n\n\tapp, err := ddevapp.NewApp(site.Dir, false)\n\tassert.NoError(err)\n\n\tapp.Database.Type = nodeps.MariaDB\n\tapp.Database.Version = nodeps.MariaDBDefaultVersion\n\n\tt.Cleanup(func() {\n\t\tout, err := exec.RunHostCommand(DdevBin, \"debug\", \"migrate-database\", fmt.Sprintf(\"%s:%s\", nodeps.MariaDB, nodeps.MariaDBDefaultVersion))\n\t\tassert.NoError(err, \"failed to migrate database; out='%s'\", out)\n\n\t\tassert.Contains(out, fmt.Sprintf(\"database was converted to %s:%s\", nodeps.MariaDB, nodeps.MariaDBDefaultVersion))\n\n\t\tout, stderr, err := app.Exec(&ddevapp.ExecOpts{\n\t\t\tService: \"db\",\n\t\t\tCmd: fmt.Sprintf(`mysql -e 'DROP TABLE IF EXISTS %s;'`, t.Name()),\n\t\t})\n\t\tassert.NoError(err, \"DROP table didn't work, out='%s', stderr='%s'\", out, stderr)\n\t\t_ = os.Chdir(origDir)\n\t})\n\n\terr = app.Start()\n\trequire.NoError(t, err)\n\n\tout, _, err := app.Exec(&ddevapp.ExecOpts{\n\t\tService: \"db\",\n\t\tCmd: `mysql -N -e 'SELECT VERSION();'`,\n\t})\n\trequire.NoError(t, err)\n\trequire.True(t, strings.HasPrefix(out, nodeps.MariaDB104))\n\n\t// Import a database so we have something to work with\n\terr = app.ImportDB(filepath.Join(origDir, \"testdata\", t.Name(), \"users.sql\"), \"\", false, false, \"\")\n\trequire.NoError(t, err)\n\n\t_, _, err = app.Exec(&ddevapp.ExecOpts{\n\t\tService: \"db\",\n\t\tCmd: fmt.Sprintf(`mysql -e 'CREATE TABLE IF NOT EXISTS example_table (name VARCHAR(255) NOT NULL); INSERT INTO example_table (name) VALUES (\"%s\");'`, t.Name()),\n\t})\n\trequire.NoError(t, err)\n\n\t// Try a migration\n\tout, err = exec.RunHostCommand(DdevBin, \"debug\", \"migrate-database\", fmt.Sprintf(\"%s:%s\", nodeps.MySQL, nodeps.MySQL80))\n\trequire.NoError(t, err, \"failed to migrate database; out='%s'\", out)\n\trequire.Contains(t, out, fmt.Sprintf(\"database was converted to %s:%s\", nodeps.MySQL, nodeps.MySQL80))\n\n\t// Make sure our inserted data is still there\n\tout, _, err = app.Exec(&ddevapp.ExecOpts{\n\t\tService: \"db\",\n\t\tCmd: fmt.Sprintf(`mysql -N -e 'SELECT name FROM example_table WHERE name = \"%s\";'`, t.Name()),\n\t})\n\trequire.NoError(t, err)\n\trequire.Contains(t, out, t.Name())\n\n\t// Make sure we have the expected new version\n\tout, _, err = app.Exec(&ddevapp.ExecOpts{\n\t\tService: \"db\",\n\t\tCmd: `mysql -N -e 'SELECT VERSION();'`,\n\t})\n\trequire.NoError(t, err)\n\trequire.True(t, strings.HasPrefix(out, nodeps.MySQL80))\n}", "func Setup(t *testing.T) db.DB {\n\t// The below values ought to match what is configured\n\t// in the Makefile, under the integration-test target:\n\tconfig := &db.Config{\n\t\tRawURI: \"postgres://[email protected]:5432/users_test?sslmode=disable\",\n\t\tMigrationsDir: \"/go/src/github.com/weaveworks-experiments/kubernetes-deployment-strategies-workload/pkg/db/migrations\",\n\t\tSchemaVersion: db.SchemaVersion,\n\t}\n\tdatabase, err := db.NewPostgreSQLDB(config)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, database)\n\treturn database\n}", "func SetupMySQLTestDatabase(t *testing.T, migrationSteps []database.MigrationStep) *MySQLTestDatabase {\n\tconf := LocalTestRootDatabaseConfig(migrationSteps)\n\tlockVdb := GetMySQlLock(t, conf)\n\trootVdb := database.NewVersionedDB(conf)\n\tClearMySQLTables(t, rootVdb)\n\tif err := rootVdb.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\trootVdb = database.NewVersionedDB(conf)\n\tif err := rootVdb.Migrate(rootVdb.MaxDBVersion()); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := rootVdb.Close(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn &MySQLTestDatabase{lockVdb, t}\n}", "func (db *DB) Setup() error {\n\tconn := db.dbconn\n\n\tconn.AutoMigrate(&AdminAccount{})\n\n\tif !conn.HasTable(db.tableName) {\n\t\treturn trace.NotFound(\"table not found in DB, Migration fail\")\n\t}\n\treturn nil\n}", "func setupDB(db *sql.DB) error {\n\tsqlScript, err := ioutil.ReadFile(\"dbSchema.sql\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstatements := strings.Split(string(sqlScript), \";\")\n\tif len(statements) > 0 {\n\t\tstatements = statements[:len(statements)-1]\n\t}\n\n\tfor _, statement := range statements {\n\t\t_, err = db.Exec(statement)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func initializeTestDatabaseTemplate(ctx context.Context, t *testing.T) {\n\n\tt.Helper()\n\n\tinitTestDatabaseHash(t)\n\n\tinitIntegresClient(t)\n\n\tif err := client.SetupTemplateWithDBClient(ctx, hash, func(db *sql.DB) error {\n\n\t\tt.Helper()\n\n\t\terr := applyMigrations(t, db)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = insertFixtures(ctx, t, db)\n\n\t\treturn err\n\t}); err != nil {\n\n\t\t// This error is exceptionally fatal as it hinders ANY future other\n\t\t// test execution with this hash as the template was *never* properly\n\t\t// setuped successfully. All GetTestDatabase will wait unti timeout\n\t\t// unless we interrupt them by discarding the base template...\n\t\tdiscardError := client.DiscardTemplate(ctx, hash)\n\n\t\tif discardError != nil {\n\t\t\tt.Fatalf(\"Failed to setup template database, also discarding failed for hash %q: %v, %v\", hash, err, discardError)\n\t\t}\n\n\t\tt.Fatalf(\"Failed to setup template database (discarded) for hash %q: %v\", hash, err)\n\n\t}\n}", "func (db database) Init() error {\n\tscript := `CREATE TABLE IF NOT EXISTS txs (\n\t\thash VARCHAR NOT NULL PRIMARY KEY,\n\t\tstatus SMALLINT,\n\t\tcreated_time BIGINT,\n\t\tselector VARCHAR(255),\n\t\ttxid VARCHAR,\n\t\ttxindex BIGINT,\n\t\tamount VARCHAR(100),\n\t\tpayload VARCHAR,\n\t\tphash VARCHAR,\n\t\tto_address VARCHAR,\n\t\tnonce VARCHAR,\n\t\tnhash VARCHAR,\n\t\tgpubkey VARCHAR,\n\t\tghash VARCHAR,\n\t\tversion VARCHAR\n\t);\nCREATE TABLE IF NOT EXISTS gateways (\n\t\tgateway_address VARCHAR NOT NULL PRIMARY KEY,\n\t\tstatus SMALLINT,\n\t\tcreated_time BIGINT,\n\t\tselector VARCHAR(255),\n\t\tpayload VARCHAR,\n\t\tphash VARCHAR,\n\t\tto_address VARCHAR,\n\t\tnonce VARCHAR,\n\t\tnhash VARCHAR,\n\t\tgpubkey VARCHAR,\n\t\tghash VARCHAR,\n\t\tversion VARCHAR\n);\n`\n\t_, err := db.db.Exec(script)\n\treturn err\n}", "func SetupAndMigrate(\n\tctx context.Context,\n\tlog logrus.FieldLogger,\n\tdb interface {\n\t\tBeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)\n\t\tExec(context.Context, string, ...any) (pgconn.CommandTag, error)\n\t},\n\ttableName string,\n\tschemas []string,\n) error {\n\ttableName = pgx.Identifier{tableName}.Sanitize()\n\n\tvar version int32\n\tvar migrateErr error\n\n\t// this is split off from the rest because we might not have permissions to\n\t// CREATE TABLE, which is checked even if the table exists\n\tif _, err := RetryIdempotent(ctx, log, func() (struct{}, error) {\n\t\t_, err := db.Exec(ctx,\n\t\t\tfmt.Sprintf(`CREATE TABLE IF NOT EXISTS %v (\n\t\t\t\tversion integer PRIMARY KEY CHECK (version > 0),\n\t\t\t\tcreated timestamptz NOT NULL DEFAULT now()\n\t\t\t)`, tableName), pgx.QueryExecModeExec,\n\t\t)\n\t\treturn struct{}{}, trace.Wrap(err)\n\t}); err != nil {\n\t\t// the very first SELECT in the next transaction will fail, we don't\n\t\t// need anything higher than debug here\n\t\tlog.WithError(err).Debugf(\"Failed to confirm the existence of the %v table.\", tableName)\n\t}\n\n\tconst idempotent = true\n\tif err := RetryTx(ctx, log, db, pgx.TxOptions{\n\t\tIsoLevel: pgx.Serializable,\n\t\tAccessMode: pgx.ReadWrite,\n\t}, idempotent, func(tx pgx.Tx) error {\n\t\tif err := tx.QueryRow(ctx,\n\t\t\tfmt.Sprintf(\"SELECT COALESCE(max(version), 0) FROM %v\", tableName),\n\t\t\tpgx.QueryExecModeExec,\n\t\t).Scan(&version); err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\tif int(version) > len(schemas) {\n\t\t\tmigrateErr = trace.BadParameter(\"unsupported schema version %v\", version)\n\t\t\t// the transaction succeeded, the error is outside of the transaction\n\t\t\treturn nil\n\t\t}\n\n\t\tif int(version) == len(schemas) {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, s := range schemas[version:] {\n\t\t\tif _, err := tx.Exec(ctx, s, pgx.QueryExecModeExec); err != nil {\n\t\t\t\treturn trace.Wrap(err)\n\t\t\t}\n\t\t}\n\n\t\tif _, err := tx.Exec(ctx,\n\t\t\tfmt.Sprintf(\"INSERT INTO %v (version) VALUES ($1)\", tableName),\n\t\t\tpgx.QueryExecModeExec, len(schemas),\n\t\t); err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif migrateErr != nil {\n\t\treturn trace.Wrap(migrateErr)\n\t}\n\n\tif int(version) != len(schemas) {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"previous_version\": version,\n\t\t\t\"current_version\": len(schemas),\n\t\t}).Info(\"Migrated database schema.\")\n\t}\n\n\treturn nil\n}", "func setupDatabase(db *sql.DB) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\t// Creating a timescaledb extension for the database\n\tconst ext = `CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;`\n\tif _, err = tx.Exec(ext); err != nil {\n\t\treturn err\n\t}\n\n\t// creating schema in the database\n\tconst sch = `CREATE SCHEMA IF NOT EXISTS \"audit\"`\n\tif _, err = tx.Exec(sch); err != nil {\n\t\treturn err\n\t}\n\n\t// creating the audit log table\n\tconst tbl = `CREATE TABLE IF NOT EXISTS audit.\"Logs\" (\n\t\t\"Timestamp\" TIMESTAMPTZ NOT NULL,\n\t\t\"UserId\" text NOT NULL,\n\t\t\"Action\" text NOT NULL\n\t );`\n\tif _, err = tx.Exec(tbl); err != nil {\n\t\treturn err\n\t}\n\n\t// creating the hypertable of audit log table for timescaledb\n\tconst hptbl = `SELECT create_hypertable('audit.\"Logs\"', 'Timestamp',if_not_exists => true);`\n\tif _, err = tx.Exec(hptbl); err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (st *Store) initDB() error {\n\n\tvar err error\n\n\tver, err := st.schemaVersion()\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch ver {\n\tcase 0:\n\t\t// starting from scratch\n\t\tschema := `\nCREATE TABLE url (\n\tid INTEGER PRIMARY KEY,\n\turl TEXT NOT NULL,\n\thash TEXT NOT NULL,\n\tpage_id INTEGER NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,\n\tFOREIGN KEY(page_id) REFERENCES page(id)\n);\n\nCREATE TABLE page (\n\tid INTEGER PRIMARY KEY,\n\tcanonical_url TEXT NOT NULL,\n\ttitle TEXT NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\n);\n\nCREATE TABLE warning (\n\tid INTEGER PRIMARY KEY,\n\tpage_id INTEGER NOT NULL,\n\tkind TEXT NOT NULL,\n\tquant INT NOT NULL,\n\tcreated TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,\n\tFOREIGN KEY(page_id) REFERENCES page(id)\n);\n\n\nCREATE TABLE version (\n\tver INTEGER NOT NULL );\n\nINSERT INTO version (ver) VALUES (1);\n`\n\t\t//\t\t`CREATE INDEX article_tag_artid ON article_tag(article_id)`,\n\t\t//\t\t`CREATE INDEX article_url_artid ON article_url(article_id)`,\n\n\t\t_, err = st.db.Exec(schema)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbreak\n\tcase 1: // all good. this is what we're expecting\n\t\tbreak\n\tdefault:\n\t\treturn fmt.Errorf(\"Bad db schema version (expected 1, got %d)\", ver)\n\t}\n\n\treturn nil\n}", "func TestMultiSchemaSupport(t *testing.T) {\n\twithEachTestDB(t, func(t *testing.T, tdb *TestDB) {\n\t\tmusic := NewMigrator(WithDialect(tdb.Dialect), WithTableName(\"music_migrations\"))\n\t\tcontacts := NewMigrator(WithDialect(tdb.Dialect), WithTableName(\"contacts_migrations\"))\n\n\t\t// Use the same connection for both sets of migrations\n\t\tdb := tdb.Connect(t)\n\t\tdefer func() { _ = db.Close() }()\n\n\t\t// Apply the Music migrations\n\t\terr := music.Apply(db, testMigrations(t, \"music\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to apply music migrations: %s\", err)\n\t\t}\n\n\t\t// ... then the Contacts Migrations\n\t\terr = contacts.Apply(db, testMigrations(t, \"contacts\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to apply contact migrations: %s\", err)\n\t\t}\n\n\t\t// Then run a SELECT COUNT(*) query on each table to ensure that all of the\n\t\t// expected tables are co-existing in the same database and that they all\n\t\t// contain the expected number of rows (this approach is admittedly odd,\n\t\t// but it relies only on ANSI SQL code, so it should run on any SQL database).\n\t\texpectedRowCounts := map[string]int{\n\t\t\t\"music_migrations\": 3,\n\t\t\t\"contacts_migrations\": 3,\n\t\t\t\"contacts\": 1,\n\t\t\t\"phone_numbers\": 3,\n\t\t\t\"addresses\": 2,\n\t\t\t\"artists\": 0,\n\t\t\t\"albums\": 0,\n\t\t\t\"tracks\": 0,\n\t\t}\n\t\tfor table, expectedRowCount := range expectedRowCounts {\n\t\t\tqtn := tdb.Dialect.QuotedTableName(\"\", table)\n\t\t\tactualCount := -1 // Don't initialize to 0 because that's an expected value\n\t\t\tquery := fmt.Sprintf(\"SELECT COUNT(*) FROM %s\", qtn)\n\t\t\trows, err := db.Query(query)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t\tif rows != nil && rows.Next() {\n\t\t\t\terr = rows.Scan(&actualCount)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"Expected rows\")\n\t\t\t}\n\t\t\tif actualCount != expectedRowCount {\n\t\t\t\tt.Errorf(\"Expected %d rows in table %s. Got %d\", expectedRowCount, qtn, actualCount)\n\t\t\t}\n\t\t}\n\t})\n}", "func setupDB(t testing.TB) *reform.DB {\n\tt.Helper()\n\n\tif testing.Short() {\n\t\tt.Skip(\"skipping in short mode\")\n\t}\n\n\tdb := test.ConnectToTestDB()\n\tpl := reform.NewPrintfLogger(t.Logf)\n\tpl.LogTypes = true\n\tdb.Logger = pl\n\tdb.Querier = db.WithTag(\"test:%s\", t.Name())\n\n\tcheckForeignKeys(t, db.Querier)\n\treturn db\n}", "func CreateTestTables() (err error) {\n\terr = createTable(\"users\")\n\treturn\n}", "func (t TicketsDB) migrateDB(sqlFiles ...string) error {\n\tfor _, sqlFile := range sqlFiles {\n\t\tsetupScript, err := ioutil.ReadFile(sqlFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = t.DB.Exec(string(setupScript))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Init() {\n\tdb, err = gorm.Open(getDBConfig())\n\tif err != nil {\n\t\tpanic(\"failed to connect database\")\n\t}\n\n\t// スキーマのマイグレーション\n\tdb.AutoMigrate(&model.Project{})\n\tdb.AutoMigrate(model.Tag{}).AddForeignKey(\"project_id\", \"projects(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.AutoMigrate(model.Member{}).AddForeignKey(\"project_id\", \"projects(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.AutoMigrate(model.ShuffleLogHead{}).AddForeignKey(\"project_id\", \"projects(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.AutoMigrate(model.ShuffleLogDetail{}).AddForeignKey(\"shuffle_log_head_id\", \"shuffle_log_heads(id)\", \"RESTRICT\", \"RESTRICT\")\n}", "func (env *Env) InitDB(filename string) {\n\t// sqlite3 database\n\tdb, err := gorm.Open(\"sqlite3\", filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// setup schema\n\tdb.AutoMigrate(&WineInfo{})\n\n\tenv.db = db\n}", "func SetupDatabase(db *gorm.DB, logMode bool) {\n\tdb.LogMode(logMode)\n\n\tuserDB = models.NewUserDB(*db)\n}", "func InitDB(dbPath string) *gorm.DB {\n\tdb, err := gorm.Open(\"sqlite3\", dbPath)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdb.AutoMigrate(&GPSDataSet{})\n\n\treturn db\n}", "func setupDatabase(db *sqlx.DB) error {\n\t// turn on write-ahead log and store temp tables on disk.\n\t_, err := db.Exec(`\n\t\tPRAGMA journal_mode=WAL;\n\t\tPRAGMA temp_store=1;\n\t\tPRAGMA foreign_keys=ON;\n\t\tPRAGMA encoding='UTF-8';\n\t`)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"execute PRAGMAs: %w\", err)\n\t}\n\n\ttx, err := db.Beginx()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"begin Tx: %w\", err)\n\t}\n\tdefer tx.Rollback()\n\n\tvar version int\n\tif err = tx.Get(&version, `PRAGMA user_version;`); err != nil {\n\t\treturn fmt.Errorf(\"PRAGMA user_version: %w\", err)\n\t}\n\tlog.Printf(\"[repo] current schema: %d\", version)\n\n\tswitch version {\n\tcase 0:\n\t\tlog.Printf(\"initialising database ...\")\n\t\t_, err = tx.Exec(`\n\t\t\t-- data table\n\t\t\tCREATE TABLE IF NOT EXISTS codepoints (\n\t\t\t\thex TEXT PRIMARY KEY,\n\t\t\t\tdec INTEGER,\n\t\t\t\tcategory TEXT,\n\t\t\t\tname TEXT,\n\t\t\t\taliases TEXT,\n\t\t\t\tentity TEXT\n\t\t\t);\n\t\t\t-- CREATE INDEX IF NOT EXISTS idx_hex ON codepoints(hex);\n\n\t\t\t-- full-text search\n\t\t\tCREATE VIRTUAL TABLE IF NOT EXISTS search USING FTS5(\n\t\t\t\tname,\n\t\t\t\taliases,\n\t\t\t\tentity,\n\t\t\t\thex,\n\t\t\t\tdec,\n\t\t\t\tcontent = 'codepoints',\n\t\t\t\ttokenize = \"unicode61 remove_diacritics 1 separators '-'\"\n\t\t\t);\n\n\t\t\tCREATE TRIGGER IF NOT EXISTS codepoints_ai AFTER INSERT ON codepoints\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO search (rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES (new.rowid, new.name, new.aliases, new.entity, new.hex, new.dec);\n\t\t\tEND;\n\t\t\tCREATE TRIGGER IF NOT EXISTS codepoints_ad AFTER DELETE ON codepoints\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO search (search, rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES ('delete', old.rowid, old.name, old.aliases, old.entity, old.hex, old.dec);\n\t\t\tEND;\n\t\t\tCREATE TRIGGER IF NOT EXISTS codepoints_au AFTER UPDATE ON codepoints\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO search (search, rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES ('delete', old.rowid, old.name, old.aliases, old.entity, old.hex, old.dec);\n\t\t\t\tINSERT INTO search (rowid, name, aliases, entity, hex, dec)\n\t\t\t\t\tVALUES (new.rowid, new.name, new.aliases, new.entity, new.hex, new.dec);\n\t\t\tEND;\n\n\t\t\tPRAGMA user_version = 1;\n\t\t`)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"migrate to version 1: %w\", err)\n\t\t}\n\t\tfallthrough\n\tcase 1: // future migration\n\t\tbreak\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn fmt.Errorf(\"commit schema updates: %w\", err)\n\t}\n\tvar n int\n\tif err = db.Get(&n, `PRAGMA user_version;`); err != nil {\n\t\treturn fmt.Errorf(\"PRAGMA user_version: %w\", err)\n\t}\n\n\tif n > version {\n\t\tif _, err := db.Exec(`VACUUM;`); err != nil {\n\t\t\treturn fmt.Errorf(\"VACUUM database: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func dbInit(dbc co.DbConnectionRequest) {\n\tdb, err := sql.Open(\"mysql\", dbc.User+\":\"+dbc.Pwd+\"@tcp(\"+dbc.Server+\":\"+dbc.Port+\")/\")\n\tif err != nil {\n\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t}\n\tfor _, stmt := range organizationsSchema {\n\t\tfmt.Println(stmt)\n\t\t_, err := db.Exec(stmt)\n\t\tif err != nil {\n\t\t\tpanic(err.Error()) // proper error handling instead of panic in your app\n\t\t}\n\t}\n\tdb.Close()\n\treturn\n}", "func doDatabaseMigrations(db *WowDB, env *Env, blizzard Blizzard) {\n\n\tif ! db.HasTable(&Race{}) {\n\t\tlog.Debug(\"Migrating race\")\n\t\tdb.AutoMigrate(&Race{})\n\t\terr := UpdateRacesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update races: %v\", err)\n\t\t}\n\t}\n\n\tif ! db.HasTable(&ToonClass{}) {\n\t\tlog.Println(\"Migrating classes\")\n\t\tdb.AutoMigrate(&ToonClass{})\n\t\terr := UpdateClassesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update classes: %v\", err)\n\t\t}\n\t}\n\n\tdb.AutoMigrate(&Stat{})\n\tdb.AutoMigrate(&Toon{})\n\n\tif ! db.HasTable(&ClassColor{}) {\n\t\tdb.AutoMigrate(&ClassColor{})\n\t\tdb.Model(&ClassColor{}).AddForeignKey(\"toon_class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\t\tvar tColor = ClassColor{ToonClassID: 1, Color: \"#C79C63\"}\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 2\n\t\ttColor.Color = \"#F58CBA\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 3\n\t\ttColor.Color = \"#ABD473\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 4\n\t\ttColor.Color = \"#FFF569\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 5\n\t\ttColor.Color = \"#F0EBE0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 6\n\t\ttColor.Color = \"#C41F3B\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 7\n\t\ttColor.Color = \"#0070DE\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 8\n\t\ttColor.Color = \"#69CCF0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 9\n\t\ttColor.Color = \"#9482C9\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 10\n\t\ttColor.Color = \"#00FF96\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 11\n\t\ttColor.Color = \"#FF7D0A\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 12\n\t\ttColor.Color = \"#A330C9\"\n\t\tdb.Create(&tColor)\n\t}\n\n\tdb.Model(&Toon{}).AddForeignKey(\"race_id\", \"races(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Toon{}).AddForeignKey(\"class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddForeignKey(\"toon_id\", \"toons(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddUniqueIndex(\"idx_toon_id_create_date\", \"toon_id\", \"insert_date\")\n}", "func InitTables(db *sql.DB, dropTables []string, initQueries []string) error {\n\tfor _, v := range dropTables {\n\t\t_, err := db.Exec(\"DROP TABLE IF EXISTS \" + v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, v := range initQueries {\n\t\t_, err := db.Exec(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func InitializeDB() *Database {\n\tconfig := new(dbConfig)\n\tconfigFile, err := ioutil.ReadFile(\"config.yaml\")\n\terr = yaml.Unmarshal(configFile, &config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tcredentials := fmt.Sprintf(\"%s:%s@/%s?charset=utf8&parseTime=True&loc=Local\", config.Database.DatabaseUser, config.Database.DatabasePassword, config.Database.Database)\n\tdialect := config.Database.DatabaseType\n\n\tdb, err := gorm.Open(dialect, credentials)\n\tif err != nil {\n\t\tlog.Fatal().Msgf(\"Failed to connect to Database. Reason: %v\\n\", err)\n\t}\n\tlog.Info().Msg(\"Successfully connected to qBot Database.\")\n\n\tdb.DB().SetConnMaxLifetime(time.Second * 100)\n\tdb.DB().SetMaxIdleConns(50)\n\tdb.DB().SetMaxOpenConns(200)\n\n\t//db.DropTableIfExists(models.User{}, models.Question{}, models.Answer{}) // Temp\n\t//db.DropTable(\"user_questions\", \"question_answers\", \"user_answers\") // Temp\n\tif err := db.AutoMigrate(models.User{}, models.Question{}, models.Answer{}).Error; err != nil {\n\t\tlog.Fatal().Msgf(\"Unable to migrate database. \\nReason: %v\", err)\n\t}\n\tlog.Info().Msg(\"Database migration successful.\")\n\treturn &Database{db}\n}", "func runTestsOnNewDB(c *C, overrider configOverrider, dbName string, tests ...func(dbt *DBTest)) {\n\tdsn := getDSN(overrider, func(config *mysql.Config) {\n\t\tconfig.DBName = \"\"\n\t})\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tc.Assert(err, IsNil, Commentf(\"Error connecting\"))\n\tdefer db.Close()\n\n\t_, err = db.Exec(fmt.Sprintf(\"DROP DATABASE IF EXISTS `%s`;\", dbName))\n\tc.Assert(err, IsNil, Commentf(\"Error drop database %s: %s\", dbName, err))\n\n\t_, err = db.Exec(fmt.Sprintf(\"CREATE DATABASE `%s`;\", dbName))\n\tc.Assert(err, IsNil, Commentf(\"Error create database %s: %s\", dbName, err))\n\n\tdefer func() {\n\t\t_, err = db.Exec(fmt.Sprintf(\"DROP DATABASE IF EXISTS `%s`;\", dbName))\n\t\tc.Assert(err, IsNil, Commentf(\"Error drop database %s: %s\", dbName, err))\n\t}()\n\n\t_, err = db.Exec(fmt.Sprintf(\"USE `%s`;\", dbName))\n\tc.Assert(err, IsNil, Commentf(\"Error use database %s: %s\", dbName, err))\n\n\tdbt := &DBTest{c, db}\n\tfor _, test := range tests {\n\t\ttest(dbt)\n\t\tdbt.db.Exec(\"DROP TABLE IF EXISTS test\")\n\t}\n}", "func InitDb(drop bool) {\n\tdb, err := dbOpen()\n\tdefer db.Close()\n\tif drop {\n\t\tstatement, err := db.Prepare(\"DROP TABLE IF EXISTS mail\")\n\t\tdefer statement.Close()\n\t\tcheckError(err)\n\t\tstatement.Exec()\n\t}\n\tstatement, err := db.Prepare(\n\t\t\"CREATE TABLE IF NOT EXISTS mail (id INTEGER PRIMARY KEY, sender TEXT, receiver TEXT, subject TEXT, text TEXT, html TEXT)\",\n\t)\n\tdefer statement.Close()\n\tcheckError(err)\n\tstatement.Exec()\n}", "func Setup() {\n\tvar err error\n\tdb, err = gorm.Open(mysql.Open(fmt.Sprintf(\"%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local\",\n\t\tconfig.DatabaseConfiguration.User,\n\t\tconfig.DatabaseConfiguration.Password,\n\t\tconfig.DatabaseConfiguration.Host,\n\t\tconfig.DatabaseConfiguration.Name)), &gorm.Config{\n\t\tNamingStrategy: schema.NamingStrategy{\n\t\t\tSingularTable: true,\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to connect to database. err: %v\", err)\n\t}\n\n\tif err = migrateDatabase(); err != nil {\n\t\tlog.Fatalf(\"failed to migrate database. err: %v\", err)\n\t}\n}", "func init() {\n\t// Open a connection to GORM\n\tdb, err := gorm.Open(\"sqlite3\", \"shop.db\")\n\tif err != nil {\n\t\tpanic(\"Failed to connect database\")\n\t}\n\n\tDB = db\n\n\tDB.AutoMigrate(models.Supply{})\n}", "func PrepareTest(t *testing.T) *sql.DB {\n\tt.Helper()\n\t//prepare mengahpus dan membuat database\n\tdb, err := connectDB(defaultdb, user, password)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := dropDB(db, dbtest); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err = createDB(db, dbtest); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdb.Close()\n\t//membuat table\n\tdb, err = connectDB(dbtest, user, password)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := db.Exec(model.TBMahasiswa); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn db\n}", "func InitDB() {\n\tvar err error\n\tvar dsn = os.Getenv(\"REVELAPP_DBUSER\") +\n\t\t\":\" + os.Getenv(\"REVELAPP_DBPASSWD\") +\n\t\t\"@\" + os.Getenv(\"REVELAPP_DBHOSTNAME\") +\n\t\t\"/\" + os.Getenv(\"REVELAPP_DBNAME\") +\n\t\t\"?parseTime=true&loc=Asia%2FTokyo\"\n\t// open db\n\tGdb, err = gorm.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\tprintln(\"FATAL\", err)\n\t\tpanic(err)\n\t}\n\tautoMigrate()\n\t// unique index if need\n\t//Gdb.Model(&models.User{}).AddUniqueIndex(\"idx_user_name\", \"name\")\n}", "func InitDB(db *mgo.Database) {\n\tfor i := range workIndexes {\n\t\terr := db.C(workIndexes[i].Name).EnsureIndex(workIndexes[i].Index)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}\n}", "func InitDB() (*gorm.DB, error) {\n\tdb, err := gorm.Open(\"sqlite3\", \"./url.db\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb.LogMode(true)\n\tmodels.Migrate(db)\n\treturn db, err\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := gormigrate.New(db.db, gormigrate.DefaultOptions, []*gormigrate.Migration{\n\t\t{\n\t\t\tID: \"00001-CreateUsers\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating users table\")\n\t\t\t\treturn tx.AutoMigrate(&User{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"users\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00002-CreateVerificationCodes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating verification codes table\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"verification_codes\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00003-CreateAuthorizedApps\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating authorized apps table\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"authorized_apps\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00004-CreateTokens\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating tokens table\")\n\t\t\t\treturn tx.AutoMigrate(&Token{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"tokens\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00005-CreateCleanups\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating cleanup status table\")\n\t\t\t\tif err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// Seed database w/ cleanup record.\n\t\t\t\tif err := tx.Create(&CleanupStatus{Type: \"cleanup\", Generation: 1, NotBefore: time.Now()}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"cleanup_statuses\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00006-AddIndexes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: add users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).AddIndex(\"users_purge_index\", \"disabled\", \"updated_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"ver_code_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"token_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: drop users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).RemoveIndex(\"users_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"ver_code_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"token_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00007-AddSymptomOnset\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename test_date to symptom_date\")\n\t\t\t\t// AutoMigrate will add missing fields.\n\t\t\t\tif err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&VerificationCode{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := tx.AutoMigrate(&Token{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&Token{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename symptom_date to test_date\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00008-AddKeyTypes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: upgrading authorized_apps table.\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"admin_key\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00009-AddIssuerColumns\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding issuer columns to issued codes\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_user\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_app\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00010-AddSMSConfig\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding sms_configs table\")\n\t\t\t\treturn tx.AutoMigrate(&SMSConfig{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"sms_configs\").Error\n\t\t\t},\n\t\t},\n\t})\n\n\tlogger.Infof(\"database migrations complete\")\n\n\treturn m.Migrate()\n}", "func TestCreateDatabase(t *testing.T) {\n\n\tobj := testSQL{}\n\tslave := copain{}\n\n\tvar err error\n\n\tdb, err = saver.NewDbManager(\"root:mypass@tcp(127.0.0.1:3306)/greader\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\terr = db.CreateTable(&obj)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\terr = db.CreateTable(&slave)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func InitStore(username string, password string, migrationDir string) error{\r\n\t//Connect to database\r\n\tdbURL := fmt.Sprint(username, \":\", password, \"@tcp(localhost:3306)/indecision\")\r\n\tdb, err := sql.Open(\"mysql\", dbURL)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\terr = db.Ping()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t} else {\r\n\t\tfmt.Println(\"Successfully connected\")\r\n\t}\r\n\t\t//database migrations\r\n\tdriver, err := mysql.WithInstance(db, &mysql.Config{})\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tm, err := migrate.NewWithDatabaseInstance(\r\n\t\tfmt.Sprintf(\"file://%s\", migrationDir), // file://path/to/directory\r\n\t\t\"mysql\", driver)\r\n\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\r\n\t\treturn err\r\n\t}\r\n\r\n\tfmt.Println(\"Database migrated\")\r\n\tstore = &dbStore{db: db}\r\n\treturn nil\r\n}", "func TestSetupDB(t *testing.T) {\n\t// Manually drop the existing table.\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\ttestDB.ExecContext(ctx, \"drop table kv\")\n\n\tcfg := &Config{\n\t\tDB: testDB,\n\t\tDefaultTimeout: 10 * time.Second,\n\t}\n\terr := SetupDB(cfg)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error setting up db: %v\", err)\n\t}\n\n\t// Trying to set it up a second time should fail.\n\terr = SetupDB(cfg)\n\tif err == nil {\n\t\tt.Fatalf(\"unexpected success when setting up db for the second time\")\n\t}\n}", "func (s *Server) InititalizeEmptyDatabase() error {\n\tctx := context.Background()\n\tdefer ctx.Done()\n\ttx, err := s.Database.BeginTx(ctx, &sql.TxOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar count int\n\terr = tx.QueryRow(\"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users';\").Scan(&count)\n\tif err != nil || count == 1 {\n\t\ttx.Rollback()\n\t\treturn errors.New(\"Database already initialized\")\n\t}\n\t_, err = tx.Exec(`CREATE TABLE users (\n username VARCHAR(255) NOT NULL,\n\t\tpassword VARCHAR(1024) NOT NULL,\n\t\tPRIMARY KEY (username)\n\t);`)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(`CREATE TABLE sessions (\n username VARCHAR(255) NOT NULL,\n\t\tsession VARCHAR(255) NOT NULL,\n\t\tPRIMARY KEY (username,session)\n\t);`)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\t_, err = tx.Exec(`CREATE TABLE permissions (\n username VARCHAR(255) NOT NULL,\n\t\tscope VARCHAR(64) NOT NULL,\n\t\tpermission VARCHAR(64) NOT NULL,\n\t\tPRIMARY KEY (username,scope),\n\t\tCONSTRAINT FK_UserPermission FOREIGN KEY (username) REFERENCES username\n\t);`)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}", "func (d *database) Initialize() error {\n\terr := d.createTable(sqlCreateGeneralLedgerTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.createTable(sqlCreateJournalEntriesTable)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func initdb() {\n\tdir, _ := os.Getwd()\n\tdatabasepath := filepath.Join(dir, \"tasks.db\")\n\tdbrepository.InitDatabase(databasepath)\n}", "func InitDB(init bool) {\n\tif init {\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS kv (\n\t\t\tk TEXT PRIMARY KEY,\n\t\t\tv TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS datasets (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\t-- 'data' or 'computed'\n\t\t\ttype TEXT,\n\t\t\tdata_type TEXT,\n\t\t\tmetadata TEXT DEFAULT '',\n\t\t\t-- only set if computed\n\t\t\thash TEXT,\n\t\t\tdone INTEGER DEFAULT 1\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS annotate_datasets (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tdataset_id INTEGER REFERENCES datasets(id),\n\t\t\tinputs TEXT,\n\t\t\ttool TEXT,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS pytorch_archs (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS pytorch_components (\n\t\t\tid TEXT PRIMARY KEY,\n\t\t\tparams TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS exec_nodes (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\top TEXT,\n\t\t\tparams TEXT,\n\t\t\tparents TEXT,\n\t\t\tworkspace TEXT\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS exec_ds_refs (\n\t\t\tnode_id INTEGER,\n\t\t\tdataset_id INTEGER,\n\t\t\tUNIQUE(node_id, dataset_id)\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS workspaces (\n\t\t\tname TEXT PRIMARY KEY\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS ws_datasets (\n\t\t\tdataset_id INTEGER,\n\t\t\tworkspace TEXT,\n\t\t\tUNIQUE(dataset_id, workspace)\n\t\t)`)\n\t\tdb.Exec(`CREATE TABLE IF NOT EXISTS jobs (\n\t\t\tid INTEGER PRIMARY KEY ASC,\n\t\t\tname TEXT,\n\t\t\t-- e.g. 'execnode'\n\t\t\ttype TEXT,\n\t\t\t-- how to process the job output and render the job\n\t\t\top TEXT,\n\t\t\tmetadata TEXT,\n\t\t\tstart_time TIMESTAMP,\n\t\t\tstate TEXT DEFAULT '',\n\t\t\tdone INTEGER DEFAULT 0,\n\t\t\terror TEXT DEFAULT ''\n\t\t)`)\n\n\t\t// add missing pytorch components\n\t\tcomponentPath := \"python/skyhook/pytorch/components/\"\n\t\tfiles, err := ioutil.ReadDir(componentPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tif !strings.HasSuffix(fi.Name(), \".json\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tid := strings.Split(fi.Name(), \".json\")[0]\n\t\t\tbytes, err := ioutil.ReadFile(filepath.Join(componentPath, fi.Name()))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.Exec(\"INSERT OR REPLACE INTO pytorch_components (id, params) VALUES (?, ?)\", id, string(bytes))\n\t\t}\n\n\t\t// add missing pytorch archs\n\t\tarchPath := \"exec_ops/pytorch/archs/\"\n\t\tfiles, err = ioutil.ReadDir(archPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor _, fi := range files {\n\t\t\tif !strings.HasSuffix(fi.Name(), \".json\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tid := strings.Split(fi.Name(), \".json\")[0]\n\t\t\tbytes, err := ioutil.ReadFile(filepath.Join(archPath, fi.Name()))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdb.Exec(\"INSERT OR REPLACE INTO pytorch_archs (id, params) VALUES (?, ?)\", id, string(bytes))\n\t\t}\n\n\t\t// add default workspace if it doesn't exist\n\t\tvar count int\n\t\tdb.QueryRow(\"SELECT COUNT(*) FROM workspaces WHERE name = ?\", \"default\").Scan(&count)\n\t\tif count == 0 {\n\t\t\tdb.Exec(\"INSERT INTO workspaces (name) VALUES (?)\", \"default\")\n\t\t}\n\t}\n\n\t// now run some database cleanup steps\n\n\t// mark jobs that are still running as error\n\tdb.Exec(\"UPDATE jobs SET error = 'terminated', done = 1 WHERE done = 0\")\n\n\t// delete temporary datasetsTODO\n}", "func (sql *SqlConnection) InitDB() error {\n\n\tvar err error\n\n\t// open a db connection //\n\tsql.Db, err = gorm.Open(\"sqlite3\", \"/var/tmp/tennis.db\")\n\tif err != nil {\n\t\tfmt.Println(\"Failed to connect database : \", err.Error())\n\t}\n\tsql.Db.LogMode(true)\n\n\treturn err\n}", "func (uts *UnapprovedTransactions) InitDB() error {\n\treturn uts.DB.CreateTable(uts.getTableName(), \"VARBINARY(100)\", \"LONGBLOB\")\n}", "func setupBoltDB() (*BoltDB, error) {\n\tos.Remove(testDB)\n\tvar err error\n\tdb, err := openBoltDB(testDB)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = createBuckets(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = upgradeDB(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, err\n}", "func InitDb() *gorm.DB {\n\t// Openning file\n\tdb, err := gorm.Open(\"sqlite3\", \"./data.db\")\n\t// Display SQL queries\n\tdb.LogMode(true)\n\n\t// Error\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// Creating the table\n\tif !db.HasTable(&Users{}) {\n\t\tdb.CreateTable(&Users{})\n\t\tdb.Set(\"gorm:table_options\", \"ENGINE=InnoDB\").CreateTable(&Users{})\n\t}\n\n\treturn db\n}", "func newTestDB(t *testing.T) (*gorm.DB, func(...string) error) {\n\treturn dbutil.NewTestDB(t, AllTables...)\n}", "func setUp() error {\n\t// Check if the users table has been created\n\t_, checkErr := database.Exec(\"SELECT \" + usersColumnName + \" FROM \" + tableUsers + \" WHERE \" + usersColumnID + \"=1;\")\n\tif checkErr != nil {\n\t\tfmt.Println(\"Creating \\\"\" + tableUsers + \"\\\" table...\")\n\t\t// Make the users table\n\t\tif cErr := createUserTableSQL(); cErr != nil {\n\t\t\treturn cErr\n\t\t}\n\t}\n\t// Check for new custom AccountInfoColumn items\n\tif newItemsErr := addNewCustomItemsSQL(); newItemsErr != nil {\n\t\treturn newItemsErr\n\t}\n\n\tif rememberMe {\n\t\t// Check if autologs table has been made\n\t\t_, checkErr := database.Exec(\"SELECT \" + autologsColumnID + \" FROM \" + tableAutologs + \" WHERE \" + autologsColumnID + \"=1;\")\n\t\tif checkErr != nil {\n\t\t\tfmt.Println(\"Making autologs table...\")\n\t\t\tif cErr := createAutologsTableSQL(); cErr != nil {\n\t\t\t\treturn cErr\n\t\t\t}\n\t\t}\n\t}\n\t// Make sure customLoginColumn is unique if it is set\n\tif len(customLoginColumn) > 0 {\n\t\t_, alterErr := database.Exec(\"ALTER TABLE \" + tableUsers + \" ADD UNIQUE (\" + customLoginColumn + \");\")\n\t\tif alterErr != nil {\n\t\t\treturn alterErr\n\t\t}\n\t}\n\n\t//\n\treturn nil\n}", "func Init(cfg Configuration) error {\n\tsqlDriver := \"postgres\"\n\tif os.Getenv(\"LIMES_DEBUG_SQL\") == \"1\" {\n\t\tutil.LogInfo(\"Enabling SQL tracing... \\x1B[1;31mTHIS VOIDS YOUR WARRANTY!\\x1B[0m If database queries fail in unexpected ways, check first if the tracing causes the issue.\")\n\t\tsqlDriver += \"-debug\"\n\t}\n\n\tdb, err := sql.Open(sqlDriver, cfg.Location)\n\tif err != nil {\n\t\treturn err\n\t}\n\tDB = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}\n\tInitGorp()\n\n\t//wait for database to reach our expected migration level (this is useful\n\t//because, depending on the rollout strategy, `limes-migrate` might still be\n\t//running when we are starting, so wait for it to complete)\n\tmigrationLevel, err := getCurrentMigrationLevel(cfg)\n\tutil.LogDebug(\"waiting for database to migrate to schema version %d\", migrationLevel)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := DB.Prepare(fmt.Sprintf(\"SELECT 1 FROM schema_migrations WHERE version = %d\", migrationLevel))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\twaitInterval := 1\n\tfor {\n\t\trows, err := stmt.Query()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif rows.Next() {\n\t\t\t//got a row - success\n\t\t\tbreak\n\t\t}\n\t\t//did not get a row - expected migration not there -> sleep with exponential backoff\n\t\twaitInterval *= 2\n\t\tutil.LogInfo(\"database is not migrated to schema version %d yet - will retry in %d seconds\", migrationLevel, waitInterval)\n\t\ttime.Sleep(time.Duration(waitInterval) * time.Second)\n\t}\n\n\tutil.LogDebug(\"database is migrated - commencing normal startup...\")\n\treturn nil\n}", "func Setup(testname string, t *testing.T) *sql.DB {\n\n\tdb, err := sql.Open(\"ramsql\", testname)\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot open conn to ramsql: %s\\n\", err)\n\t}\n\n\terr = database.InitSchemas(db)\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot setup database schemas: %s\", err)\n\t}\n\n\treturn db\n}" ]
[ "0.73692185", "0.724161", "0.721584", "0.7181012", "0.71460074", "0.7139826", "0.71323043", "0.7104169", "0.7086372", "0.7060455", "0.7036444", "0.70175046", "0.70077455", "0.6931672", "0.6924954", "0.68977255", "0.68855184", "0.6883087", "0.68763554", "0.68635714", "0.6788959", "0.6765336", "0.670607", "0.66839975", "0.6669654", "0.6665373", "0.6615059", "0.6613988", "0.6607835", "0.66064227", "0.6606415", "0.6593359", "0.6592875", "0.65759987", "0.6574263", "0.6570184", "0.6532686", "0.6525395", "0.65240836", "0.652056", "0.65177405", "0.650325", "0.65029645", "0.6456309", "0.6432712", "0.64291334", "0.64200014", "0.64141786", "0.640205", "0.6401828", "0.6399149", "0.6381618", "0.6372695", "0.6366362", "0.6365533", "0.6364594", "0.63640994", "0.63608587", "0.6352197", "0.63436186", "0.6335724", "0.63306874", "0.632976", "0.6329718", "0.6329018", "0.63276106", "0.6321029", "0.6319301", "0.6316563", "0.6304916", "0.6291841", "0.6283033", "0.6275509", "0.62733996", "0.62674", "0.6257909", "0.62411326", "0.62328255", "0.6229846", "0.6229263", "0.6227642", "0.62273306", "0.6226507", "0.6226329", "0.6224663", "0.62223536", "0.6212585", "0.6209567", "0.6207097", "0.62026393", "0.61979866", "0.61957204", "0.6191279", "0.61873645", "0.61834365", "0.6182575", "0.6180509", "0.61803246", "0.6169998", "0.6166992" ]
0.71609265
4
Hijack implements the http.Hijacker interface.
func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { if w.size < 0 { w.size = 0 } return w.ResponseWriter.(http.Hijacker).Hijack() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *ResponseWriter) Hijack() {\n\tr.ResponseWriter.Hijack()\n\treturn\n}", "func (response *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn response.Writer.(http.Hijacker).Hijack()\n}", "func (l *logWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn l.ResponseWriter.(http.Hijacker).Hijack()\n}", "func (r *response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn r.ResponseWriter.(http.Hijacker).Hijack()\n}", "func (w *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tw.hijacked = true\n\tconn := newNodeConn(w.Value, w.reqReader)\n\tbrw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))\n\treturn conn, brw, nil\n\n}", "func (w *interceptRW) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif w, ok := w.ResponseWriter.(http.Hijacker); ok {\n\t\treturn w.Hijack()\n\t}\n\treturn nil, nil, http.ErrNotSupported\n}", "func (resp *response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif resp.size < 0 {\n\t\tresp.size = 0\n\t}\n\treturn resp.ResponseWriter.(http.Hijacker).Hijack()\n}", "func (mrw *MonitoringResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif hj, ok := mrw.ResponseWriter.(http.Hijacker); ok {\n\t\treturn hj.Hijack()\n\t}\n\treturn nil, nil, fmt.Errorf(\"http.Hijacker interface is not supported\")\n}", "func (r *Response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {\n\treturn r.ResponseWriter.(http.Hijacker).Hijack()\n}", "func (w *WithCodeResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn w.Writer.(http.Hijacker).Hijack()\n}", "func (w *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn w.writer.(http.Hijacker).Hijack()\n}", "func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif hj, ok := w.ResponseWriter.(http.Hijacker); ok {\n\t\treturn hj.Hijack()\n\t}\n\treturn nil, nil, fmt.Errorf(\"http.Hijacker interface is not supported\")\n}", "func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\thj, ok := r.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"webserver doesn't support hijacking\")\n\t}\n\treturn hj.Hijack()\n}", "func (w *FlushingWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif hijacker, ok := w.WriterFlusher.(http.Hijacker); ok {\n\t\tw.hijacked = true\n\t\treturn hijacker.Hijack()\n\t}\n\treturn nil, nil, errors.New(\"cannot hijack connection\")\n}", "func (g *GzipResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\treturn g.r.Hijack()\n}", "func serveHijack(w http.ResponseWriter, targetConn net.Conn) error {\n\thijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\treturn caddyhttp.Error(http.StatusInternalServerError,\n\t\t\tfmt.Errorf(\"ResponseWriter does not implement http.Hijacker\"))\n\t}\n\tclientConn, bufReader, err := hijacker.Hijack()\n\tif err != nil {\n\t\treturn caddyhttp.Error(http.StatusInternalServerError,\n\t\t\tfmt.Errorf(\"hijack failed: %v\", err))\n\t}\n\tdefer clientConn.Close()\n\t// bufReader may contain unprocessed buffered data from the client.\n\tif bufReader != nil {\n\t\t// snippet borrowed from `proxy` plugin\n\t\tif n := bufReader.Reader.Buffered(); n > 0 {\n\t\t\trbuf, err := bufReader.Reader.Peek(n)\n\t\t\tif err != nil {\n\t\t\t\treturn caddyhttp.Error(http.StatusBadGateway, err)\n\t\t\t}\n\t\t\ttargetConn.Write(rbuf)\n\t\t}\n\t}\n\t// Since we hijacked the connection, we lost the ability to write and flush headers via w.\n\t// Let's handcraft the response and send it manually.\n\tres := &http.Response{StatusCode: http.StatusOK,\n\t\tProto: \"HTTP/1.1\",\n\t\tProtoMajor: 1,\n\t\tProtoMinor: 1,\n\t\tHeader: make(http.Header),\n\t}\n\tres.Header.Set(\"Server\", \"Caddy\")\n\n\terr = res.Write(clientConn)\n\tif err != nil {\n\t\treturn caddyhttp.Error(http.StatusInternalServerError,\n\t\t\tfmt.Errorf(\"failed to send response to client: %v\", err))\n\t}\n\n\treturn dualStream(targetConn, clientConn, clientConn, false)\n}", "func (r *recorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\trw := bufio.NewReadWriter(bufio.NewReader(r.conn), bufio.NewWriter(r.conn))\n\treturn r.conn, rw, nil\n}", "func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {\n\tif w.handlerDone.isSet() {\n\t\tpanic(\"net/http: Hijack called after ServeHTTP finished\")\n\t}\n\tif w.wroteHeader {\n\t\tw.cw.flush()\n\t}\n\n\tc := w.conn\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t// Release the bufioWriter that writes to the chunk writer, it is not\n\t// used after a connection has been hijacked.\n\trwc, buf, err = c.hijackLocked()\n\tif err == nil {\n\t\tputBufioWriter(w.w)\n\t\tw.w = nil\n\t}\n\treturn rwc, buf, err\n}", "func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\th, ok := w.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"the response writer doesn't support the http.Hijacker interface\")\n\t}\n\treturn h.Hijack()\n}", "func (c *CompressingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\thijacker, ok := c.writer.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"ResponseWriter doesn't support Hijacker interface\")\n\t}\n\treturn hijacker.Hijack()\n}", "func (u *HyperConn) SockRequestHijack(method, endpoint string, data io.Reader, ct string) (net.Conn, *bufio.Reader, error) {\n\treq, client, err := u.newRequestHyperConn(method, endpoint, data, ct)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclient.Do(req)\n\tconn, br := client.Hijack()\n\treturn conn, br, nil\n}", "func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tr.rendered = true\n\thijacker, ok := r.ResponseWriter.(http.Hijacker)\n\tif !ok {\n\t\treturn nil, nil, errors.New(\"the ResponseWriter doesn't support the Hijacker interface\")\n\t}\n\treturn hijacker.Hijack()\n}", "func (pe *providerEndpoint) setHijack(cb HijackFunc) {\n\tpe.hijack = cb\n}", "func (d4w *d4Writer) hijackHeader() bool {\n\td4w.fb[1] = 2\n\treturn true\n}", "func (pe *providerEndpoint) getHijack() HijackFunc {\n\treturn pe.hijack\n}", "func execmServerConnHijack(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*httputil.ServerConn).Hijack()\n\tp.Ret(1, ret, ret1)\n}", "func execmClientConnHijack(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret, ret1 := args[0].(*httputil.ClientConn).Hijack()\n\tp.Ret(1, ret, ret1)\n}", "func (b *Browser) HijackRequests() *HijackRouter {\n\treturn newHijackRouter(b, b).initEvents()\n}", "func (u Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif hijacker, ok := w.(http.Hijacker); ok {\n\t\tif !u.DisableDirect && r.Method == \"PRI\" && r.URL.Path == \"*\" && r.Proto == \"HTTP/2.0\" {\n\t\t\tbody := \"SM\\r\\n\\r\\n\"\n\t\t\tcon, rw, err := hijacker.Hijack()\n\t\t\tdefer con.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Hijack failed %v\", err)\n\t\t\t} else if n, err := io.MultiReader(r.Body, rw).Read([]byte(body)); n != len(body) {\n\t\t\t\tlog.Printf(\"%d %v\", n, err)\n\t\t\t} else {\n\t\t\t\twrap := io.MultiReader(bytes.NewBuffer([]byte(http2.ClientPreface)), rw)\n\t\t\t\tnc := &conn{\n\t\t\t\t\tConn: con,\n\t\t\t\t\tWriter: rw.Writer,\n\t\t\t\t\tReader: wrap,\n\t\t\t\t}\n\t\t\t\th2c := &http2.Server{}\n\t\t\t\th2c.ServeConn(nc, &http2.ServeConnOpts{Handler: u.Handler})\n\t\t\t\treturn\n\t\t\t}\n\t\t\thttp.Error(w, \"Server could not handle the request.\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tif initReq := InitH2c(r); initReq != nil {\n\t\t\tfsz := uint32(1 << 14) // RFC default\n\t\t\tfor _, s := range initReq.Settings {\n\t\t\t\tif s.ID == http2.SettingMaxFrameSize && s.Val != 0 {\n\t\t\t\t\tfsz = s.Val\n\t\t\t\t}\n\t\t\t}\n\t\t\tonError := func(e error) {\n\t\t\t\tlog.Print(e)\n\t\t\t\thttp.Error(w, \"Error in upgrading initial request\", http.StatusInternalServerError)\n\t\t\t}\n\n\t\t\th2req := bytes.NewBuffer([]byte(http2.ClientPreface))\n\t\t\tfr := http2.NewFramer(h2req, nil)\n\n\t\t\tif err := fr.WriteSettings(initReq.Settings...); err != nil {\n\t\t\t\tonError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\thdr := initReq.HeaderBlock\n\t\t\tif uint32(len(hdr)) <= fsz {\n\t\t\t\tif err := fr.WriteHeaders(http2.HeadersFrameParam{\n\t\t\t\t\tStreamID: 1,\n\t\t\t\t\tBlockFragment: hdr,\n\t\t\t\t\tEndHeaders: true,\n\t\t\t\t}); err != nil {\n\t\t\t\t\tonError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif err := fr.WriteHeaders(http2.HeadersFrameParam{\n\t\t\t\t\tStreamID: 1,\n\t\t\t\t\tBlockFragment: hdr[:fsz],\n\t\t\t\t}); err != nil {\n\t\t\t\t\tonError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thdr = hdr[fsz:]\n\t\t\t\tfor len(hdr) > 0 {\n\t\t\t\t\tif uint32(len(hdr)) > fsz {\n\t\t\t\t\t\tif err := fr.WriteContinuation(1, false, hdr[:fsz]); err != nil {\n\t\t\t\t\t\t\tonError(err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\thdr = hdr[fsz:]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif err := fr.WriteContinuation(1, true, hdr); err != nil {\n\t\t\t\t\t\t\tonError(err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\thdr = nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcon, rw, err := hijacker.Hijack()\n\t\t\t// Note: It seems rw is a wrapper for con.\n\t\t\t// r.Body.Read still looks working unless rw.Read call.\n\t\t\tdefer con.Close()\n\t\t\tif err != nil {\n\t\t\t\tonError(err)\n\t\t\t\trw.Flush()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trw.Write([]byte(\n\t\t\t\t\"HTTP/1.1 101 Switching Protocols\\r\\n\" +\n\t\t\t\t\t\"Connection: upgrade\\r\\n\" +\n\t\t\t\t\t\"Upgrade: h2c\\r\\n\" +\n\t\t\t\t\t\"\\r\\n\"))\n\n\t\t\th2req2 := &h2cInitReqBody{\n\t\t\t\tFramer: fr,\n\t\t\t\tBuffer: h2req,\n\t\t\t\tBody: r.Body,\n\t\t\t\tFrameSize: fsz,\n\t\t\t}\n\t\t\tnc := &conn{\n\t\t\t\tConn: con,\n\t\t\t\tWriter: rw.Writer,\n\t\t\t\tReader: io.MultiReader(h2req2, vacuumPreface{rw}, rw),\n\t\t\t\tvacuumAck: true, // because we sent HTTP2-Settings payload\n\t\t\t}\n\t\t\th2c := &http2.Server{}\n\t\t\tfor _, s := range initReq.Settings {\n\t\t\t\tswitch s.ID {\n\t\t\t\tcase http2.SettingMaxConcurrentStreams:\n\t\t\t\t\th2c.MaxConcurrentStreams = s.Val\n\t\t\t\tcase http2.SettingMaxFrameSize:\n\t\t\t\t\th2c.MaxReadFrameSize = s.Val\n\t\t\t\tdefault:\n\t\t\t\t\t// just ignore\n\t\t\t\t}\n\t\t\t}\n\t\t\th2c.ServeConn(nc, &http2.ServeConnOpts{Handler: u.Handler})\n\t\t\treturn\n\t\t}\n\t}\n\tif u.Handler != nil {\n\t\tu.Handler.ServeHTTP(w, r)\n\t} else {\n\t\thttp.DefaultServeMux.ServeHTTP(w, r)\n\t}\n\treturn\n}", "func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {\n\tif c.hijackedv {\n\t\treturn nil, nil, ErrHijacked\n\t}\n\tc.r.abortPendingRead()\n\n\tc.hijackedv = true\n\trwc = c.rwc\n\trwc.SetDeadline(time.Time{})\n\n\tbuf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))\n\tif c.r.hasByte {\n\t\tif _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"unexpected Peek failure reading buffered byte: %v\", err)\n\t\t}\n\t}\n\tc.setState(rwc, StateHijacked, runHooks)\n\treturn\n}", "func (p *Page) HijackRequests() *HijackRouter {\n\treturn newHijackRouter(p.browser, p).initEvents()\n}", "func (irc *Bot) hijackSession() bool {\n\treturn false\n}", "func WrapHeaderHack(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tvar wrote bool\n\t\tww := httpsnoop.Wrap(w, httpsnoop.Hooks{\n\t\t\tWrite: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc {\n\t\t\t\twrote = true\n\t\t\t\treturn next\n\t\t\t},\n\t\t\tWriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {\n\t\t\t\twrote = true\n\t\t\t\treturn next\n\t\t\t},\n\t\t\tReadFrom: func(next httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc {\n\t\t\t\twrote = true\n\t\t\t\treturn func(src io.Reader) (int64, error) {\n\t\t\t\t\tn, err := next(src)\n\t\t\t\t\tif n > 0 {\n\t\t\t\t\t\twrote = true\n\t\t\t\t\t}\n\t\t\t\t\treturn n, err\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\n\t\th.ServeHTTP(ww, req)\n\n\t\tif !wrote {\n\t\t\tw.WriteHeader(204)\n\t\t}\n\t})\n}", "func Middleware(options ...HijackOptions) func(http.Handler) http.Handler {\n\topt := DefaultHijackOptions\n\tif len(options) > 0 {\n\t\topt = options[0]\n\t}\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx, log := chi.RouteContext(r.Context()), middleware.GetLogEntry(r)\n\t\t\tif ctx == nil || r.Method != \"OPTIONS\" {\n\t\t\t\t// Just proxy to the next handler\n\t\t\t\th.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Hijack request\n\t\t\tvar routes Routes\n\t\t\tu := getStringSliceFromURI(r.RequestURI)\n\t\t\tchi.Walk(ctx.Routes, walkFn(u, &routes))\n\t\t\traw, err := opt.Render(routes)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tlog.Panic(fmt.Sprintf(\"rendering OPTIONS description failed: %s\", err), nil)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.WriteHeader(200)\n\t\t\tw.Header().Add(\"Content-Type\", opt.ContentType)\n\t\t\tw.Write(raw)\n\t\t})\n\t}\n}", "func (Secure)Intercept(ctx context.Context, chain *fw.MiddlewareChain) context.Context {\n\ttoken, ok := wegocontext.Value(ctx, \"Securetoken\").(string)\n\tif !ok || (ok && token != \"passpass\") {\n\t\tctx = wegocontext.SetError(ctx, e.HTTPError(ctx, http.StatusForbidden, e.SecurityException,\n\t\t\tmap[string]interface{}{}))\n\t\treturn ctx\n\t}\n\tctx = chain.DoContinue(ctx)\n\treturn ctx\n}", "func (this Interceptor) Intercept(url string, exec rack.Middleware) error {\n\tif this[url] != nil {\n\t\treturn PreExistingInterceptorError{url}\n\t}\n\tthis[url] = exec\n\treturn nil\n}", "func (a *SessionAuthenticator) Challenge(*http.Request, http.ResponseWriter) {\n}", "func WithRequestHijack(h func(*http.Request)) Option {\n\treturn func(o *option) {\n\t\to.reqChain = append(o.reqChain, h)\n\t}\n}", "func streamAuthIntercept(\n\tserver interface{},\n\tstream grpc.ServerStream,\n\tinfo *grpc.StreamServerInfo,\n\thandler grpc.StreamHandler,\n) error {\n\t//bypass auth if method is /hahiye.AuthService/Login\n\tif info.FullMethod == \"/hahiye.AuthService/Login\" {\n\t\tfmt.Println(\"bypassing auth cz it's login action\")\n\t\treturn handler(server, stream)\n\t}\n\tif err := auth(stream.Context()); err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"authorization OK\")\n\treturn handler(server, stream)\n}", "func replayInjectionPoint(req types.Request, tracerPayload, exploit string) error {\n\tu, err := url.Parse(req.RequestURL)\n\tif err != nil {\n\t\tlog.Warning.Print(err)\n\t\treturn err\n\t}\n\n\trr := strings.Replace(req.RawRequest, tracerPayload, url.QueryEscape(exploit), -1)\n\t// dial require a port. If they used regular 80 and 443, they\n\t// won't be included in the URL\n\thosts := strings.Split(u.Host, \":\")\n\thost := u.Host\n\tvar conn net.Conn\n\tif u.Scheme != \"https\" {\n\t\tif len(hosts) == 1 {\n\t\t\thost += \":80\"\n\t\t}\n\t\tconn, err := net.Dial(\"tcp\", host)\n\t\tif conn != nil {\n\t\t\tdefer conn.Close()\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Warning.Print(err)\n\t\t\treturn err\n\t\t}\n\n\t} else {\n\n\t\tif len(hosts) == 1 {\n\t\t\thost += \":443\"\n\t\t}\n\t\ttserver, err := tls.Dial(\"tcp\", host, &tls.Config{InsecureSkipVerify: true})\n\t\t// Have to check for nil differently with tls.Dial because it\n\t\t// returns a pointer of a connection instead of a struct.\n\t\tvar nilTest *tls.Conn\n\t\tif tserver != nilTest {\n\t\t\tconn = tserver\n\t\t\tdefer conn.Close()\n\t\t}\n\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Warning.Print(err)\n\t\t\treturn err\n\t\t}\n\t}\n\tfmt.Fprint(conn, rr)\n\treturn nil\n}", "func Inject(inner http.Handler) http.Handler {\n\treturn http.HandlerFunc(handler(inner))\n}", "func mockConnUpgradeHandler(t *testing.T, upgradeType string, write []byte) http.Handler {\n\tt.Helper()\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trequire.Equal(t, constants.WebAPIConnUpgrade, r.URL.Path)\n\t\trequire.Equal(t, upgradeType, r.Header.Get(constants.WebAPIConnUpgradeHeader))\n\t\trequire.Equal(t, upgradeType, r.Header.Get(constants.WebAPIConnUpgradeTeleportHeader))\n\t\trequire.Equal(t, constants.WebAPIConnUpgradeConnectionType, r.Header.Get(constants.WebAPIConnUpgradeConnectionHeader))\n\n\t\thj, ok := w.(http.Hijacker)\n\t\trequire.True(t, ok)\n\n\t\tconn, _, err := hj.Hijack()\n\t\trequire.NoError(t, err)\n\t\tdefer conn.Close()\n\n\t\t// Upgrade response.\n\t\tresponse := &http.Response{\n\t\t\tStatusCode: http.StatusSwitchingProtocols,\n\t\t\tProtoMajor: 1,\n\t\t\tProtoMinor: 1,\n\t\t}\n\t\trequire.NoError(t, response.Write(conn))\n\n\t\t// Upgraded.\n\t\tswitch upgradeType {\n\t\tcase constants.WebAPIConnUpgradeTypeALPNPing:\n\t\t\t// Wrap conn with Ping and write some pings.\n\t\t\tpingConn := pingconn.New(conn)\n\t\t\tpingConn.WritePing()\n\t\t\t_, err = pingConn.Write(write)\n\t\t\trequire.NoError(t, err)\n\t\t\tpingConn.WritePing()\n\n\t\tdefault:\n\t\t\t_, err = conn.Write(write)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t})\n}", "func (irc *IrcCon) HijackSession() bool {\n\tunaddr,err := net.ResolveUnixAddr(\"unix\", irc.unixastr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcon,err := net.DialUnix(\"unix\", nil, unaddr)\n\tif err != nil {\n\t\tfmt.Println(\"Couldnt restablish connection, no prior bot.\")\n\t\tfmt.Println(err)\n\t\treturn false\n\t}\n\n\tncon,err := sendfd.RecvFD(con)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnetcon,err := net.FileConn(ncon)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tirc.reconnect = true\n\tirc.con = netcon\n\treturn true\n}", "func HangMe(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tch := make(chan int)\n\tch <- 5\n\treturn\n}", "func (lw LoggingWrapper) Wrap(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\th.ServeHTTP(w, r)\n\t\tlog.Info(fmt.Sprintf(\"request for %v with method %v\", r.RequestURI, r.Method))\n\t})\n}", "func (aw AWrapper) Wrap(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\th.ServeHTTP(w, r)\n\t\tw.Write([]byte(\"A wrapper wrote this\\n\"))\n\t})\n}", "func (b *bcsApiRequester) PostHijacked(ctx context.Context, uri string, header ...*http.HeaderSet) (types.HijackedResponse, error) {\n\treq, err := htplib.NewRequest(htplib.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn types.HijackedResponse{}, err\n\t}\n\tif header != nil {\n\t\tfor _, h := range header {\n\t\t\treq.Header.Set(h.Key, h.Value)\n\t\t}\n\t}\n\tif b.bcsToken != \"\" {\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+b.bcsToken)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tconn, err := b.setupHijackConn(ctx, uri, req, \"websocket\")\n\tif err != nil {\n\t\treturn types.HijackedResponse{}, err\n\t}\n\n\treturn types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err\n}", "func (p *Proxy) onRequest(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {\n\tresChan := make(chan *http.Response)\n\terrChan := make(chan error, 1)\n\n\t// Rotate proxy IP for every AFTER request\n\tif (rotate == \"\") || (ok >= p.Options.Rotate) {\n\t\tif p.Options.Method == \"sequent\" {\n\t\t\trotate = p.Options.ProxyManager.NextProxy()\n\t\t}\n\n\t\tif p.Options.Method == \"random\" {\n\t\t\trotate = p.Options.ProxyManager.RandomProxy()\n\t\t}\n\n\t\tif ok >= p.Options.Rotate {\n\t\t\tok = 1\n\t\t}\n\t} else {\n\t\tok++\n\t}\n\n\tgo func() {\n\t\tif (req.URL.Scheme != \"http\") && (req.URL.Scheme != \"https\") {\n\t\t\terrChan <- fmt.Errorf(\"Unsupported protocol scheme: %s\", req.URL.Scheme)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debugf(\"%s %s %s\", req.RemoteAddr, req.Method, req.URL)\n\n\t\ttr, err := mubeng.Transport(rotate)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tproxy := &mubeng.Proxy{\n\t\t\tAddress: rotate,\n\t\t\tTransport: tr,\n\t\t}\n\n\t\tclient, req = proxy.New(req)\n\t\tclient.Timeout = p.Options.Timeout\n\t\tif p.Options.Verbose {\n\t\t\tclient.Transport = dump.RoundTripper(tr)\n\t\t}\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t// Copying response body\n\t\tbuf, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(buf))\n\t\tresChan <- resp\n\t}()\n\n\tselect {\n\tcase err := <-errChan:\n\t\tlog.Errorf(\"%s %s\", req.RemoteAddr, err)\n\t\treturn req, goproxy.NewResponse(req, mime, http.StatusBadGateway, \"Proxy server error\")\n\tcase resp := <-resChan:\n\t\tlog.Debug(req.RemoteAddr, \" \", resp.Status)\n\t\treturn req, resp\n\t}\n}", "func (listener *Listener) HijackPong(address string) error {\n\tif _, err := net.ResolveUDPAddr(\"udp\", address); err != nil {\n\t\treturn fmt.Errorf(\"error resolving UDP address: %v\", err)\n\t}\n\tgo func() {\n\t\tticker := time.NewTicker(time.Second)\n\t\tdefer ticker.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tdata, err := Ping(address)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// It's okay if these packets are lost sometimes. There's no need to log this.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t//noinspection SpellCheckingInspection\n\t\t\t\tif string(data[:4]) == \"MCPE\" {\n\t\t\t\t\tfragments := bytes.Split(data, []byte{';'})\n\t\t\t\t\tfor len(fragments) < 9 {\n\t\t\t\t\t\t// Append to the fragments if it's not at least 9 elements long.\n\t\t\t\t\t\tfragments = append(fragments, nil)\n\t\t\t\t\t}\n\n\t\t\t\t\tfragments = fragments[:9]\n\t\t\t\t\tfragments[6] = []byte(strconv.Itoa(int(listener.id)))\n\t\t\t\t\tfragments[7] = []byte(\"Proxy\")\n\t\t\t\t\tfragments[8] = []byte{}\n\n\t\t\t\t\tlistener.PongData(bytes.Join(fragments, []byte{';'}))\n\t\t\t\t} else {\n\t\t\t\t\tlistener.PongData(data)\n\t\t\t\t}\n\t\t\tcase <-listener.closeCtx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}", "func (o *Obfuscated2) Handshake(protocol [4]byte, dc int, s mtproxy.Secret) error {\n\tk, err := generateKeys(o.rand, protocol, s.Secret, dc)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"generate keys\")\n\t}\n\to.keys = k\n\n\tif _, err := o.conn.Write(o.header); err != nil {\n\t\treturn errors.Wrap(err, \"write obfuscated header\")\n\t}\n\n\treturn nil\n}", "func HandShake(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"text/javascript\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tif r.Method != \"POST\" {\n\t\tfmt.Fprintln(w, \"bad request\")\n\t\treturn\n\t}\n\n\tr.ParseForm()\n\tID := r.Form[\"id\"][0]\n\tVC := r.Form[\"vc\"][0]\n\n\tuserCache, err := services.CacheRetrieve(redisClient, ID)\n\n\tif err != nil || userCache == nil {\n\t\tlog.Println(\"user handashaking failed:\")\n\t\tlog.Println(err)\n\t\tlog.Println(\"<=END\")\n\t\tfmt.Fprintln(w, \"0\")\n\t\treturn\n\t}\n\n\tif userCache[0].Vc == VC {\n\t\tfmt.Fprintln(w, \"1\")\n\t\treturn\n\t} else {\n\t\tfmt.Fprintln(w, \"-1\")\n\t\treturn\n\t}\n\n}", "func (r *Responder) UseProxy() { r.write(http.StatusUseProxy) }", "func (r *Responder) Locked() { r.write(http.StatusLocked) }", "func Proxy(ctx context.Context, wrapped http.Handler, host, shimPath string, rewriteHost, enableWebsocketInjection bool, openWebsocketWrapper func(wrapped http.Handler, metricHandler *metrics.MetricHandler) http.Handler, metricHandler *metrics.MetricHandler) (http.Handler, error) {\n\tmux := http.NewServeMux()\n\tif shimPath != \"\" {\n\t\tshimPath = path.Clean(\"/\"+shimPath) + \"/\"\n\t\tshimServer := createShimChannel(ctx, host, shimPath, rewriteHost, openWebsocketWrapper, enableWebsocketInjection, metricHandler)\n\t\tmux.Handle(shimPath, shimServer)\n\t}\n\tmux.Handle(\"/\", wrapped)\n\treturn mux, nil\n}", "func (bw BWrapper) Wrap(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\th.ServeHTTP(w, r)\n\t\tw.Write([]byte(\"B wrapper wrote this\\n\"))\n\t})\n\n}", "func wrapWriter(w http.ResponseWriter) writerProxy {\n\tvar _, cn = w.(http.CloseNotifier) // nolint\n\tvar _, fl = w.(http.Flusher)\n\tvar _, hj = w.(http.Hijacker)\n\tvar _, rf = w.(io.ReaderFrom)\n\n\tvar bw = basicWriter{ResponseWriter: w}\n\tif cn && fl && hj && rf {\n\t\treturn &fancyWriter{&bw}\n\t}\n\tif fl {\n\t\treturn &flushWriter{&bw}\n\t}\n\treturn &bw\n}", "func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {\n\t// Attempts to validate the user and their cookie.\n\tlogger := log.NewLogEntry()\n\tstart := time.Now()\n\ttags := []string{\"action:proxy\"}\n\tvar err error\n\n\t// If the request is explicitly whitelisted, we skip authentication\n\tif p.IsWhitelistedRequest(req) {\n\t\ttags = append(tags, \"auth_type:whitelisted\")\n\t} else {\n\t\ttags = append(tags, \"auth_type:authenticated\")\n\t\terr = p.Authenticate(rw, req)\n\t}\n\n\t// If the authentication is not successful we proceed to start the OAuth Flow with\n\t// OAuthStart. If authentication is successful, we proceed to proxy to the configured\n\t// upstream.\n\tif err != nil {\n\t\tswitch err {\n\t\tcase http.ErrNoCookie:\n\t\t\t// No cookie is set, start the oauth flow\n\t\t\tp.OAuthStart(rw, req, tags)\n\t\t\treturn\n\t\tcase ErrLifetimeExpired:\n\t\t\t// User's lifetime expired, we trigger the start of the oauth flow\n\t\t\tp.OAuthStart(rw, req, tags)\n\t\t\treturn\n\t\tcase ErrWrongIdentityProvider:\n\t\t\t// User is authenticated with the incorrect provider. This most common non-malicious\n\t\t\t// case occurs when an upstream has been transitioned to a different provider but\n\t\t\t// the user has a stale sesssion.\n\t\t\tp.OAuthStart(rw, req, tags)\n\t\t\treturn\n\t\tcase ErrUnauthorizedUpstreamRequested:\n\t\t\t// The users session has been authorised for use with a different upstream than the one\n\t\t\t// that is being requested, so we trigger the start of the oauth flow.\n\t\t\t// This exists primarily to implement some form of grace period while this additional session\n\t\t\t// check is being introduced.\n\t\t\tp.OAuthStart(rw, req, tags)\n\t\t\treturn\n\t\tcase sessions.ErrInvalidSession:\n\t\t\t// The user session is invalid and we can't decode it.\n\t\t\t// This can happen for a variety of reasons but the most common non-malicious\n\t\t\t// case occurs when the session encoding schema changes. We manage this ux\n\t\t\t// by triggering the start of the oauth flow.\n\t\t\tp.OAuthStart(rw, req, tags)\n\t\t\treturn\n\t\tcase ErrUserNotAuthorized:\n\t\t\ttags = append(tags, \"error:user_unauthorized\")\n\t\t\tp.StatsdClient.Incr(\"application_error\", tags, 1.0)\n\t\t\t// We know the user is not authorized for the request, we show them a forbidden page\n\t\t\tp.ErrorPage(rw, req, http.StatusForbidden, \"Forbidden\", \"You're not authorized to view this page\")\n\t\t\treturn\n\t\tcase providers.ErrTokenRevoked:\n\t\t\tp.ErrorPage(rw, req, http.StatusUnauthorized, \"Unauthorized\", \"Token Expired or Revoked\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tlogger.Error(err, \"unknown error authenticating user\")\n\t\t\ttags = append(tags, \"error:internal_error\")\n\t\t\tp.StatsdClient.Incr(\"application_error\", tags, 1.0)\n\t\t\t// We don't know exactly what happened, but authenticating the user failed, show an error\n\t\t\tp.ErrorPage(rw, req, http.StatusInternalServerError, \"Internal Error\", \"An unexpected error occurred\")\n\t\t\treturn\n\t\t}\n\t}\n\n\toverhead := time.Now().Sub(start)\n\tp.StatsdClient.Timing(\"request_overhead\", overhead, tags, 1.0)\n\n\tp.handler.ServeHTTP(rw, req)\n}", "func (r *Responder) Conflict() { r.write(http.StatusConflict) }", "func (ctx *HijackRequest) Method() string {\n\treturn ctx.event.Request.Method\n}", "func ProxyRootHandler(\n\tclient *http.Client,\n\ttargetURL, selfURL *url.URL,\n\tlogger *log.Logger,\n) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tnewURL := &url.URL{\n\t\t\tScheme: targetURL.Scheme,\n\t\t\tHost: targetURL.Host,\n\t\t\t// In incoming r.URL only these 2 fields are set:\n\t\t\tPath: r.URL.Path,\n\t\t\tRawQuery: r.URL.RawQuery,\n\t\t}\n\t\treq, err := http.NewRequest(r.Method, newURL.String(), r.Body)\n\t\tif CheckError(logger, w, err) {\n\t\t\treturn\n\t\t}\n\t\treq.Header.Set(\"X-Forwarded-For\", r.RemoteAddr)\n\t\tCopyRequestHeaders(r, req, requestHeadersToCopy)\n\n\t\tresp, err := client.Do(req)\n\t\tif CheckError(logger, w, err) {\n\t\t\treturn\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif CheckError(logger, w, err) {\n\t\t\treturn\n\t\t}\n\n\t\theader := w.Header()\n\t\tfor key, values := range resp.Header {\n\t\t\tcanonicalKey := textproto.CanonicalMIMEHeaderKey(key)\n\t\t\tfor _, value := range values {\n\t\t\t\tif canonicalKey == \"Location\" {\n\t\t\t\t\tvalue = RewriteURL(logger, value, targetURL.Host, selfURL)\n\t\t\t\t}\n\t\t\t\theader.Add(canonicalKey, value)\n\t\t\t}\n\t\t}\n\t\tw.WriteHeader(resp.StatusCode)\n\t\tif _, err := w.Write(body); err != nil {\n\t\t\tif logger != nil {\n\t\t\t\tlogger.Print(err)\n\t\t\t}\n\t\t}\n\t\tif flusher, ok := w.(http.Flusher); ok {\n\t\t\tflusher.Flush()\n\t\t}\n\t}\n}", "func Middleware(h http.Handler) http.Handler {\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n log.Println(\"Running PRE plugin\")\n r.Header.Set(\"X-Trace-ID\", strconv.Itoa(int(rand.Int63())))\n h.ServeHTTP(w, r)\n })\n}", "func (tunnel *TunnelHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\t// execution middleware\n\tctx := tunnel.Ctx.WithRequest(req)\n\tresp, err := ctx.Next(req)\n\tif err != nil && err != MethodNotSupportErr {\n\t\tif resp != nil {\n\t\t\tcopyHeaders(rw.Header(), resp.Header, tunnel.Ctx.KeepDestinationHeaders)\n\t\t\trw.WriteHeader(resp.StatusCode)\n\t\t\tbuf := tunnel.buffer().Get()\n\t\t\t_, err = io.CopyBuffer(rw, resp.Body, buf)\n\t\t\ttunnel.buffer().Put(buf)\n\t\t}\n\t\treturn\n\t}\n\n\t// hijacker connection\n\tproxyClient, err := hijacker(rw)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), 502)\n\t\treturn\n\t}\n\n\tvar (\n\t\tu *url.URL = nil\n\t\ttargetConn net.Conn = nil\n\t\ttargetAddr = hostAndPort(req.URL.Host)\n\t\tisCascadeProxy = false\n\t)\n\tif tunnel.Ctx.Transport != nil && tunnel.Ctx.Transport.Proxy != nil {\n\t\tu, err = tunnel.Ctx.Transport.Proxy(req)\n\t\tif err != nil {\n\t\t\tConnError(proxyClient)\n\t\t\treturn\n\t\t}\n\t\tif u != nil {\n\t\t\t// connect addr eg. \"localhost:80\"\n\t\t\ttargetAddr = hostAndPort(u.Host)\n\t\t\tisCascadeProxy = true\n\t\t}\n\t}\n\n\t// connect to targetAddr\n\ttargetConn, err = tunnel.connContainer().Get(targetAddr)\n\tif err != nil {\n\t\ttargetConn, err = tunnel.ConnectDial(\"tcp\", targetAddr)\n\t\tif err != nil {\n\t\t\tConnError(proxyClient)\n\t\t\treturn\n\t\t}\n\t}\n\n\t// If the ConnContainer is exists,\n\t// When io.CopyBuffer is complete,\n\t// put the idle connection into the ConnContainer so can reuse it next time\n\tdefer func() {\n\t\terr := tunnel.connContainer().Put(targetConn)\n\t\tif err != nil {\n\t\t\t// put conn fail, conn must be closed\n\t\t\t_ = targetConn.Close()\n\t\t}\n\t}()\n\n\t// The cascade proxy needs to forward the request\n\tif isCascadeProxy {\n\t\t// The cascade proxy needs to send it as-is\n\t\t_ = req.Write(targetConn)\n\t} else {\n\t\t// Tell client that the tunnel is ready\n\t\t_, _ = proxyClient.Write(HttpTunnelOk)\n\t}\n\n\tgo func() {\n\t\tbuf := tunnel.buffer().Get()\n\t\t_, _ = io.CopyBuffer(targetConn, proxyClient, buf)\n\t\ttunnel.buffer().Put(buf)\n\t\t_ = proxyClient.Close()\n\t}()\n\tbuf := tunnel.buffer().Get()\n\t_, _ = io.CopyBuffer(proxyClient, targetConn, buf)\n\ttunnel.buffer().Put(buf)\n}", "func interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {\n\n\tif err := auth(ctx); err != nil {\n\t\tfmt.Println(\"111\")\n\t\treturn nil, err\n\t}\n\t//继续处理请求\n\treturn handler(ctx, req)\n\n}", "func (c *UrlReplaceHandler) Intercept(pipeline Pipeline, middlewareIndex int, req *http.Request) (*http.Response, error) {\n\treqOption, ok := req.Context().Value(urlReplaceOptionKey).(urlReplaceOptionsInt)\n\tif !ok {\n\t\treqOption = &c.options\n\t}\n\n\tobsOptions := GetObservabilityOptionsFromRequest(req)\n\tctx := req.Context()\n\tvar span trace.Span\n\tif obsOptions != nil {\n\t\tctx, span = otel.GetTracerProvider().Tracer(obsOptions.GetTracerInstrumentationName()).Start(ctx, \"UrlReplaceHandler_Intercept\")\n\t\tspan.SetAttributes(attribute.Bool(\"com.microsoft.kiota.handler.url_replacer.enable\", true))\n\t\tdefer span.End()\n\t\treq = req.WithContext(ctx)\n\t}\n\n\tif !reqOption.IsEnabled() || len(reqOption.GetReplacementPairs()) == 0 {\n\t\treturn pipeline.Next(req, middlewareIndex)\n\t}\n\n\treq.URL.Path = ReplacePathTokens(req.URL.Path, reqOption.GetReplacementPairs())\n\n\tif span != nil {\n\t\tspan.SetAttributes(attribute.String(\"http.request_url\", req.RequestURI))\n\t}\n\n\treturn pipeline.Next(req, middlewareIndex)\n}", "func protectWebSocket(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\treqURL := req.URL.RequestURI()\n\t\treqURL = strings.ReplaceAll(reqURL, \"\\n\", \"\")\n\t\treqURL = strings.ReplaceAll(reqURL, \"\\r\", \"\")\n\t\tlogging.Log.Debugf(\"Proxying request: %s %s %s\", req.RemoteAddr, req.Method, reqURL)\n\t\tif !checkUpgradeSameOrigin(req) {\n\t\t\torigin := req.Header.Get(\"Origin\")\n\t\t\torigin = strings.ReplaceAll(origin, \"\\n\", \"\")\n\t\t\torigin = strings.ReplaceAll(origin, \"\\r\", \"\")\n\t\t\tlogging.Log.Warnf(\"websocket: Connection upgrade blocked, Host: %s, Origin: %s\", req.Host, origin)\n\t\t\thttp.Error(w, \"websocket: request origin not allowed\", http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(w, req)\n\t})\n}", "func Middleware(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\ttracer := opentracing.GlobalTracer()\n\t\toperationName := fmt.Sprintf(\"%s %s%s\", req.Method, req.Host, req.URL.Path)\n\n\t\tvar span opentracing.Span\n\t\tvar ctx context.Context\n\t\tif spanCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\tspan, ctx = opentracing.StartSpanFromContext(req.Context(), operationName)\n\t\t\text.SpanKindRPCServer.Set(span)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(operationName, ext.RPCServerOption((spanCtx)))\n\t\t\tctx = opentracing.ContextWithSpan(req.Context(), span)\n\t\t\text.SpanKindRPCClient.Set(span)\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tbodyString := string(golib.MaskJSONPassword(body))\n\t\tbodyString = golib.MaskPassword(bodyString)\n\n\t\tisRemoveBody, ok := req.Context().Value(\"remove-tag-body\").(bool)\n\t\tif ok {\n\t\t\tif !isRemoveBody {\n\t\t\t\tspan.SetTag(\"body\", bodyString)\n\t\t\t}\n\t\t} else {\n\t\t\tspan.SetTag(\"body\", bodyString)\n\t\t}\n\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // reuse body\n\n\t\tspan.SetTag(\"http.headers\", req.Header)\n\t\text.HTTPUrl.Set(span, req.Host+req.RequestURI)\n\t\text.HTTPMethod.Set(span, req.Method)\n\n\t\tspan.LogEvent(\"start_handling_request\")\n\n\t\tdefer func() {\n\t\t\tspan.LogEvent(\"complete_handling_request\")\n\t\t\tspan.Finish()\n\t\t}()\n\n\t\th.ServeHTTP(w, req.WithContext(ctx))\n\t})\n}", "func (s *HTTPServer) wrap(handler endpoint, methods []string) http.HandlerFunc {\n\treturn func(resp http.ResponseWriter, req *http.Request) {\n\t\tsetHeaders(resp, s.agent.config.HTTPResponseHeaders)\n\t\tsetTranslateAddr(resp, s.agent.config.TranslateWANAddrs)\n\n\t\t// Obfuscate any tokens from appearing in the logs\n\t\tformVals, err := url.ParseQuery(req.URL.RawQuery)\n\t\tif err != nil {\n\t\t\ts.agent.logger.Printf(\"[ERR] http: Failed to decode query: %s from=%s\", err, req.RemoteAddr)\n\t\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tlogURL := req.URL.String()\n\t\tif tokens, ok := formVals[\"token\"]; ok {\n\t\t\tfor _, token := range tokens {\n\t\t\t\tif token == \"\" {\n\t\t\t\t\tlogURL += \"<hidden>\"\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlogURL = strings.Replace(logURL, token, \"<hidden>\", -1)\n\t\t\t}\n\t\t}\n\t\tlogURL = aclEndpointRE.ReplaceAllString(logURL, \"$1<hidden>$4\")\n\n\t\tif s.blacklist.Block(req.URL.Path) {\n\t\t\terrMsg := \"Endpoint is blocked by agent configuration\"\n\t\t\ts.agent.logger.Printf(\"[ERR] http: Request %s %v, error: %v from=%s\", req.Method, logURL, err, req.RemoteAddr)\n\t\t\tresp.WriteHeader(http.StatusForbidden)\n\t\t\tfmt.Fprint(resp, errMsg)\n\t\t\treturn\n\t\t}\n\n\t\tisForbidden := func(err error) bool {\n\t\t\tif acl.IsErrPermissionDenied(err) || acl.IsErrNotFound(err) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t_, ok := err.(ForbiddenError)\n\t\t\treturn ok\n\t\t}\n\n\t\tisMethodNotAllowed := func(err error) bool {\n\t\t\t_, ok := err.(MethodNotAllowedError)\n\t\t\treturn ok\n\t\t}\n\n\t\tisBadRequest := func(err error) bool {\n\t\t\t_, ok := err.(BadRequestError)\n\t\t\treturn ok\n\t\t}\n\n\t\tisTooManyRequests := func(err error) bool {\n\t\t\t// Sadness net/rpc can't do nice typed errors so this is all we got\n\t\t\treturn err.Error() == consul.ErrRateLimited.Error()\n\t\t}\n\n\t\taddAllowHeader := func(methods []string) {\n\t\t\tresp.Header().Add(\"Allow\", strings.Join(methods, \",\"))\n\t\t}\n\n\t\thandleErr := func(err error) {\n\t\t\ts.agent.logger.Printf(\"[ERR] http: Request %s %v, error: %v from=%s\", req.Method, logURL, err, req.RemoteAddr)\n\t\t\tswitch {\n\t\t\tcase isForbidden(err):\n\t\t\t\tresp.WriteHeader(http.StatusForbidden)\n\t\t\t\tfmt.Fprint(resp, err.Error())\n\t\t\tcase structs.IsErrRPCRateExceeded(err):\n\t\t\t\tresp.WriteHeader(http.StatusTooManyRequests)\n\t\t\tcase isMethodNotAllowed(err):\n\t\t\t\t// RFC2616 states that for 405 Method Not Allowed the response\n\t\t\t\t// MUST include an Allow header containing the list of valid\n\t\t\t\t// methods for the requested resource.\n\t\t\t\t// https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n\t\t\t\taddAllowHeader(err.(MethodNotAllowedError).Allow)\n\t\t\t\tresp.WriteHeader(http.StatusMethodNotAllowed) // 405\n\t\t\t\tfmt.Fprint(resp, err.Error())\n\t\t\tcase isBadRequest(err):\n\t\t\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\t\t\tfmt.Fprint(resp, err.Error())\n\t\t\tcase isTooManyRequests(err):\n\t\t\t\tresp.WriteHeader(http.StatusTooManyRequests)\n\t\t\t\tfmt.Fprint(resp, err.Error())\n\t\t\tdefault:\n\t\t\t\tresp.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tfmt.Fprint(resp, err.Error())\n\t\t\t}\n\t\t}\n\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\ts.agent.logger.Printf(\"[DEBUG] http: Request %s %v (%v) from=%s\", req.Method, logURL, time.Since(start), req.RemoteAddr)\n\t\t}()\n\n\t\tvar obj interface{}\n\n\t\t// if this endpoint has declared methods, respond appropriately to OPTIONS requests. Otherwise let the endpoint handle that.\n\t\tif req.Method == \"OPTIONS\" && len(methods) > 0 {\n\t\t\taddAllowHeader(append([]string{\"OPTIONS\"}, methods...))\n\t\t\treturn\n\t\t}\n\n\t\t// if this endpoint has declared methods, check the request method. Otherwise let the endpoint handle that.\n\t\tmethodFound := len(methods) == 0\n\t\tfor _, method := range methods {\n\t\t\tif method == req.Method {\n\t\t\t\tmethodFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !methodFound {\n\t\t\terr = MethodNotAllowedError{req.Method, append([]string{\"OPTIONS\"}, methods...)}\n\t\t} else {\n\t\t\terr = s.checkWriteAccess(req)\n\n\t\t\tif err == nil {\n\t\t\t\t// Invoke the handler\n\t\t\t\tobj, err = handler(resp, req)\n\t\t\t}\n\t\t}\n\t\tcontentType := \"application/json\"\n\t\thttpCode := http.StatusOK\n\t\tif err != nil {\n\t\t\tif errPayload, ok := err.(CodeWithPayloadError); ok {\n\t\t\t\thttpCode = errPayload.StatusCode\n\t\t\t\tif errPayload.ContentType != \"\" {\n\t\t\t\t\tcontentType = errPayload.ContentType\n\t\t\t\t}\n\t\t\t\tif errPayload.Reason != \"\" {\n\t\t\t\t\tresp.Header().Add(\"X-Consul-Reason\", errPayload.Reason)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandleErr(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif obj == nil {\n\t\t\treturn\n\t\t}\n\t\tvar buf []byte\n\t\tif contentType == \"application/json\" {\n\t\t\tbuf, err = s.marshalJSON(req, obj)\n\t\t\tif err != nil {\n\t\t\t\thandleErr(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tif strings.HasPrefix(contentType, \"text/\") {\n\t\t\t\tif val, ok := obj.(string); ok {\n\t\t\t\t\tbuf = []byte(val)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresp.Header().Set(\"Content-Type\", contentType)\n\t\tresp.WriteHeader(httpCode)\n\t\tresp.Write(buf)\n\t}\n}", "func (s SocksProxy) Rewrite(addr *socks5.AddrSpec) *socks5.AddrSpec {\n\tlog.Infof(\"%+v\", addr)\n\taddr.IP = net.IP{0, 0, 0, 0}\n\t// TODO http or https\n\taddr.Port = s.HttpPort\n\treturn addr\n}", "func proxyHandler(w http.ResponseWriter, r *http.Request) {\n\tif isPreflight(w, r) {\n\t\treturn\n\t}\n\tid := r.Header.Get(\"X-Session-ID\")\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif nil != err {\n\t\tlog.Println(\"Invalid data.\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tif string(body) != id { // Mismatched IDs!\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}\n\t// Maybe confirm that X-Session-ID is the same.\n\tlog.Println(\"Received snowflake: \", id)\n\tsnowflake := AddSnowflake(id)\n\n\t// Wait for a client to avail an offer to the snowflake, or timeout\n\t// and ask the snowflake to poll later.\n\tselect {\n\tcase offer := <-snowflake.offerChannel:\n\t\tlog.Println(\"Passing client offer to snowflake.\")\n\t\tw.Write(offer)\n\n\tcase <-time.After(time.Second * ProxyTimeout):\n\t\t// This snowflake is no longer available to serve clients.\n\t\theap.Remove(snowflakes, snowflake.index)\n\t\tdelete(snowflakeMap, snowflake.id)\n\t\tw.WriteHeader(http.StatusGatewayTimeout)\n\t}\n}", "func (a *Middleware) Wrap(h http.Handler) {\n\ta.Handler = h\n}", "func (r *HijackRouter) Run() {\n\tr.run()\n}", "func bypass(w http.ResponseWriter, r *http.Request, url string, method string, body map[string]interface{}) {\n\tresPayload := make([]byte, 0)\n\n\tlog.Infof(\"Bypassing request\")\n\tif method == \"GET\" {\n\t\tresPayload = makeGetRequest(url, r.Header)\n\t} else if method == \"POST\" {\n\t\tresPayload = makePostRequest(url, body, r.Header)\n\t} else {\n\t\tlog.Errorf(\"Method not supported for bypass\")\n\t}\n\t// Use interface to dynamically get different response JSON structures.\n\tq := make(map[string]interface{})\n\tjson.Unmarshal(resPayload, &q)\n\tif len(q) == 0 {\n\t\tl := make([]interface{}, 0)\n\t\tjson.Unmarshal(resPayload, &l)\n\t\trespondJSON(w, http.StatusOK, l)\n\t} else {\n\t\trespondJSON(w, http.StatusOK, q)\n\t}\n}", "func Recovery(inner http.Handler) http.Handler {\n\trecovery := &SimpleRecovery{}\n\treturn http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {\n\t\trecovery.ServeHTTP(rw, r, inner)\n\t})\n}", "func (ba *BasicAuthenticator) Wrap(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuname, pw, ok := r.BasicAuth()\n\t\tif !ok {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\tw.Write([]byte(\"no basic credentials in request header\"))\n\t\t\treturn\n\t\t}\n\t\tuname, err := ba.authenticate(uname, pw)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\tw.Write([]byte(fmt.Sprintf(\"authentication failed. %s\", err)))\n\t\t\treturn\n\t\t}\n\t\th.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), unameCtxKey, uname)))\n\t})\n}", "func (sm *Manager) HandleHTTPRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\thijacker, ok := w.(http.Hijacker)\n\tif !ok {\n\t\treturn errors.New(\"handler does not support hijack\")\n\t}\n\n\tid := r.Header.Get(headerSessionID)\n\n\tproto := r.Header.Get(\"Upgrade\")\n\n\tsm.mu.Lock()\n\tif _, ok := sm.sessions[id]; ok {\n\t\tsm.mu.Unlock()\n\t\treturn errors.Errorf(\"session %s already exists\", id)\n\t}\n\n\tif proto == \"\" {\n\t\tsm.mu.Unlock()\n\t\treturn errors.New(\"no upgrade proto in request\")\n\t}\n\n\tif proto != \"h2c\" {\n\t\tsm.mu.Unlock()\n\t\treturn errors.Errorf(\"protocol %s not supported\", proto)\n\t}\n\n\tconn, _, err := hijacker.Hijack()\n\tif err != nil {\n\t\tsm.mu.Unlock()\n\t\treturn errors.Wrap(err, \"failed to hijack connection\")\n\t}\n\n\tresp := &http.Response{\n\t\tStatusCode: http.StatusSwitchingProtocols,\n\t\tProtoMajor: 1,\n\t\tProtoMinor: 1,\n\t\tHeader: http.Header{},\n\t}\n\tresp.Header.Set(\"Connection\", \"Upgrade\")\n\tresp.Header.Set(\"Upgrade\", proto)\n\n\t// set raw mode\n\tconn.Write([]byte{})\n\tresp.Write(conn)\n\n\treturn sm.handleConn(ctx, conn, r.Header)\n}", "func Force(host string, handler http.Handler) http.Handler {\n\treturn https.Force(host, handler)\n}", "func (r *Responder) PermanentRedirect() { r.write(http.StatusPermanentRedirect) }", "func main() {\n\tdefer gock.Off()\n\n\tgock.New(\"http://httpbin.org\").\n\t\tGet(\"/*\").\n\t\tReply(204).\n\t\tSetHeader(\"Server\", \"gock\")\n\n\tcli := gentleman.New()\n\n\tcli.UseHandler(\"before dial\", func(ctx *context.Context, h context.Handler) {\n\t\tgock.InterceptClient(ctx.Client)\n\t\th.Next(ctx)\n\t})\n\n\tres, err := cli.Request().URL(\"http://httpbin.org/get\").Send()\n\tif err != nil {\n\t\tfmt.Errorf(\"Error: %s\", err)\n\t}\n\n\tfmt.Printf(\"Status: %d\\n\", res.StatusCode)\n\tfmt.Printf(\"Server header: %s\\n\", res.Header.Get(\"Server\"))\n}", "func (ctx *HijackRequest) Header(key string) string {\n\treturn ctx.event.Request.Headers[key].String()\n}", "func (b *BasicAuthenticationBackend) Wrap(wrapped auth.AuthenticatedHandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\ttoken := tokenFromRequest(r)\n\n\t\t// if not coming from cookie or X-Auth-Token\n\t\ts := strings.SplitN(token, \" \", 2)\n\t\tif len(s) == 2 || s[0] == \"Basic\" {\n\t\t\ttoken = s[1]\n\t\t}\n\n\t\t// add \"fake\" header to let the basic auth library do the authentication\n\t\tr.Header.Set(\"Authorization\", \"Basic \"+token)\n\n\t\tif username := b.CheckAuth(r); username == \"\" {\n\t\t\tUnauthorized(w, r, ErrWrongCredentials)\n\t\t} else {\n\t\t\tauthCallWrapped(w, r, username, wrapped)\n\t\t}\n\t}\n}", "func badGateway(rw http.ResponseWriter, r *http.Request) {\n\n}", "func (r rewrite) Rewrite(ctx context.Context, req *socks5.Request) (context.Context, *socks5.AddrSpec) {\n\thash := fnv.New32a()\n\thash.Write(req.RemoteAddr.IP)\n\thash.Write(req.DestAddr.IP)\n\treturn context.WithValue(ctx, \"hint\", hash.Sum32()), req.DestAddr\n}", "func HijackTLSConnection(certAuthority *tls.Certificate, c net.Conn, domainName string,\n\tonHandshake func(error) error) (serverConn *tls.Conn, targetServerName string, err error) {\n\ttargetServerName = domainName\n\tif len(domainName) == 0 || strings.Contains(domainName, \":\") {\n\t\terr = onHandshake(errWrongDomain)\n\t\treturn\n\t}\n\t// make a cert for the provided domain\n\tvar fakeTargetServerCert *tls.Certificate\n\tfakeTargetServerCert, err = SignLeafCertUsingCertAuthority(certAuthority, []string{domainName})\n\tif err != nil {\n\t\terr = onHandshake(err)\n\t\treturn\n\t}\n\tfakeTargetServerTLSConfig := &tls.Config{\n\t\tCertificates: []tls.Certificate{*fakeTargetServerCert},\n\t\tGetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\t\tif len(hello.ServerName) > 0 {\n\t\t\t\ttargetServerName = hello.ServerName\n\t\t\t}\n\t\t\treturn SignLeafCertUsingCertAuthority(certAuthority, []string{targetServerName})\n\t\t},\n\t}\n\t// perform the fake handshake with the connection given\n\tserverConn = tls.Server(c, fakeTargetServerTLSConfig)\n\tif onHandshake != nil {\n\t\tif err = onHandshake(nil); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tif err = serverConn.Handshake(); err != nil {\n\t\tserverConn.Close()\n\t\tserverConn = nil\n\t}\n\treturn\n}", "func (v *Verifier) Wrap(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {\n\t\tv.Negroni().ServeHTTP(rw, req, handler.ServeHTTP)\n\t})\n}", "func PreflightHandler(w http.ResponseWriter, r *http.Request) {\n headers := []string{\"Content-Type\", \"Accept\", \"Authorization\"}\n w.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(headers, \",\"))\n methods := []string{\"GET\", \"HEAD\", \"POST\", \"PUT\", \"DELETE\"}\n w.Header().Set(\"Access-Control-Allow-Methods\", strings.Join(methods, \",\"))\n glog.Infof(\"preflight request for %s\", r.URL.Path)\n}", "func HttpHandler(svc Service) http.Handler {\n\treturn http.HandlerFunc(func(rw http.ResponseWriter, httpReq *http.Request) {\n\t\tif httpReq.Body != nil {\n\t\t\tdefer httpReq.Body.Close()\n\t\t}\n\n\t\treq := Request{\n\t\t\tContext: httpReq.Context(),\n\t\t\tRequest: *httpReq}\n\t\tif h, ok := rw.(http.Hijacker); ok {\n\t\t\treq.hijacker = h\n\t\t}\n\t\trsp := svc(req)\n\n\t\t// If the connection was hijacked, we should not attempt to write anything out\n\t\tif rsp.hijacked {\n\t\t\treturn\n\t\t}\n\n\t\trwHeader := rw.Header()\n\t\tfor k, v := range rsp.Header {\n\t\t\trwHeader[k] = v\n\t\t}\n\t\trw.WriteHeader(rsp.StatusCode)\n\t\tif rsp.Body != nil && bodyAllowedForStatus(rsp.StatusCode) {\n\t\t\tdefer rsp.Body.Close()\n\t\t\tbuf := *httpChunkBufPool.Get().(*[]byte)\n\t\t\tdefer httpChunkBufPool.Put(&buf)\n\t\t\tif isStreamingRsp(rsp) {\n\t\t\t\t// Streaming responses use copyChunked(), which takes care of flushing transparently\n\t\t\t\tif _, err := copyChunked(rw, rsp.Body, buf); err != nil {\n\t\t\t\t\tslog.Log(slog.Eventf(copyErrSeverity(err), req, \"Couldn't send streaming response body\", err))\n\n\t\t\t\t\t// Prevent the client from accidentally consuming a truncated stream by aborting the response.\n\t\t\t\t\t// The official way of interrupting an HTTP reply mid-stream is panic(http.ErrAbortHandler), which\n\t\t\t\t\t// works for both HTTP/1.1 and HTTP.2. https://github.com/golang/go/issues/17790\n\t\t\t\t\tpanic(http.ErrAbortHandler)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif _, err := io.CopyBuffer(rw, rsp.Body, buf); err != nil {\n\t\t\t\t\tslog.Log(slog.Eventf(copyErrSeverity(err), req, \"Couldn't send response body\", err))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}", "func intercept(p *supervisor.Process, tele *Teleproxy) error {\n\tif os.Geteuid() != 0 {\n\t\treturn errors.New(\"ERROR: teleproxy must be run as root or suid root\")\n\t}\n\n\tsup := p.Supervisor()\n\n\tif tele.DNSIP == \"\" {\n\t\tdat, err := ioutil.ReadFile(\"/etc/resolv.conf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, line := range strings.Split(string(dat), \"\\n\") {\n\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"nameserver\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\ttele.DNSIP = fields[1]\n\t\t\t\tlog.Printf(\"TPY: Automatically set -dns=%v\", tele.DNSIP)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif tele.DNSIP == \"\" {\n\t\treturn errors.New(\"couldn't determine dns ip from /etc/resolv.conf\")\n\t}\n\n\tif tele.FallbackIP == \"\" {\n\t\tif tele.DNSIP == \"8.8.8.8\" {\n\t\t\ttele.FallbackIP = \"8.8.4.4\"\n\t\t} else {\n\t\t\ttele.FallbackIP = \"8.8.8.8\"\n\t\t}\n\t\tlog.Printf(\"TPY: Automatically set -fallback=%v\", tele.FallbackIP)\n\t}\n\tif tele.FallbackIP == tele.DNSIP {\n\t\treturn errors.New(\"if your fallbackIP and your dnsIP are the same, you will have a dns loop\")\n\t}\n\n\ticeptor := interceptor.NewInterceptor(\"teleproxy\")\n\tapis, err := api.NewAPIServer(iceptor)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"API Server\")\n\t}\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: TranslatorWorker,\n\t\t// XXX: Requires will need to include the api server once it is changed to not bind early\n\t\tRequires: []string{ProxyWorker, DNSServerWorker},\n\t\tWork: iceptor.Work,\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: APIWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tapis.Start()\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\tapis.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSServerWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tsrv := dns.Server{\n\t\t\t\tListeners: dnsListeners(p, DNSRedirPort),\n\t\t\t\tFallback: tele.FallbackIP + \":53\",\n\t\t\t\tResolve: func(domain string) string {\n\t\t\t\t\troute := iceptor.Resolve(domain)\n\t\t\t\t\tif route != nil {\n\t\t\t\t\t\treturn route.Ip\n\t\t\t\t\t}\n\t\t\t\t\treturn \"\"\n\t\t\t\t},\n\t\t\t}\n\t\t\terr := srv.Start(p)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no srv.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: ProxyWorker,\n\t\tRequires: []string{},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\t// hmm, we may not actually need to get the original\n\t\t\t// destination, we could just forward each ip to a unique port\n\t\t\t// and either listen on that port or run port-forward\n\t\t\tproxy, err := proxy.NewProxy(fmt.Sprintf(\":%s\", ProxyRedirPort), iceptor.Destination)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Proxy\")\n\t\t\t}\n\n\t\t\tproxy.Start(10000)\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\t\t\t// there is no proxy.Stop()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\tsup.Supervise(&supervisor.Worker{\n\t\tName: DNSConfigWorker,\n\t\tRequires: []string{TranslatorWorker},\n\t\tWork: func(p *supervisor.Process) error {\n\t\t\tbootstrap := route.Table{Name: \"bootstrap\"}\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tIp: tele.DNSIP,\n\t\t\t\tTarget: DNSRedirPort,\n\t\t\t\tProto: \"udp\",\n\t\t\t})\n\t\t\tbootstrap.Add(route.Route{\n\t\t\t\tName: \"teleproxy\",\n\t\t\t\tIp: MagicIP,\n\t\t\t\tTarget: apis.Port(),\n\t\t\t\tProto: \"tcp\",\n\t\t\t})\n\t\t\ticeptor.Update(bootstrap)\n\n\t\t\tvar restore func()\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore = dns.OverrideSearchDomains(p, \".\")\n\t\t\t}\n\n\t\t\tp.Ready()\n\t\t\t<-p.Shutdown()\n\n\t\t\tif !tele.NoSearch {\n\t\t\t\trestore()\n\t\t\t}\n\n\t\t\tdns.Flush()\n\t\t\treturn nil\n\t\t},\n\t})\n\n\treturn nil\n}", "func Proxy(addr string, logger Logger) dns.Handler {\n\treturn dns.HandlerFunc(func(w dns.ResponseWriter, req *dns.Msg) {\n\t\t// log request\n\t\tif logger != nil {\n\t\t\tlogger(ProxyRequest, req, nil, \"\")\n\t\t}\n\n\t\t// forward request to fallback\n\t\trs, err := dns.Exchange(req, addr)\n\t\tif err != nil {\n\t\t\tif logger != nil {\n\t\t\t\tlogger(ProxyError, nil, err, \"\")\n\t\t\t}\n\t\t\t_ = w.Close()\n\t\t\treturn\n\t\t}\n\n\t\t// log response\n\t\tif logger != nil {\n\t\t\tlogger(ProxyResponse, rs, nil, \"\")\n\t\t}\n\n\t\t// write response\n\t\terr = w.WriteMsg(rs)\n\t\tif err != nil {\n\t\t\tif logger != nil {\n\t\t\t\tlogger(NetworkError, nil, err, \"\")\n\t\t\t}\n\t\t\t_ = w.Close()\n\t\t}\n\t})\n}", "func (a *APITest) Intercept(interceptor Intercept) *APITest {\n\ta.request.interceptor = interceptor\n\treturn a\n}", "func (client *Client) Middleware() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif !client.isAllowedPathToCache(c.Request().URL.String()) {\n\t\t\t\tnext(c)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif client.cacheableMethod(c.Request().Method) {\n\t\t\t\tsortURLParams(c.Request().URL)\n\t\t\t\tkey := generateKey(c.Request().URL.String())\n\t\t\t\tif c.Request().Method == http.MethodPost && c.Request().Body != nil {\n\t\t\t\t\tbody, err := ioutil.ReadAll(c.Request().Body)\n\t\t\t\t\tdefer c.Request().Body.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tnext(c)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treader := ioutil.NopCloser(bytes.NewBuffer(body))\n\t\t\t\t\tkey = generateKeyWithBody(c.Request().URL.String(), body)\n\t\t\t\t\tc.Request().Body = reader\n\t\t\t\t}\n\n\t\t\t\tparams := c.Request().URL.Query()\n\t\t\t\tif _, ok := params[client.refreshKey]; ok {\n\t\t\t\t\tdelete(params, client.refreshKey)\n\n\t\t\t\t\tc.Request().URL.RawQuery = params.Encode()\n\t\t\t\t\tkey = generateKey(c.Request().URL.String())\n\n\t\t\t\t\tclient.adapter.Release(key)\n\t\t\t\t} else {\n\t\t\t\t\tb, ok := client.adapter.Get(key)\n\t\t\t\t\tresponse := BytesToResponse(b)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tif response.Expiration.After(time.Now()) {\n\t\t\t\t\t\t\tresponse.LastAccess = time.Now()\n\t\t\t\t\t\t\tresponse.Frequency++\n\t\t\t\t\t\t\tclient.adapter.Set(key, response.Bytes(), response.Expiration)\n\n\t\t\t\t\t\t\t//w.WriteHeader(http.StatusNotModified)\n\t\t\t\t\t\t\tfor k, v := range response.Header {\n\t\t\t\t\t\t\t\tc.Response().Header().Set(k, strings.Join(v, \",\"))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tc.Response().WriteHeader(http.StatusOK)\n\t\t\t\t\t\t\tc.Response().Write(response.Value)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tclient.adapter.Release(key)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresBody := new(bytes.Buffer)\n\t\t\t\tmw := io.MultiWriter(c.Response().Writer, resBody)\n\t\t\t\twriter := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}\n\t\t\t\tc.Response().Writer = writer\n\t\t\t\tif err := next(c); err != nil {\n\t\t\t\t\tc.Error(err)\n\t\t\t\t}\n\n\t\t\t\tstatusCode := writer.statusCode\n\t\t\t\tvalue := resBody.Bytes()\n\t\t\t\tif statusCode < 400 {\n\t\t\t\t\tnow := time.Now()\n\n\t\t\t\t\tresponse := Response{\n\t\t\t\t\t\tValue: value,\n\t\t\t\t\t\tHeader: writer.Header(),\n\t\t\t\t\t\tExpiration: now.Add(client.ttl),\n\t\t\t\t\t\tLastAccess: now,\n\t\t\t\t\t\tFrequency: 1,\n\t\t\t\t\t}\n\t\t\t\t\tclient.adapter.Set(key, response.Bytes(), response.Expiration)\n\t\t\t\t}\n\t\t\t\t//for k, v := range writer.Header() {\n\t\t\t\t//\tc.Response().Header().Set(k, strings.Join(v, \",\"))\n\t\t\t\t//}\n\t\t\t\t//c.Response().WriteHeader(statusCode)\n\t\t\t\t//c.Response().Write(value)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func hstsHandler(fn http.HandlerFunc) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Strict-Transport-Security\", \"max-age=31536000; preload\")\n\t\tfn(w, r)\n\t})\n}", "func logger(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\twi := &interceptor{delegate: w}\n\t\tdefer func() {\n\t\t\tlog.Println(r.RemoteAddr, \" \", r.Method, \" \", r.RequestURI, \" \", r.Proto, \" \", wi.Status, \" \", wi.Bytes)\n\t\t}()\n\t\tnext.ServeHTTP(wi, r)\n\t})\n}", "func (h *middlewareHarness) interceptStream(methodURI string,\n\texpectedRequest proto.Message, responseReplacement proto.Message,\n\treadOnly bool) {\n\n\t// Read intercept message and make sure it's for an RPC stream auth.\n\tauthIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\n\t// Make sure the custom condition is populated correctly (if we're using\n\t// a macaroon with a custom condition).\n\tif !readOnly {\n\t\trequire.Equal(\n\t\t\th.t, \"itest-value\", authIntercept.CustomCaveatCondition,\n\t\t)\n\t}\n\n\tauth := authIntercept.GetStreamAuth()\n\trequire.NotNil(h.t, auth)\n\n\t// This is just the authentication, so we can only look at the URI.\n\trequire.Equal(h.t, methodURI, auth.MethodFullUri)\n\n\t// We need to accept the auth.\n\th.sendAccept(authIntercept.MsgId, nil)\n\n\t// Read intercept message and make sure it's for an RPC request.\n\treqIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\treq := reqIntercept.GetRequest()\n\trequire.NotNil(h.t, req)\n\n\t// We know the request we're going to send so make sure we get the right\n\t// type and content from the interceptor.\n\trequire.Equal(h.t, methodURI, req.MethodFullUri)\n\tassertInterceptedType(h.t, expectedRequest, req)\n\n\t// We need to accept the request.\n\th.sendAccept(reqIntercept.MsgId, nil)\n\n\t// Now read the intercept message for the response.\n\trespIntercept, err := h.stream.Recv()\n\trequire.NoError(h.t, err)\n\tres := respIntercept.GetResponse()\n\trequire.NotNil(h.t, res)\n\n\t// We expect the request ID to be the same for the auth intercept,\n\t// request intercept and the response intercept messages. But the\n\t// message IDs must be different/unique.\n\trequire.Equal(h.t, authIntercept.RequestId, respIntercept.RequestId)\n\trequire.Equal(h.t, reqIntercept.RequestId, respIntercept.RequestId)\n\trequire.NotEqual(h.t, authIntercept.MsgId, reqIntercept.MsgId)\n\trequire.NotEqual(h.t, authIntercept.MsgId, respIntercept.MsgId)\n\trequire.NotEqual(h.t, reqIntercept.MsgId, respIntercept.MsgId)\n\n\t// We need to accept the response as well.\n\th.sendAccept(respIntercept.MsgId, responseReplacement)\n\n\th.responsesChan <- res\n}", "func (s *Serverus) ChainInterceptors(inter interface{}) {}", "func (r *ProxyHandler) tryUpgrade(w http.ResponseWriter, req, newReq *http.Request, location *url.URL, transport http.RoundTripper, gv schema.GroupVersion) bool {\n\tif !httpstream.IsUpgradeRequest(req) {\n\t\treturn false\n\t}\n\tbackendConn, err := proxyutil.DialURL(location, transport)\n\tif err != nil {\n\t\tresponsewriters.ErrorNegotiated(err, r.Serializer, gv, w, req)\n\t\treturn true\n\t}\n\tdefer backendConn.Close()\n\n\t// TODO should we use _ (a bufio.ReadWriter) instead of requestHijackedConn\n\t// when copying between the client and the backend? Docker doesn't when they\n\t// hijack, just for reference...\n\trequestHijackedConn, _, err := w.(http.Hijacker).Hijack()\n\tif err != nil {\n\t\tresponsewriters.ErrorNegotiated(err, r.Serializer, gv, w, req)\n\t\treturn true\n\t}\n\tdefer requestHijackedConn.Close()\n\n\tif err = newReq.Write(backendConn); err != nil {\n\t\tresponsewriters.ErrorNegotiated(err, r.Serializer, gv, w, req)\n\t\treturn true\n\t}\n\n\tdone := make(chan struct{}, 2)\n\n\tgo func() {\n\t\t_, err := io.Copy(backendConn, requestHijackedConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tglog.Errorf(\"Error proxying data from client to backend: %v\", err)\n\t\t}\n\t\tdone <- struct{}{}\n\t}()\n\n\tgo func() {\n\t\t_, err := io.Copy(requestHijackedConn, backendConn)\n\t\tif err != nil && !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\tglog.Errorf(\"Error proxying data from backend to client: %v\", err)\n\t\t}\n\t\tdone <- struct{}{}\n\t}()\n\n\t<-done\n\treturn true\n}", "func HSTSMiddleware(h http.HandlerFunc) http.HandlerFunc {\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Allow only https connections for the next 2 years, requesting to be preloaded\n\t\tw.Header().Set(\"Strict-Transport-Security\", \"max-age=63072000; includeSubDomains; preload\")\n\n\t\t// Call the handler\n\t\th(w, r)\n\n\t}\n}", "func (ghost *Ghost) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tvar conn, _, err = w.(http.Hijacker).Hijack()\n\tif err != nil {\n\t\tlog.Print(\"rpc hijacking \", req.RemoteAddr, \": \", err.Error())\n\t\treturn\n\t}\n\tio.WriteString(conn, \"HTTP/1.1 200\\n\")\n\tio.WriteString(conn, \"Content-Type: application/json-rpc\\n\\n\")\n\tghost.server.ServeCodec(jsonrpc.NewServerCodec(conn))\n}", "func (r *Responder) MovedPermanently() { r.write(http.StatusMovedPermanently) }", "func LogRequest(r *http.Request, t string) {\n\tas_c := new(bytes.Buffer)\n\tr.ParseForm()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogger.Printf(\"[!] Error: %s\\n\", err)\n\t}\n\tip, _, err := net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\tlogger.Printf(\"[!] Error: %s\\n\", err)\n\t}\n\t// Create the attack entry\n\tattack := Attack{\n\t\tTimestamp: time.Now(),\n\t\tSourceIP: ip,\n\t\tMethod: r.Method,\n\t\tURL: strings.Join([]string{r.Host, r.URL.String()}, \"\"),\n\t\tForm: r.Form.Encode(),\n\t\tPayload: string(body),\n\t\tHost: r.Host,\n\t\tUserAgent: r.UserAgent(),\n\t\tContentType: r.Header.Get(\"Content-Type\"),\n\t\tAcceptLanguage: r.Header.Get(\"Accept-Language\"),\n\t\tSensorIP: Conf.SensorIP,\n\t\tType: t,\n\t}\n\t// Convert to JSON\n\tas, err := JSONMarshal(attack)\n\tif err != nil {\n\t\tlogger.Printf(\"[!] ERROR: %s\\n\", err)\n\t}\n\terr = json.Compact(as_c, as)\n\tfmt.Printf(\"%s\\n\", as)\n\t// Log the entry\n\tf, err := os.OpenFile(*logFlag, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0660)\n\tif err != nil {\n\t\tlogger.Printf(\"[!] ERROR: %s\\n\", err)\n\t} else {\n\t\tdefer f.Close()\n\t\tif _, err = f.WriteString(string(as_c.String()) + \"\\n\"); err != nil {\n\t\t\tlogger.Printf(\"[!] ERROR: %s\\n\", err)\n\t\t}\n\t}\n\t// If the client wants to use a remote server, let's upload the attack data\n\tif Conf.UseRemote {\n\t\tbuff := bytes.NewBuffer(as)\n\t\treq, err := http.NewRequest(\"POST\", Conf.Remote.URL, buff)\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"[!] Error: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\t// Set the Basic Auth if desired\n\t\tif Conf.Remote.UseAuth {\n\t\t\treq.SetBasicAuth(Conf.Remote.Auth.Username, Conf.Remote.Auth.Password)\n\t\t}\n\t\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"elastichoney v%s\", version))\n\t\tclient := &http.Client{}\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"[!] Error: %s\\n\", err)\n\t\t} else {\n\t\t\tif *verboseFlag {\n\t\t\t\tlogger.Printf(\"Upload Status: %d\\n\", resp.StatusCode)\n\t\t\t}\n\t\t}\n\t}\n\n\tif Conf.HpFeeds.Enabled {\n\t\thpfeedsChannel <- []byte(as_c.String())\n\t}\n}" ]
[ "0.7620157", "0.754383", "0.7506798", "0.7460087", "0.74350834", "0.7414825", "0.738739", "0.7385394", "0.7369718", "0.7350782", "0.7296897", "0.72345155", "0.7159378", "0.7158735", "0.7012246", "0.70109314", "0.69657886", "0.68642426", "0.68232936", "0.67975926", "0.6614268", "0.6349469", "0.62204444", "0.59386337", "0.5808979", "0.5654732", "0.5590196", "0.5387266", "0.5292705", "0.5259284", "0.52152103", "0.5207227", "0.51745796", "0.5049457", "0.5019045", "0.5018777", "0.4955766", "0.49542296", "0.49259815", "0.49081182", "0.48817503", "0.48777056", "0.4870819", "0.48697102", "0.4864701", "0.48485628", "0.4808769", "0.4803533", "0.4796454", "0.47943133", "0.47797647", "0.47674665", "0.4747344", "0.47384727", "0.47384128", "0.47053763", "0.47044846", "0.47040507", "0.46903265", "0.46844572", "0.46777654", "0.46569005", "0.46374145", "0.46142802", "0.45756343", "0.45475996", "0.45343286", "0.45267826", "0.45186365", "0.44830662", "0.44581932", "0.4455241", "0.44402206", "0.44307387", "0.4429085", "0.44267216", "0.4422544", "0.44138208", "0.44055498", "0.43975842", "0.43952158", "0.43872663", "0.43787423", "0.43643755", "0.4362519", "0.43608347", "0.43605417", "0.43556508", "0.43542278", "0.43516046", "0.43442118", "0.43425202", "0.43401575", "0.43319952", "0.4327802", "0.43235368", "0.43175885", "0.4315289", "0.43132362" ]
0.7054844
14
CloseNotify implements the http.CloseNotify interface.
func (w *responseWriter) CloseNotify() <-chan bool { return w.ResponseWriter.(http.CloseNotifier).CloseNotify() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (resp *response) CloseNotify() <-chan bool {\n\treturn resp.ResponseWriter.(http.CloseNotifier).CloseNotify()\n}", "func (r *responseWriterWithCloseNotify) CloseNotify() <-chan bool {\n\treturn r.rw.(http.CloseNotifier).CloseNotify()\n}", "func (r *Response) CloseNotify() <-chan bool {\n\treturn r.ResponseWriter.(http.CloseNotifier).CloseNotify()\n}", "func (cr *connReader) closeNotify() {\n\tres, _ := cr.conn.curReq.Load().(*response)\n\tif res != nil && atomic.CompareAndSwapInt32(&res.didCloseNotify, 0, 1) {\n\t\tres.closeNotifyCh <- true\n\t}\n}", "func (c *connReader) closeNotify() {\n\t// @comment : loads it from atomic value\n\tres, _ := c.conn.curReq.Load().(*response)\n\tif res != nil {\n\t\tif atomic.CompareAndSwapInt32(&res.didCloseNotify, 0, 1) {\n\t\t\tres.closeNotifyCh <- true\n\t\t}\n\t}\n}", "func (w *responseWriter) CloseNotify() <-chan bool {\n\tif notifier, ok := w.ResponseWriter.(http.CloseNotifier); ok {\n\t\treturn notifier.CloseNotify()\n\t}\n\treturn nil\n}", "func (w *responseWriter) CloseNotify() <-chan bool {\n\tif closeNotifier, ok := w.ResponseWriter.(http.CloseNotifier); ok {\n\t\treturn closeNotifier.CloseNotify()\n\t}\n\treturn nil\n}", "func (g *GzipResponse) CloseNotify() <-chan bool {\n\treturn g.r.CloseNotify()\n}", "func (c *CompressingResponseWriter) CloseNotify() <-chan bool {\n\treturn c.writer.(http.CloseNotifier).CloseNotify()\n}", "func (w *ResponseWriter) CloseNotify() <-chan bool {\n\treturn w.closeNotifyChan\n}", "func (w *BaseWebsocketClient) OnClose(wasClean bool, code int, reason string) {}", "func CloseNotify(c chan os.Signal) {\n\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGUSR1)\n}", "func (s *Stream) CloseNotify() <-chan struct{} {\n\treturn s.nc\n}", "func (c *CallbackService) Close() {\n\tc.httpServer.Shutdown()\n}", "func (n *Notify) Close() {\n\tif n.isClosed {\n\t\treturn\n\t}\n\tn.watcher.Close()\n\tn.isClosed = true\n}", "func (v *NotifyNotification) Close() error {\n\tvar err *C.GError\n\tc := C.notify_notification_close(v.native(), &err)\n\tif c == 0 {\n\t\tdefer C.g_error_free(err)\n\t\treturn errors.New(goString(err.message))\n\t}\n\treturn nil\n}", "func (h *HTTP) Close() error {\n\treturn nil\n}", "func (s *Connection) NotifyClose(c chan<- *Stream, timeout time.Duration) {\n\ts.goAwayTimeout = timeout\n\ts.lastStreamChan = c\n}", "func (f *Pub) CloseNotify() <-chan bool {\n\treturn f.csignal\n}", "func (c *connection) Close() {\n\tbaseurl := \"http://fritz.box/webservices/homeautoswitch.lua\"\n\tparameters := make(map[string]string)\n\tparameters[\"sid\"] = c.sid\n\tparameters[\"logout\"] = \"logout\"\n\tUrl := prepareRequest(baseurl, parameters)\n\tsendRequest(Url)\n}", "func (c *Client) Close() {}", "func (c *Client) Close() {}", "func (cPtr *Client) Close() {\n\tif cPtr.isHTTP {\n\t\treturn\n\t}\n\tselect {\n\tcase cPtr.close <- struct{}{}:\n\t\t<-cPtr.didQuit\n\tcase <-cPtr.didQuit:\n\t}\n}", "func Close(URL *url.URL) error { return request(URL, http.MethodDelete, nil, nil) }", "func (v *DCHttpResponse) Close() {\n\tif !v.Raw.Close && v.Raw.Body != nil {\n\t\tv.Raw.Body.Close()\n\t}\n}", "func (p *ClientsPool) Close() {\n\tclose(p.notifications)\n}", "func (e *HTTPExecuter) Close() {}", "func (c *Client) Close() {\n}", "func (c *Client) Close() {\n}", "func (n *ConfirmChanNotifier) Close() {\n\tclose(n.C)\n}", "func (fic *FakeClient) Close() {\n}", "func (c *AuditClient) Close() error {\n\tvar err error\n\n\t// Only unregister and close the socket once.\n\tc.closeOnce.Do(func() {\n\t\tif c.clearPIDOnClose {\n\t\t\t// Unregister from the kernel for a clean exit.\n\t\t\tstatus := AuditStatus{\n\t\t\t\tMask: AuditStatusPID,\n\t\t\t\tPID: 0,\n\t\t\t}\n\t\t\terr = c.set(status, NoWait)\n\t\t}\n\n\t\terr = multierr.Append(err, c.Netlink.Close())\n\t})\n\n\treturn err\n}", "func (w *Watcher) Close() {\n\t_ = w.Client.Close()\n}", "func (n *ReturnChanNotifier) Close() {\n\tclose(n.C)\n}", "func (s *JSONHTTPServer) Close() error {\n\tlog.Debug(\"Stopping json-http service...\")\n\tif s.server != nil {\n\t\tif err := s.server.Shutdown(context.TODO()); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (w *ResponseWriter) Close() {\n\tif !w.closed {\n\t\tw.closed = true\n\t\tw.closeNotifyChan <- w.closed\n\t}\n}", "func (h *HTTPTester) Close() error {\n\treturn nil\n}", "func (s *JSONHTTPServer) Close() error {\n\tlog.Debug(\"stopping new json-http service...\")\n\tserver := s.getServer()\n\tif server != nil {\n\t\tctx := cmdp.Ctx()\n\n\t\tif err := server.Shutdown(ctx); err != nil {\n\t\t\treturn fmt.Errorf(\"shutdown: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (w *closeableWriter) CloseNotify() <-chan bool {\n\treturn w.ch\n}", "func (*GenericFramework) Close(ctx *NetworkContext) {}", "func (a *AbstractSessionChannelHandler) OnClose() {}", "func (n *ErrorChanNotifier) Close() {\n\tclose(n.C)\n}", "func (t *Client) Close() error { return nil }", "func (w *PrometheusWriter) Close() error {\n\tlogger.Debug.Printf(\"stopping HTTP server (%s)...\\n\", w.srv.Addr)\n\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\treturn w.srv.Shutdown(ctx)\n}", "func (bn *BasicNotifiee) ListenClose(n net.Network, addr ma.Multiaddr) {\n\tglog.V(4).Infof(\"Notifiee - Close: %v\", addr)\n}", "func (c *cloudChannelRESTClient) Close() error {\n\t// Replace httpClient with nil to force cleanup.\n\tc.httpClient = nil\n\treturn nil\n}", "func (db *DB) NotifyClose() <-chan struct{} {\n\treturn db.notifyQuit\n}", "func (p *pingChannelServer) OnClose(msg string) {\n\tlogging.Println(\"server onclose \" + msg)\n}", "func (s *HTTPServer) Close() error { s.ln.Close(); return nil }", "func (notifee *Notifee) ListenClose(network.Network, multiaddr.Multiaddr) {}", "func (c *whoisClient) Close() error {\n\tc.Conn.SetWriteDeadline(time.Now().Add(time.Second))\n\n\tc.w.Write([]byte(\"end\"))\n\tc.w.Write(ncEOL)\n\t// This error is not important, because the previous are a courtesy.\n\tc.w.Flush()\n\treturn c.Conn.Close()\n}", "func (ch *Channel) Close() {}", "func (c *Client) Close() {\n\tc.HTTPClient.CloseIdleConnections()\n}", "func (file *Remote) Close() error {\n\t_, err := file.client.Send(&Tclunk{\n\t\tFID: file.fid,\n\t})\n\treturn err\n}", "func (s *Server) Close() {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tif err := s.httpServer.Shutdown(ctx); err != nil {\n\t\tlog.Errora(\"Failed to shutdown the HTTP server\", err)\n\t}\n\tcancel()\n\tlog.Debug(\"Agent server closed\")\n}", "func (r *Rietveld) Close(issue int64, message string) error {\n\tif err := r.AddComment(issue, message); err != nil {\n\t\treturn err\n\t}\n\treturn r.post(fmt.Sprintf(\"/%d/close\", issue), nil)\n}", "func (h *Health) Close() error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\terr := h.server.Shutdown(ctx)\n\th.wg.Wait()\n\treturn err\n}", "func (c Client) Notify(ctx context.Context, ee logger.ErrorEvent) {\n\tc.Client.CaptureEvent(errEvent(ctx, ee), nil, raven.NewScope())\n\tc.Client.Flush(c.Config.FlushTimeoutOrDefault()) // goose this a bit\n}", "func (c *connReader) closeNotifyFromPipelinedRequest() {\n\tc.closeNotify()\n}", "func (c *UDPChannel) Close() {\n\n}", "func (h *Handler) Close() {\n}", "func (s *Service) Close() {\n}", "func (s *Service) Close() {\n}", "func (s *Service) Close() {\n}", "func (s *Service) Close() {\n}", "func (c *RemoteHTTP) Close() {\n\tc.HTTPClient = nil\n\n\tif c.SSHSession != nil {\n\t\tc.SSHSession.Close()\n\t\tc.SSHSession = nil\n\t}\n\n\tif c.SSHClient != nil {\n\t\tc.SSHClient.Close()\n\t\tc.SSHClient = nil\n\t}\n}", "func (cl *Client) Close(fh *FileHandle) (err error) {\n\tif fh == nil {\n\t\treturn nil\n\t}\n\tvar (\n\t\tlogp = \"Close\"\n\t\treq = cl.generatePacket()\n\t\tpayload = req.fxpClose(fh)\n\t)\n\n\tres, err := cl.send(payload)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %w\", logp, err)\n\t}\n\tif res.kind != packetKindFxpStatus {\n\t\treturn errUnexpectedResponse(packetKindFxpStatus, res.kind)\n\t}\n\tif res.code != statusCodeOK {\n\t\treturn handleStatusCode(res.code, res.message)\n\t}\n\n\treturn nil\n}", "func (ci *ConnectionInfo) NotifyWhenClose(f func()) {\n\tci.Lock()\n\n\tif ci.closed {\n\t\tci.Unlock()\n\t\tf()\n\t\treturn\n\t}\n\n\tci.closeNotify = append(ci.closeNotify, f)\n\tci.Unlock()\n}", "func (h *HealthCheck) Close() {\n\th.metricTicker.Stop()\n}", "func (bs *Listener) Close() {\n\tbs.mu.Lock()\n\n\tif bs.isClosed {\n\t\tbs.mu.Unlock()\n\t\treturn\n\t}\n\n\tclose(bs.newDataNotifications)\n\tbs.isClosed = true\n\n\tbs.mu.Unlock()\n}", "func (c *Client) Close() {\n\tc.httpClient.CloseIdleConnections()\n}", "func (c *Client) Close(_ context.Context) error {\n\t// Cancel the background goroutines,\n\t// and wait for them to finish\n\t// before closing the socket.\n\tc.cancel()\n\tpollError := <-c.pollError\n\tpingError := <-c.pingError\n\tcloseError := c.webSock.Close()\n\n\tswitch {\n\tcase closeError != nil:\n\t\treturn closeError\n\tcase pollError != nil:\n\t\treturn pollError\n\tcase pingError != nil:\n\t\treturn pingError\n\tdefault:\n\t\treturn nil\n\t}\n}", "func (s *Server) Close() error {\n\treturn s.httpSrv.Close()\n}", "func (f *Forward) Close() { f.OnShutdown() }", "func (cli *OpsGenieAlertV2Client) Close(req alertsv2.CloseRequest) (*AsyncRequestResponse, error) {\n\treturn cli.sendAsyncPostRequest(&req)\n}", "func (f *HTTPFrontend) Close() {\n\tf.ctxCancel()\n\tf.workerTkr.Stop()\n\tf.workerWg.Wait()\n}", "func (w *Watcher) Close() {\n\tw.eb.Unsubscribe(string(w.Topic), w.ID)\n}", "func (self *AMQPChannel) NotifyClose() chan *amqp.Error {\n\treturn self.channel.NotifyClose(make(chan *amqp.Error))\n}", "func (hc *LegacyHealthCheckImpl) Close() error {\n\thc.mu.Lock()\n\tfor _, th := range hc.addrToHealth {\n\t\tth.cancelFunc()\n\t}\n\thc.addrToHealth = nil\n\t// Release the lock early or a pending checkHealthCheckTimeout\n\t// cannot get a read lock on it.\n\thc.mu.Unlock()\n\n\t// Wait for the checkHealthCheckTimeout Go routine and each Go\n\t// routine per tablet.\n\thc.connsWG.Wait()\n\n\treturn nil\n}", "func (c *client) Close() error { return c.c.Close() }", "func notifyOnShutdown(s *http.Server) {\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\t<-signalChan\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\ts.SetKeepAlivesEnabled(false)\n\ts.Shutdown(ctx)\n\n\tlog.Printf(\"shutting down gracefully\")\n\tos.Exit(0)\n}", "func (c *client) SocketClosed() {\n}", "func (c *FakeZkConn) Close() {\n\tc.invalidateWatchers(zk.ErrClosing)\n\tc.history.addToHistory(\"Close\")\n}", "func (cc *ClientConn) Close() error {\n\terr := errors.New(\"http2: client connection force closed via ClientConn.Close\")\n\tcc.closeForError(err)\n\treturn nil\n}", "func (s *HTTPServer) Close() error {\n\tglog.Infof(\"http server closing\")\n\treturn s.https.Close()\n}", "func (th *telemetryHandle) Close(timeout int) {\n\tif timeout <= 0 {\n\t\ttimeout = defaultTimeout\n\t}\n\n\t// wait for items to be sent otherwise timeout\n\t<-th.client.Channel().Close(time.Duration(timeout) * time.Second)\n\n\t// Remove diganostic message listener\n\tif th.diagListener != nil {\n\t\tth.diagListener.Remove()\n\t\tth.diagListener = nil\n\t}\n}", "func (c *client) Close() {\n\tc.exit <- 1\n}", "func (p *Note) Close() {}", "func quitHttpHandler(writer http.ResponseWriter, response *http.Request) {\n\tdefer shutdown()\n\tsendHttpStatusOk(writer)\n\tsendByeMessageToClient(writer)\n\tprintByeMessageToConsole()\n}", "func quitHttpHandler(writer http.ResponseWriter, response *http.Request) {\n\tdefer shutdown()\n\tsendHttpStatusOk(writer)\n\tsendByeMessageToClient(writer)\n\tprintByeMessageToConsole()\n}", "func (a *Client) Close(params *CloseParams) (*CloseOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewCloseParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"Close\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/predict/close\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &CloseReader{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.(*CloseOK), nil\n\n}", "func (w *HttpWriter) Close() error {\n\tif buf, err := w.buildRequestBody(); err != nil {\n\t\tif err != ErrNoContent {\n\t\t\treturn fmt.Errorf(\"could not close http writer: %v\", err)\n\t\t}\n\t} else {\n\n\t\treq, err := http.NewRequest(w.Method, w.Url, buf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tif w.Auth != \"\" {\n\t\t\treq.Header.Set(\"Authorization\", w.Auth)\n\t\t}\n\n\t\tclient := &http.Client{Transport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}}\n\t\tif _, err := client.Do(req); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tw.reset()\n\treturn nil\n}", "func (policy *manualPollingPolicy) close() {\n}", "func (r NopReporter) Notify(ctx context.Context, err error) {}", "func (t Task) Close() error {\n\tpath := fmt.Sprintf(\"tasks/%d/close\", t.ID)\n\t_, err := makeRequest(http.MethodPost, path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (self *File_Client) Close() {\n\tself.cc.Close()\n}", "func ConnClose(c *tls.Conn,) error", "func (srv *Server) StopNotify() <-chan struct{} {\n return srv.stopc\n}" ]
[ "0.71369374", "0.69510823", "0.6842617", "0.67997015", "0.67796373", "0.6760421", "0.6758504", "0.666461", "0.641242", "0.63343847", "0.5994585", "0.5943047", "0.59304035", "0.5919809", "0.5905144", "0.5892296", "0.5802287", "0.56952953", "0.5690403", "0.56514496", "0.5640458", "0.5640458", "0.563468", "0.55836946", "0.5576761", "0.55455256", "0.55313396", "0.549762", "0.549762", "0.5479164", "0.5474359", "0.53809994", "0.53546566", "0.53259945", "0.53104913", "0.52904296", "0.52900624", "0.5282993", "0.5281552", "0.5276919", "0.5276346", "0.5268225", "0.52546674", "0.52546585", "0.5243536", "0.5243294", "0.51999056", "0.5184743", "0.51723456", "0.5141493", "0.5126524", "0.5117735", "0.50999045", "0.5090145", "0.508315", "0.5073357", "0.50721776", "0.5062981", "0.50559396", "0.5044956", "0.5043181", "0.5036471", "0.5036471", "0.5036471", "0.5036471", "0.5034601", "0.50329846", "0.50312936", "0.50224143", "0.50180733", "0.50146705", "0.5002834", "0.49987715", "0.4987349", "0.49830788", "0.4975065", "0.49730873", "0.49703628", "0.49644345", "0.4956194", "0.49547914", "0.49483496", "0.4940837", "0.49402183", "0.49353924", "0.4931745", "0.49303675", "0.49242675", "0.4923919", "0.4923919", "0.49229473", "0.49197182", "0.49179393", "0.49173766", "0.49148142", "0.49134526", "0.49126142", "0.49099028" ]
0.6749032
9
Flush implements the http.Flush interface.
func (w *responseWriter) Flush() { w.WriteHeaderNow() w.ResponseWriter.(http.Flusher).Flush() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *mockHTTPWriter) Flush() {}", "func (b *BodyWriter) Flush() {}", "func (b *httpBatch) Flush() error {\n\treturn nil\n}", "func (p *ProxyWriter) Flush() {\n\tif f, ok := p.W.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n}", "func (resp *response) Flush() {\n\tresp.ResponseWriter.(http.Flusher).Flush()\n}", "func (r *response) Flush() {\n\tr.ResponseWriter.(http.Flusher).Flush()\n}", "func (w *ResponseWriter) Flush() {\n\tw.written = append(w.written, w.buffer...)\n\tw.buffer = nil\n}", "func (w *responseWriter) Flush() {\n\tw.ResponseWriter.(http.Flusher).Flush()\n}", "func (handler Handler) Flush(w http.ResponseWriter) {\n\tflusher := w.(http.Flusher)\n\tflusher.Flush()\n}", "func (w *chunkedResponseBody) Flush() os.Error {\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\tw.finalizeChunk()\n\tif w.n > 0 {\n\t\tw.writeBuf()\n\t\tif w.err != nil {\n\t\t\treturn w.err\n\t\t}\n\t}\n\tw.s = 0\n\tw.n = w.ndigit + 2 // length CRLF\n\treturn nil\n}", "func (r *Response) Flush() {\n\tif flusher, ok := r.ResponseWriter.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n}", "func (r *Response) Flush() {\n\tif flusher, ok := r.ResponseWriter.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n}", "func (w *responseWriter) Flush() {\n\tif w, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tw.Flush()\n\t}\n}", "func (w *ResponseWriter) Flush() {\n\tw.Writer.Flush()\n\n\tif flusher, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n}", "func (w *responseWriter) Flush() {\n\tif f, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n}", "func (w *interceptRW) Flush() {\n\tif w, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tw.Flush()\n\t}\n}", "func workaroundFlush(w http.ResponseWriter) {\n\tw.(http.Flusher).Flush()\n}", "func (w *RWWrapper) Flush() {\n\tif w.gz != nil {\n\t\tw.gz.Flush()\n\t}\n\n\tif rw, ok := w.rw.(http.Flusher); ok {\n\t\trw.Flush()\n\t}\n}", "func (w *responseWriter) Flush() {\n\tif flusher, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n}", "func (res *ServerHTTPResponse) flush(ctx context.Context) {\n\tif res.flushed {\n\t\t/* coverage ignore next line */\n\t\tres.contextLogger.Error(ctx,\n\t\t\t\"Flushed a server response multiple times\",\n\t\t\tzap.String(\"path\", res.Request.URL.Path),\n\t\t)\n\t\t/* coverage ignore next line */\n\t\treturn\n\t}\n\n\tres.flushed = true\n\tres.writeHeader(res.pendingStatusCode)\n\tif _, noContent := noContentStatusCodes[res.pendingStatusCode]; !noContent {\n\t\tres.writeBytes(res.pendingBodyBytes)\n\t}\n\tres.finish(ctx)\n}", "func (b *Writer) Flush() (err error)", "func (r *responseInfoRecorder) Flush() {\n\tif f, ok := r.ResponseWriter.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n}", "func (c *Client) Flush() error {\n\treturn nil\n}", "func (c *Client) Flush() error {\n\treturn nil\n}", "func (w *statusInterceptor) Flush(code int) {\n\tm := w.Header()\n\tfor k, v := range w.headers {\n\t\tm[k] = v\n\t\tdelete(w.headers, k)\n\t}\n\tw.ResponseWriter.WriteHeader(code)\n\tw.ResponseWriter.Write(w.body.Bytes())\n\tw.body.Reset()\n}", "func (w *WithCodeResponseWriter) Flush() {\n\tif flusher, ok := w.Writer.(http.Flusher); ok {\n\t\tflusher.Flush()\n\t}\n}", "func (g *GzipResponse) Flush() {\n\tif g.gw != nil {\n\t\t_ = g.gw.Flush()\n\t}\n\n\tg.r.Flush()\n}", "func (c *Conn) Flush() error {\n\treturn c.w.Flush()\n}", "func (r *ResponseStatusRecorder) Flush() {\n\tif r.flusher != nil {\n\t\tr.flusher.Flush()\n\t}\n}", "func (io *Io) Flush() {\n\tio.writer.Flush()\n}", "func (t *HTTPSyncTransport) Flush(_ time.Duration) bool {\n\treturn true\n}", "func (stream *Stream) Flush() error {\n\tif stream.err != nil {\n\t\treturn stream.err\n\t}\n\n\tbuf := stream.buf\n\tif len(buf) > 0 {\n\t\t_, err := stream.w.Write(buf)\n\t\t// Reset buf.\n\t\tstream.buf = buf[:0]\n\t\tif err != nil {\n\t\t\tstream.err = err\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Conn) Flush() error {\n\treturn c.flush(nil)\n}", "func (w *streamWriter) Flush() error {\n\tw.h.init(w.recType, w.c.reqID, w.buf.Len()-8)\n\tw.writeHeader()\n\tw.buf.Write(pad[:w.h.PaddingLength])\n\t_, err := w.buf.WriteTo(w.c.rwc)\n\treturn err\n}", "func (w *Writer) Flush() error {\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\tif w.Timeout != nil {\n\t\terr := w.Timeout(true)\n\t\tif err != nil {\n\t\t\tw.setError(err)\n\t\t\treturn err\n\t\t}\n\t\tdefer w.Timeout(false)\n\t}\n\terr := w.bw.Flush()\n\tif err != nil {\n\t\tw.setError(err)\n\t\treturn err\n\t}\n\tif !w.zlibOn {\n\t\treturn nil\n\t}\n\terr = w.zlibW.Flush()\n\tif err != nil {\n\t\tw.setError(err)\n\t}\n\treturn err\n}", "func (z *Writer) Flush() error {\n\tif err := z.checkError(); err != nil {\n\t\treturn err\n\t}\n\tif z.closed {\n\t\treturn nil\n\t}\n\tif !z.wroteHeader {\n\t\t_, err := z.Write(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// We send current block to compression\n\tz.compressCurrent(true)\n\n\treturn z.checkError()\n}", "func (c *Connect) Flush() error {\n\tline, err := c.writeReadLine(c.rw, \"flush_all \\r\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif bytes.Equal(line, resultOK) {\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(string(line))\n}", "func (w *Writer) Flush() error {\n\t_, err := w.write(nil, true)\n\treturn err\n}", "func (w *Writer) Flush() error {\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\tif len(w.ibuf) == 0 {\n\t\treturn nil\n\t}\n\tw.write(w.ibuf)\n\tw.ibuf = w.ibuf[:0]\n\treturn w.err\n}", "func (rw *ReadWrite) Flush() {\n\trw.w.Flush()\n}", "func (bw *BufWriter) Flush() error {\n\tif bw.Error != nil {\n\t\treturn bw.Error\n\t}\n\tbw.Error = bw.writer.Flush()\n\treturn bw.Error\n}", "func (e ElasticSearch) Flush() {\n\te.client.Flush().\n\t\tIndex(e.index).\n\t\tAllowNoIndices(true).\n\t\tIgnoreUnavailable(true).\n\t\tDo()\n}", "func (c *Conn) Flush() error {\n\tif c.FlushMock != nil {\n\t\treturn c.FlushMock()\n\t}\n\n\tif len(c.queue) > 0 {\n\t\tfor _, cmd := range c.queue {\n\t\t\treply, err := c.do(cmd.commandName, cmd.args...)\n\t\t\tc.replies = append(c.replies, replyElement{reply: reply, err: err})\n\t\t}\n\t\tc.queue = []queueElement{}\n\t}\n\n\treturn nil\n}", "func (chunker *Chunker) Flush() {\n\tchunker.OutputStream.Flush()\n\tchunker.WriteChunk(blobName(path.Base(chunker.Location), chunker.Index), chunker.OutputStream.Output.Bytes())\n\t// Set size and reset Output stream buffer\n\tchunker.OutputStream.Output.Reset()\n}", "func (w *gzipResponseWriter) Flush() {\n\tif w.gw == nil && w.bw == nil && !w.ignore {\n\t\t// Only flush once startGzip, startBrotli or startPlain has been called.\n\t\t//\n\t\t// Flush is thus a no-op until we're certain whether a plain\n\t\t// or compressed response will be served.\n\t\treturn\n\t}\n\n\tif w.gw != nil {\n\t\tw.gw.Flush()\n\t} else if w.bw != nil {\n\t\tw.bw.Flush()\n\t}\n\n\tif fw, ok := w.ResponseWriter.(http.Flusher); ok {\n\t\tfw.Flush()\n\t}\n}", "func (bm *BucketManager) Flush(name string) error {\n\treq := &gocbcore.HttpRequest{\n\t\tService: gocbcore.ServiceType(MgmtService),\n\t\tPath: fmt.Sprintf(\"/pools/default/buckets/%s/controller/doFlush\", name),\n\t\tMethod: \"POST\",\n\t}\n\n\tresp, err := bm.httpClient.DoHttpRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\tdata, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = resp.Body.Close()\n\t\tif err != nil {\n\t\t\tlogDebugf(\"Failed to close socket (%s)\", err)\n\t\t}\n\t\treturn networkError{statusCode: resp.StatusCode, message: string(data)}\n\t}\n\treturn nil\n}", "func (w *ServiceWriter) Flush() {\n\tif !w.updated {\n\t\treturn\n\t}\n\tw.updated = false\n\n\tserviceBuffer := w.serviceBuffer\n\n\tlog.Debugf(\"going to flush updated service metadata, %d services\", len(serviceBuffer))\n\tatomic.StoreInt64(&w.stats.Services, int64(len(serviceBuffer)))\n\n\tdata, err := model.EncodeServicesPayload(serviceBuffer)\n\tif err != nil {\n\t\tlog.Errorf(\"encoding issue: %v\", err)\n\t\treturn\n\t}\n\n\theaders := map[string]string{\n\t\tlanguageHeaderKey: strings.Join(info.Languages(), \"|\"),\n\t\t\"Content-Type\": \"application/json\",\n\t}\n\n\tatomic.AddInt64(&w.stats.Bytes, int64(len(data)))\n\n\tstartFlush := time.Now()\n\n\t// Send the payload to the endpoint\n\terr = w.endpoint.Write(data, headers)\n\n\tflushTime := time.Since(startFlush)\n\n\t// TODO: if error, depending on why, replay later.\n\tif err != nil {\n\t\tatomic.AddInt64(&w.stats.Errors, 1)\n\t\tlog.Errorf(\"failed to flush service payload, time:%s, size:%d bytes, error: %s\", flushTime, len(data), err)\n\t\treturn\n\t}\n\n\tlog.Infof(\"flushed service payload to the API, time:%s, size:%d bytes\", flushTime, len(data))\n\tstatsd.Client.Gauge(\"datadog.trace_agent.service_writer.flush_duration\", flushTime.Seconds(), nil, 1)\n\tatomic.AddInt64(&w.stats.Payloads, 1)\n}", "func Flush() {\n\tsentry.Flush(3 * time.Second)\n}", "func (c *Client) Flush(filename string) error {\n\t_, err := c.ExecCmd(NewCmd(\"flush\").WithArgs(filename))\n\treturn err\n}", "func (connection *Connection) Flush() error {\n\t//TODO\n}", "func Flush() {\n\tlogger.flush()\n}", "func (redactor *Redactor) Flush() error {\n\t_, err := redactor.output.Write(redactor.outbuf)\n\tredactor.outbuf = redactor.outbuf[:0]\n\treturn err\n}", "func (conn *Conn) Flush() error {\n\treturn conn.brw.Flush()\n}", "func (c *captureClient) Flush() error {\n\tlog.Infof(\"Successfully wrote %d metrics to %q\", c.lines, c.f.Name())\n\treturn c.f.Close()\n}", "func (f *Filter) Flush() error {\n\treturn f.sendCommand(\"flush\")\n}", "func (h *Host) Flush(d time.Duration) {\n\tif h.W == nil || h.W.Buffered() == 0 {\n\t\treturn\n\t}\n\terr := h.W.Flush()\n\tif err != nil {\n\t\th.Lg.Error(\"error while flushing the host buffer\", zap.Error(err), zap.String(\"host name\", h.Name), zap.Uint16(\"host port\", h.Port))\n\t\t// if flushing fails, the connection has to be re-established\n\t\th.Conn = nil\n\t\th.W = nil\n\t}\n}", "func (c *TCPClient) Flush() error {\n\tc.metrics.flush.Inc(1)\n\treturn c.writerMgr.Flush()\n}", "func (w *Writer) Flush() error {\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\t_, w.err = w.w.Write(w.b)\n\tif cap(w.b) > maxBufferCap || w.err != nil {\n\t\tw.b = nil\n\t} else {\n\t\tw.b = w.b[:0]\n\t}\n\treturn w.err\n}", "func (w *Writer) Flush() error {\n\tif w.count != 8 {\n\t\t_, err := w.w.Write(w.b[:])\n\t\treturn err\n\t}\n\treturn nil\n}", "func (b *Writer) Flush() error {\n\tif b.err != nil {\n\t\treturn b.err\n\t}\n\tif b.n == 0 {\n\t\treturn nil\n\t}\n\t// 将buf中的内容写入到实际的io.Writer\n\tn, err := b.wr.Write(b.buf[0:b.n])\n\tif n < b.n && err == nil {\n\t\terr = io.ErrShortWrite\n\t}\n\tif err != nil {\n\t\tif n > 0 && n < b.n {\n\t\t\tcopy(b.buf[0:b.n-n], b.buf[n:b.n])\n\t\t}\n\t\tb.n -= n\n\t\tb.err = err\n\t\treturn err\n\t}\n\tb.n = 0\n\treturn nil\n}", "func (t *HTTPTransport) Flush(timeout time.Duration) bool {\n\ttoolate := time.After(timeout)\n\n\t// Wait until processing the current batch has started or the timeout.\n\t//\n\t// We must wait until the worker has seen the current batch, because it is\n\t// the only way b.done will be closed. If we do not wait, there is a\n\t// possible execution flow in which b.done is never closed, and the only way\n\t// out of Flush would be waiting for the timeout, which is undesired.\n\tvar b batch\n\tfor {\n\t\tselect {\n\t\tcase b = <-t.buffer:\n\t\t\tselect {\n\t\t\tcase <-b.started:\n\t\t\t\tgoto started\n\t\t\tdefault:\n\t\t\t\tt.buffer <- b\n\t\t\t}\n\t\tcase <-toolate:\n\t\t\tgoto fail\n\t\t}\n\t}\n\nstarted:\n\t// Signal that there won't be any more items in this batch, so that the\n\t// worker inner loop can end.\n\tclose(b.items)\n\t// Start a new batch for subsequent events.\n\tt.buffer <- batch{\n\t\titems: make(chan *http.Request, t.BufferSize),\n\t\tstarted: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t}\n\n\t// Wait until the current batch is done or the timeout.\n\tselect {\n\tcase <-b.done:\n\t\tLogger.Println(\"Buffer flushed successfully.\")\n\t\treturn true\n\tcase <-toolate:\n\t\tgoto fail\n\t}\n\nfail:\n\tLogger.Println(\"Buffer flushing reached the timeout.\")\n\treturn false\n}", "func (c *conn) Flush() error {\n\treturn c.writer.Flush()\n}", "func (h *Handler) Flush() {\n\th.q.Wait()\n}", "func (us *awsStream) Flush() (err error) {\n\tlog.Printf(\"Finalizing... %s\", *us.multipart.Key)\n\tlog.Printf(\"Flushing gzip stream... %s\", *us.multipart.Key)\n\tif err = us.gzw.Flush(); err != nil {\n\t\tlog.Print(\"failed to Flush gzip stream\")\n\t\treturn\n\t}\n\tlog.Printf(\"Closing gzip stream... %s\", *us.multipart.Key)\n\tif err = us.gzw.Close(); err != nil {\n\t\tlog.Print(\"failed to Flush gzip stream\")\n\t\treturn\n\t}\n\tpayload := make([]byte, us.buf.Len())\n\tlog.Printf(\"Getting gzip footer... %s\", *us.multipart.Key)\n\tif _, err = us.buf.Read(payload); err != nil {\n\t\tlog.Print(\"failed to get gzip footer payload\")\n\t\treturn\n\t}\n\tlog.Print(\"Uploading gzip footer...\")\n\tif err = us.uploadPart(payload); err != nil {\n\t\tlog.Print(\"failed to upload gzip footer payload\")\n\t\treturn\n\t}\n\tlog.Printf(\"Completing multipart upload... %s\", *us.multipart.Key)\n\tres, err := us.completeMultipartUpload()\n\tif err != nil {\n\t\tlog.Print(utils.Concat(\"Error completing upload of\", *us.multipart.Key, \" due to error: \", err.Error()))\n\t\terr = us.abortMultipartUpload()\n\t\tif err != nil {\n\t\t\tlog.Print(utils.Concat(\"Error aborting uploaded file: \", err.Error()))\n\t\t} else {\n\t\t\tlog.Print(utils.Concat(\"Upload aborted:\", *us.multipart.Key))\n\t\t}\n\t\treturn\n\t}\n\tlog.Print(utils.Concat(\"Successfully uploaded file:\", res.String()))\n\tlog.Printf(\"awsStream flushed successfully %s\", *us.multipart.Key)\n\treturn\n}", "func (writer *Writer) Flush() {\n\twriter.BufWriter.Flush()\n}", "func (w *Writer) Flush() error {\n\treturn w.w.Flush()\n}", "func (z *Writer) Flush() error {\n\tif debugFlag {\n\t\tdebug(\"flush with index %d\", z.idx)\n\t}\n\tif z.idx == 0 {\n\t\treturn nil\n\t}\n\n\tdata := getBuffer(z.Header.BlockMaxSize)[:len(z.data[:z.idx])]\n\tcopy(data, z.data[:z.idx])\n\n\tz.idx = 0\n\tif z.c == nil {\n\t\treturn z.compressBlock(data)\n\t}\n\tif !z.NoChecksum {\n\t\t_, _ = z.checksum.Write(data)\n\t}\n\tc := make(chan zResult)\n\tz.c <- c\n\twriterCompressBlock(c, z.Header, data)\n\treturn nil\n}", "func (client *LDClient) Flush() {\n\tclient.eventProcessor.Flush()\n}", "func (w *writer) Flush() error {\n\treturn w.flusher.Flush()\n}", "func (c *HTTPCollector) flush(b []*zipkincore.Span) (err error) {\n\tdefer func() {\n\t\tc.batchPool.Put(b[:0])\n\t\tif err != nil {\n\t\t\tc.logger.Log(\"err\", err)\n\t\t}\n\t}()\n\n\t// Do not send an empty batch\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tdata, err := httpSerialize(b)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar req *http.Request\n\n\treq, err = http.NewRequest(\"POST\", c.url, data)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/x-thrift\")\n\tif _, err = c.client.Do(req); err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}", "func (l *MockLogger) Flush() {}", "func (c *Concentrator) Flush(force bool) *pb.StatsPayload {\n\treturn c.flushNow(time.Now().UnixNano(), force)\n}", "func (w *Writer) Flush() error {\n\tif w.buf.Len() == 0 {\n\t\treturn nil\n\t}\n\n\tif err := w.clearLines(); err != nil {\n\t\treturn err\n\t}\n\tw.lines = countLines(w.buf.String())\n\n\tif _, err := w.w.Write(w.buf.Bytes()); err != nil {\n\t\treturn err\n\t}\n\n\tw.buf.Reset()\n\treturn nil\n}", "func (bw *BlockWriter) Flush() error {\n\tif bw.stream != nil {\n\t\treturn bw.stream.flush(true)\n\t}\n\n\treturn nil\n}", "func (this *LocalFileWriter) Flush() error {\n\tglog.V(logging.LogLevelDebug).Infof(\"Flush writer for %s\", this.filename)\n\n\t// If a write stream is still open, close the block.\n\tif this.writeStream != nil {\n\t\tresponse, err := this.writeStream.CloseAndRecv()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tblockId := response.BlockId\n\t\tpvId := response.VolumeId\n\n\t\tblockMetadata := &nameservice.BlockMetadata{\n\t\t\tBlockId: blockId,\n\t\t\tPvId: pvId,\n\t\t}\n\n\t\tthis.blockList = append(this.blockList, blockMetadata)\n\t\tthis.writeStream = nil\n\n\t\tglog.V(logging.LogLevelTrace).Infof(\"Received block writer response: %v blockMetadata: %v\", response, blockMetadata)\n\t}\n\n\treturn nil\n}", "func (w *Writer) Flush() error {\n\treturn w.writer.Flush()\n}", "func (d *Object) flush() {\n\n\td.buf.Pos = offsetFieldCount\n\td.buf.WriteUint16(d.fieldCount)\n\n\td.buf.Pos = offsetSize\n\td.buf.WriteUint24(d.size)\n}", "func (iter *Iterator) Flush() error { return iter.impl.Flush() }", "func (ab *AutoflushBuffer) Flush(ctx context.Context) {\n\tab.Lock()\n\tdefer ab.Unlock()\n\tab.flushUnsafe(ctx, ab.Contents.Drain())\n}", "func (w *batchWriter) Flush(ctx context.Context) error {\n\tfor i, s := range w.batch {\n\t\t_, err := fmt.Fprintln(w.writer, s)\n\t\tif err != nil {\n\t\t\tw.batch = w.batch[i:]\n\t\t\tw.persistRecords = w.persistRecords[i:]\n\t\t\treturn err\n\t\t}\n\t\tw.flushed = w.persistRecords[i]\n\t}\n\tw.batch = make([]string, 0, batchSize)\n\tw.persistRecords = make([]*persistRecord, 0, batchSize)\n\treturn nil\n}", "func Flush() {\n\tsyscall.Syscall(gpFlush, 0, 0, 0, 0)\n}", "func (f *ClientFD) Flush(ctx context.Context) error {\n\tif !f.client.IsSupported(Flush) {\n\t\t// If Flush is not supported, it probably means that it would be a noop.\n\t\treturn nil\n\t}\n\treq := FlushReq{FD: f.fd}\n\tctx.UninterruptibleSleepStart(false)\n\terr := f.client.SndRcvMessage(Flush, uint32(req.SizeBytes()), req.MarshalUnsafe, NoopUnmarshal, nil)\n\tctx.UninterruptibleSleepFinish(false)\n\treturn err\n}", "func (t TermHandler) Flush() error {\n\ts := t.buf.String()\n\ts = strings.ReplaceAll(s, \"\\r\\n\", \"\\n\")\n\ts = strings.ReplaceAll(s, \"\\r\", \"\\n\")\n\tt.win.Write(\"body\", []byte(s))\n\tt.buf.Reset()\n\treturn nil\n}", "func (w *Writer) Flush() {\n\tif w.available != 8 {\n\t\t_ = w.out.WriteByte(w.cache)\n\t}\n\tw.Reset(w.out)\n}", "func (p *Provider) Flush() error { return nil }", "func (ipset *IPSet) Flush() error {\n\t_, err := ipset.run(\"flush\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (dc *detachedConn) Flush() error {\n\treturn dc.conn.wr.Flush()\n}", "func (w *Writer) Flush() error {\n\tif w.nb > 0 {\n\t\tw.err = fmt.Errorf(\"cpio: missed writing %d bytes\", w.nb)\n\t\treturn w.err\n\t}\n\t_, w.err = w.w.Write(zeroBlock[:w.pad])\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\tw.nb = 0\n\tw.pad = 0\n\treturn w.err\n}", "func (th *telemetryHandle) Flush() {\n\tth.client.Channel().Flush()\n}", "func (b *FlushingBatch) Flush() error {\n\terr := b.index.Batch(b.batch)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.batch = b.index.NewBatch()\n\treturn nil\n}", "func (l *Log) Flush() {\n\tl.flush()\n}", "func (rw ChunkedResponseWriter) Write(p []byte) (nn int, err error) {\n\tnn, err = rw.w.Write(p)\n\trw.w.(http.Flusher).Flush()\n\treturn\n}", "func (_e *MockDataCoord_Expecter) Flush(ctx interface{}, req interface{}) *MockDataCoord_Flush_Call {\n\treturn &MockDataCoord_Flush_Call{Call: _e.mock.On(\"Flush\", ctx, req)}\n}", "func (c *Client) Flush() error {\n\tif len(c.data) > 0 {\n\t\tc.logger.Infof(\"Pushing metrics: %d\", len(c.data))\n\n\t\tinput := &cloudwatch.PutMetricDataInput{\n\t\t\tNamespace: aws.String(c.namespace),\n\t\t\tMetricData: c.data,\n\t\t}\n\n\t\t_, err := c.svc.PutMetricData(input)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.data = nil\n\t}\n\n\treturn nil\n}", "func (w *Writer) Flush(spaceId []byte) (err error) {\n\tif space := w.spaces[string(spaceId)]; space != nil {\n\t\terr = w.writeSpace(space)\n\t}\n\n\treturn\n}", "func (x *Writer) Flush() error {\n\tif x.fifo.Len() > 0 {\n\t\terr := x.emitDataRecord(x.fifo.Next(x.fifo.Len()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (e *Extent) Flush() (err error) {\n\terr = e.file.Sync()\n\treturn\n}", "func (f *FrameWriter) Flush() error {\n\tif f.offset > 0 {\n\t\tn, err := f.w.Write(f.buf[:f.offset])\n\n\t\tif n < f.offset && err == nil {\n\t\t\terr = io.ErrShortWrite\n\t\t}\n\t\tif err != nil {\n\t\t\tif 0 < n && n < f.offset {\n\t\t\t\tcopy(f.buf[0:], f.buf[n:f.offset])\n\t\t\t}\n\t\t\tf.offset -= n\n\t\t\treturn err\n\t\t}\n\t\tf.offset = 0\n\t}\n\treturn nil\n}", "func Flush() {\n\tif printer.Format == FormatJSON {\n\t\tvar b []byte\n\t\tif printer.Single && len(printer.Lines) == 1 {\n\t\t\tb, _ = json.MarshalIndent(printer.Lines[0], \"\", \" \")\n\t\t} else {\n\t\t\tb, _ = json.MarshalIndent(printer.Lines, \"\", \" \")\n\t\t}\n\n\t\tfmt.Fprintln(printer.writer, string(b))\n\t\tprinter.Lines = []interface{}{}\n\t}\n}", "func (mlog *MultiLogger) Flush() {\n\tmlog.Lock()\n\tdefer mlog.Unlock()\n\n\tif mlog.isClosed {\n\t\treturn\n\t}\n\tmlog.qerr <- cmdFlush\n\tmlog.qout <- cmdFlush\n\t<-mlog.flushq\n\t<-mlog.flushq\n}" ]
[ "0.7804822", "0.77415204", "0.75806135", "0.7484612", "0.7451575", "0.7442949", "0.7434191", "0.7376928", "0.7280186", "0.7275494", "0.72015464", "0.72015464", "0.71789104", "0.71663654", "0.7159713", "0.7103418", "0.70785534", "0.70785403", "0.70659363", "0.69853115", "0.6836929", "0.67939776", "0.67622584", "0.67622584", "0.67123437", "0.6708808", "0.6672667", "0.6583624", "0.656565", "0.64696383", "0.6436091", "0.6409652", "0.6401952", "0.6393139", "0.6368398", "0.6367639", "0.6359836", "0.63464576", "0.6346287", "0.63416415", "0.6332256", "0.63219625", "0.63199806", "0.62800217", "0.6262362", "0.6258446", "0.62495846", "0.6249021", "0.6247722", "0.62367755", "0.6211923", "0.61871654", "0.6147859", "0.61259294", "0.61239797", "0.6090731", "0.60887206", "0.6076117", "0.6062793", "0.6060891", "0.60569793", "0.6052062", "0.60301834", "0.60296917", "0.60285974", "0.6027381", "0.60251725", "0.60204434", "0.6018954", "0.6017661", "0.6001041", "0.5989815", "0.5983616", "0.5978266", "0.5959881", "0.5954546", "0.5948779", "0.593207", "0.59287596", "0.59269476", "0.5922149", "0.5905288", "0.59008217", "0.58977276", "0.5891265", "0.5883778", "0.58826053", "0.5874303", "0.5873794", "0.5871049", "0.58665174", "0.585772", "0.5854764", "0.5848555", "0.58416146", "0.5838335", "0.5824206", "0.58227515", "0.5820007", "0.5819612" ]
0.71478975
15
bigramWordByCopy concatenates adjecent pairs of word by reusing the input string and suppressing the allocation.
func bigramWordByCopy(str string) []string { ss := strings.Split(str, " ") // Handle unexpected string input: // ss = "" => []string{""} // ss = "foobar" => []string{"foobar"} if len(ss) <= 1 { return ss } bigram := make([]string, len(ss)-1) for i := 0; i < len(ss)-1; i++ { // Counts the length of primary and secondary words and whitespace // and copy it to the element of slice. bigram[i] = str[:(len(ss[i])+1)+len(ss[i+1])] // Drop the primary word and whitespace. str = str[len(ss[i])+1:] } return bigram }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func bigramWordByConcat(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\tbigram[i] = ss[i] + \" \" + ss[i+1]\n\t}\n\treturn bigram\n}", "func bigramWordByAppend(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tvar tmp string\n\tvar bigram []string\n\tfor i, s := range ss {\n\t\tif i != 0 {\n\t\t\tbigram = append(bigram, strings.Join([]string{tmp, s}, \" \"))\n\t\t}\n\t\ttmp = s\n\t}\n\treturn bigram\n}", "func gostringnocopy(str *byte) string", "func bigramWordByJoin(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\tbigram[i] = strings.Join([]string{ss[i], ss[i+1]}, \" \")\n\t}\n\treturn bigram\n}", "func fastXORWords(dst, a, b []byte) {\n\tdw := *(*[]uintptr)(unsafe.Pointer(&dst))\n\taw := *(*[]uintptr)(unsafe.Pointer(&a))\n\tbw := *(*[]uintptr)(unsafe.Pointer(&b))\n\tn := len(b) / wordSize\n\tfor i := 0; i < n; i++ {\n\t\tdw[i] = aw[i] ^ bw[i]\n\t}\n}", "func (nGramMap NGramMap) CombineDistinctiveNGrams(words []string, maxN int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tfor i := 2; i <= maxN; i++ {\n\t\terr := nGramMap.addDistinctiveNGrams(words, i, distinctiveWords, threshold)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func main() {\n\tdup([]string{\"kelless\", \"keenness\"})\n\tdup([]string{\"abracadabra\", \"allottee\", \"assessee\"})\n}", "func strCopy(dest *[C.MaxTextExtent]C.char, src []byte) {\n\tfor i, c := range src {\n\t\tdest[i] = C.char(c)\n\t}\n\t// This is C, we need to terminate the string!\n\tdest[len(src)] = 0\n}", "func biGramCharByConcat(s string) []string {\n\tr := []rune(strings.Replace(s, \" \", \"\", -1))\n\t// Handle unexpected string input.\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(r) <= 1 {\n\t\treturn []string{string(r)}\n\t}\n\n\tlist := make([]string, len(r)-1)\n\tfor i := 0; i < len(r)-1; i++ {\n\t\tlist[i] = string(r[i : i+2])\n\t}\n\treturn list\n}", "func emitCopy(dst *tokens, offset, length int) {\n\tdst.tokens[dst.n] = matchToken(uint32(length-3), uint32(offset-minOffsetSize))\n\tdst.n++\n}", "func appendString(dst, src []byte, encode bool) []byte {\n\tvar b []byte\n\tif !encode {\n\t\tb = src\n\t} else {\n\t\tb = bytePool.Get().([]byte)\n\t\tb = HuffmanEncode(b[:0], src)\n\t}\n\t// TODO: Encode only if length is lower with the string encoded\n\n\tn := uint64(len(b))\n\tnn := len(dst) - 1 // peek last byte\n\tif nn >= 0 && dst[nn] != 0 {\n\t\tdst = append(dst, 0)\n\t\tnn++\n\t}\n\tdst = appendInt(dst, 7, n)\n\tdst = append(dst, b...)\n\n\tif encode {\n\t\tbytePool.Put(b)\n\t\tdst[nn] |= 128 // setting H bit\n\t}\n\treturn dst\n}", "func (nGramMap NGramMap) addDistinctiveNGrams(words []string, n int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tnGrams, err := createNGrams(words, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, gram := range nGrams {\n\t\tif gram.IsDistinctive(distinctiveWords, threshold) {\n\t\t\tnGramMap[gram.Key()]++\n\t\t}\n\t}\n\treturn nil\n}", "func scramblePassword(scramble, password []byte) (result []byte) {\n\tif len(password) == 0 {\n\t\treturn\n\t}\n\n\t// stage1Hash = SHA1(password)\n\tcrypt := sha1.New()\n\tcrypt.Write(password)\n\tstage1Hash := crypt.Sum(nil)\n\n\t// scrambleHash = SHA1(scramble + SHA1(stage1Hash))\n\t// inner Hash\n\tcrypt.Reset()\n\tcrypt.Write(stage1Hash)\n\tscrambleHash := crypt.Sum(nil)\n\n\t// outer Hash\n\tcrypt.Reset()\n\tcrypt.Write(scramble)\n\tcrypt.Write(scrambleHash)\n\tscrambleHash = crypt.Sum(nil)\n\n\t// token = scrambleHash XOR stage1Hash\n\tresult = make([]byte, 20)\n\tfor i := range result {\n\t\tresult[i] = scrambleHash[i] ^ stage1Hash[i]\n\t}\n\treturn\n}", "func mutate(m message) message {\n\tif len(m) == 0 {\n\t\treturn m\n\t}\n\tn := make(message, len(m))\n\tcopy(n, m)\n\tfor tries := 0; tries < 3; tries++ {\n\t\ti := rand.Intn(len(m))\n\t\tword := m[i]\n\t\tif len(word.original) >= minWordLength {\n\t\t\tn[i] = dictionary.randomSubstituteFor(word)\n\t\t\treturn n\n\t\t}\n\t}\n\treturn n\n}", "func concat(a string, b string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func mergeAlternately(word1 string, word2 string) string {\n\tvar buf bytes.Buffer\n\tfor i := range word1 {\n\t\tbuf.WriteByte(word1[i])\n\t\tif i < len(word2) {\n\t\t\tbuf.WriteByte(word2[i])\n\t\t}\n\t}\n\n\tif len(word1) < len(word2) {\n\t\tbuf.WriteString(word2[len(word1):])\n\t}\n\treturn buf.String()\n}", "func CloneWStringSlice(dst, src []WString) {\n\tfor i := range src {\n\t\tdst[i] = *src[i].Clone()\n\t}\n}", "func WordsToBytes(bank string, words []string, dest []byte) error {\n\twordsAll := GetWords(\"english\")\n\n\t// 2048 words per bank, which is 2^11.\n\tnumWords := (8*len(dest) + 10) / 11\n\tif numWords != len(words) {\n\t\treturn errors.New(Fmt(\"Expected %v words for %v dest bytes\", numWords, len(dest)))\n\t}\n\n\tn2048 := big.NewInt(2048)\n\tnData := big.NewInt(0)\n\tfor i := 0; i < numWords; i++ {\n\t\trem := GetWordIndex(wordsAll, words[numWords-i-1])\n\t\tif rem < 0 {\n\t\t\treturn errors.New(Fmt(\"Unrecognized word %v for bank %v\", words[i], bank))\n\t\t}\n\t\tnRem := big.NewInt(int64(rem))\n\t\tnData.Mul(nData, n2048)\n\t\tnData.Add(nData, nRem)\n\t}\n\tnDataBytes := nData.Bytes()\n\tif len(nDataBytes) > len(dest) {\n\t\treturn errors.New(Fmt(\"Value %v (len=%v) overflows dest len %v\",\n\t\t\tnData, len(nDataBytes), len(dest)))\n\t}\n\tcopy(dest[len(dest)-len(nDataBytes):], nDataBytes)\n\treturn nil\n}", "func (s String) Copy() String {\n\tcopy := make(String)\n\tfor k := range s {\n\t\tcopy[k] = yes\n\t}\n\treturn copy\n}", "func bild() {\n\n root.word = words[0]\n d := 0 \n var( \n tmp ,tmp2 *Node\n )\n\n for i := range words{\n if i == 0 {continue}\n if words[i] == \"\" {continue}\n \n tmp = new(Node)\n (*tmp).word = words[i]\n\n d = dist(root.word, (*tmp).word)\n if d == 0{\n //fmt.Printf(\"problem %s %d\",words[i],i)\n }\n tmp2 = &root\n\n for ;;{\n \n d = dist(((*tmp).word),((*tmp2).word))\n\n if ((*tmp2).child)[d] == nil {\n ((*tmp2).child)[d] = tmp\n break\n } else{\n tmp2 = ((*tmp2).child)[d]\n } \n } \n }\n}", "func addWord(root *TrieNode, word string, idx int) {\n for i := 0; i < len(word); i++ {\n if isPalindrome(word[i:]) {\n root.match[idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n root.nodes[offset] = &TrieNode{idx:-1, match: make(map[int]bool)} \n }\n root = root.nodes[offset]\n }\n root.idx = idx\n root.match[idx] = true // \"\" is the rest of any string, and is also a palindrome.\n}", "func (i *StringIterator) Copy() Object {\n\treturn &StringIterator{v: i.v, i: i.i, l: i.l}\n}", "func (String) Copy(c *compiler.Compiler, item compiler.Expression) (expression compiler.Expression, err error) {\n\texpression = c.NewExpression()\n\texpression.Type = String{}\n\n\texpression.Go.WriteB(item.Go)\n\n\texpression.JS.WriteString(`(' ' + `)\n\texpression.JS.WriteB(item.JS)\n\texpression.JS.WriteString(`).slice(1)`)\n\n\treturn\n}", "func biGramChar(str string) []string {\n\ts := strings.Replace(str, \" \", \"\", -1)\n\n\tif len(str) <= 1 {\n\t\treturn []string{str}\n\t}\n\n\tbigram := make([]string, len(s)-1)\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tbigram[i] = s[i : i+2]\n\t}\n\treturn bigram\n}", "func dupe(src []byte) []byte {\n\td := make([]byte, len(src))\n\tcopy(d, src)\n\treturn d\n}", "func buildPhrases(words []string, ppWords int) {\n dictLength := big.NewInt(int64(len(words)))\n password := \"\"\n for i := 0; i < ppWords; i++ {\n index, err := rand.Int(rand.Reader, dictLength)\n if err != nil {\n fmt.Println(\"Something strange happened\")\n return\n }\n word := []byte(words[index.Uint64()])\n password += ucFirst(toUtf8(word))\n }\n fmt.Printf(\": %-60s - Brute force giving a total of %.1f bit entropy.\\n\", password, math.Log2(float64(58))*float64(len(password)))\n}", "func scramblePassword(scramble []byte, password []byte) []byte {\n\tif len(password) == 0 {\n\t\treturn nil\n\t}\n\n\t// stage1Hash = SHA1(password)\n\tcrypt := sha1.New()\n\tcrypt.Write(password)\n\tstage1 := crypt.Sum(nil)\n\n\t// scrambleHash = SHA1(scramble + SHA1(stage1Hash))\n\t// inner Hash\n\tcrypt.Reset()\n\tcrypt.Write(stage1)\n\thash := crypt.Sum(nil)\n\n\t// outer Hash\n\tcrypt.Reset()\n\tcrypt.Write(scramble)\n\tcrypt.Write(hash)\n\tscramble = crypt.Sum(nil)\n\n\t// token = scrambleHash XOR stage1Hash\n\tfor i := range scramble {\n\t\tscramble[i] ^= stage1[i]\n\t}\n\treturn scramble\n}", "func copyIfNeeded(bd *netBuf, b []byte) []byte {\n\tif bd.pool == -1 && sameUnderlyingStorage(b, bd.buf) {\n\t\treturn b\n\t}\n\tn := make([]byte, len(b))\n\tcopy(n, b)\n\treturn n\n}", "func (a *ArrayObject) concatenateCopies(t *thread, n *IntegerObject) Object {\n\taLen := len(a.Elements)\n\tresult := make([]Object, 0, aLen*n.value)\n\n\tfor i := 0; i < n.value; i++ {\n\t\tresult = append(result, a.Elements...)\n\t}\n\n\treturn t.vm.initArrayObject(result)\n}", "func ConcatCopyPreAllocate(slices [][]byte) []byte {\n\tvar totalLen int\n\tfor _, s := range slices {\n\t\ttotalLen += len(s)\n\t}\n\ttmp := make([]byte, totalLen)\n\tvar i int\n\tfor _, s := range slices {\n\t\ti += copy(tmp[i:], s)\n\t}\n\treturn tmp\n}", "func (ws *Words) Clone() *Words {\n\tif ws.Len() == 0 {\n\t\treturn nil\n\t}\n\twss := make([]*Word, len(ws.words), cap(ws.words))\n\tcopy(wss, ws.words)\n\treturn NewWords(wss)\n}", "func copyQKEKey(o QKEKey) QKEKey {\n\tc := make(QKEKey, len(o))\n\tcopy(c, o)\n\treturn c\n}", "func largestMerge(word1 string, word2 string) string {\n\tvar i, j int\n\tans := make([]byte, 0, len(word1)+len(word2))\n\tfor i < len(word1) && j < len(word2) {\n\t\tcomp := strings.Compare(word1[i:], word2[j:])\n\t\tif comp > 0 {\n\t\t\tans = append(ans, word1[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tans = append(ans, word2[j])\n\t\t\tj++\n\t\t}\n\t}\n\tfor i < len(word1) {\n\t\tans = append(ans, word1[i])\n\t\ti++\n\t}\n\tfor j < len(word2) {\n\t\tans = append(ans, word2[j])\n\t\tj++\n\t}\n\treturn string(ans)\n}", "func (b *Builder) Strcpy(maxCount uint64) {\n\tb.popStackMulti(2)\n\tb.instructions = append(b.instructions, asm.Strcpy{\n\t\tMaxCount: maxCount,\n\t})\n}", "func combine(str1, str2 string) string {\n\tvar res string\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\t//mark the number of same chars\n\tvar sameNum int = 0\n\tfor len1 > 0 && sameNum < len2 {\n\t\tif str1[len1-1] == str2[sameNum] {\n\t\t\tlen1--\n\t\t\tsameNum++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\t//combine str1 and str2\n\tres = str1[0:len1] + str2[sameNum:len2]\n\treturn res\n\n}", "func ConcatWord(a, b uint8) uint16 {\n\treturn (uint16(a) << 8) | uint16(b)\n}", "func BenchmarkShortStrings(b *testing.B) {\n\tenv := setupJVM(nil)\n\tll := int64(0)\n\twords := len(someWords)\n\tfor i := 0; i < b.N; i++ {\n\t\tstr := someWords[rand.Int()%words] + strconv.Itoa(i)\n\t\tobj, err := env.NewStringObject(str)\n\t\tif err == nil {\n\t\t\tenv.DeleteLocalRef(obj)\n\t\t\tll += int64(len(str))\n\t\t} // else why didn't the tests fail...\n\t}\n\n\tb.SetBytes(ll)\n}", "func mapStringStringMergeFrom(dst, src *map[string]string) {\n\tif (src == nil) || (*src == nil) {\n\t\treturn\n\t}\n\n\tif *dst == nil {\n\t\t*dst = make(map[string]string)\n\t}\n\n\tfor key, value := range *src {\n\t\tif _, ok := (*dst)[key]; ok {\n\t\t\t// Such key already exists in dst\n\t\t\tcontinue\n\t\t}\n\n\t\t// No such a key in dst\n\t\t(*dst)[key] = value\n\t}\n}", "func SquashSpaces(bb []byte) []byte {\n\ti := 0\n\tfor i < len(bb) {\n\t\tif unicode.IsSpace(rune(bb[i])) && (i != len(bb)-1) {\n\t\t\tif unicode.IsSpace(rune(bb[i+1])) {\n\t\t\t\tcopy(bb[i:], bb[i+1:])\n\t\t\t\tbb = bb[:len(bb)-1]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ti++\n\t}\n\treturn bb\n}", "func (b *Board) Copy() Board {\n\tb2 := Board{}\n\tfor i := 0; i < Size; i++ {\n\t\tfor j := 0; j < Size; j++ {\n\t\t\tb2.Spaces[i][j] = b.Spaces[i][j]\n\t\t}\n\t}\n\treturn b2\n}", "func (this *CombinationIterator) generate(temp *[]byte, start int) {\n\t// check if we have valid combo\n\tif len(*temp) == this.combinationLength {\n\t\tthis.combinations = append(this.combinations, string(*temp))\n\t}\n\n\t// go through possible characters\n\tfor i := start; i < len(this.characters); i++ {\n\t\t// take character, backtrack, remove\n\t\t*temp = append(*temp, this.characters[i])\n\t\tthis.generate(temp, i+1)\n\t\t*temp = (*temp)[:len(*temp)-1]\n\t}\n}", "func (c *charset) subtract(oth charset) {\n\tr := *c\n\tout := r[:0]\n\tvar allocated bool\nmainLoop:\n\tfor i := 0; i < len(r); i += 2 {\n\t\tlo, hi := r[i], r[i+1]\n\t\tfor len(oth) > 0 && hi >= oth[0] {\n\t\t\tif oth[1] < lo {\n\t\t\t\toth = oth[2:]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif lo < oth[0] {\n\t\t\t\tout = append(out, lo, oth[0]-1)\n\t\t\t}\n\t\t\tlo = oth[1] + 1\n\t\t\tif lo > hi {\n\t\t\t\tcontinue mainLoop\n\t\t\t}\n\t\t\toth = oth[2:]\n\t\t\tif !allocated && len(out) > i {\n\t\t\t\tallocated = true\n\t\t\t\tout = append(charset(nil), out...)\n\t\t\t}\n\t\t}\n\t\tout = append(out, lo, hi)\n\t}\n\t*c = out\n}", "func (a *Alphabet) Clone() *Alphabet {\n\treturn &Alphabet{\n\t\tt: a.t,\n\t\tisUnlimit: a.isUnlimit,\n\t\tletters: []byte(string(a.letters)),\n\t\tpairs: []byte(string(a.pairs)),\n\t\tgap: []byte(string(a.gap)),\n\t\tambiguous: []byte(string(a.ambiguous)),\n\t\tallLetters: []byte(string(a.allLetters)),\n\t\tpairLetters: []byte(string(a.pairLetters)),\n\t}\n\n}", "func generateCutWordMap(words []string) {\n\twordCost = make(map[string]float64)\n\tvar wordLen int\n\tlogLen := math.Log(float64(len(words)))\n\tfor idx, word := range words {\n\t\twordLen = len(word)\n\t\tif wordLen > maxLenWord {\n\t\t\tmaxLenWord = wordLen\n\t\t}\n\t\twordCost[word] = math.Log(logLen * float64(idx+1))\n\t}\n}", "func (b *Board) copy() *Board {\n\tnewBoard := &Board{\n\t\tPlayer1: make([]Square, len(b.Player1)),\n\t\tPlayer2: make([]Square, len(b.Player2)),\n\t\tresult: b.result,\n\t}\n\tfor i := range b.Player1 {\n\t\tnewBoard.Player1[i] = b.Player1[i]\n\t}\n\tfor i := range b.Player2 {\n\t\tnewBoard.Player2[i] = b.Player2[i]\n\t}\n\treturn newBoard\n}", "func BenchmarkVeryLongStrings(b *testing.B) {\n\t// ~8192 bytes (2 pages) @ ~4ch/word => 2048\n\twordsPer := 2048\n\tenv := setupJVM(nil)\n\tll := int64(0)\n\twords := len(someWords)\n\tfor i := 0; i < b.N; i++ {\n\t\tstr := \"\"\n\t\tfor j := 0; j < wordsPer; j++ {\n\t\t\tstr += someWords[rand.Int()%words]\n\t\t}\n\t\tobj, err := env.NewStringObject(str)\n\t\tif err == nil {\n\t\t\tenv.DeleteLocalRef(obj)\n\t\t\tll += int64(len(str))\n\t\t} // else why didn't the tests fail...\n\t}\n\n\tb.SetBytes(ll)\n}", "func (n *bigNumber) mulCopy(x *bigNumber, y *bigNumber) *bigNumber {\n\t//it does not work in place, that why the temporary bigNumber is necessary\n\treturn n.set(new(bigNumber).mul(x, y))\n}", "func andNotASM(dst, a, b *byte, len uint64)", "func (c *Commander) pasteCopy() ([]string, error) {\n\tout, err := exec.Command(\"pbpaste\").Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsplit := strings.Split(string(out), \"\\n\")\n\trm := strings.Split(split[0], \" \")\n\treturn rm[1:5], nil\n}", "func newAltWords(h *RunList, i, j int) interface{} {\n\tcanon := h.At(i).(*wordPair).canon;\n\talts := make([]string, j-i);\n\tk := 0;\n\tfor ; i < j; i++ {\n\t\talts[k] = h.At(i).(*wordPair).alt;\n\t\tk++;\n\t}\n\treturn &AltWords{canon, alts};\n}", "func StringMap(dst *map[string]string, src map[string]string) {\n\tif *dst == nil {\n\t\t*dst = make(map[string]string, len(src))\n\t}\n\tfor k, v := range src {\n\t\t(*dst)[k] = v\n\t}\n}", "func checkScramble(s1 string, s2 string, m map[[2]string]bool) bool {\n if s1==s2 {\n m[[2]string{s1,s2}] = true\n return true\n }\n\n //if len(s1)!=len(s2) || sortString(s1)!=sortString(s2) {\n if !containSameChar(s1, s2) {\n m[[2]string{s1,s2}] = false\n return false\n }\n\n //var n int = len(s1)\n\n if len(s1)==1 && s1!=s2 {\n m[[2]string{s1,s2}] = false\n return false\n }\n\n if val, ok := m[[2]string{s1,s2}]; ok {\n return val\n }\n\n if val, ok := m[[2]string{s1,s2}]; ok {\n return val\n }\n\n var output bool = false\n\n for i:=1;i<len(s1);i++ {\n\n output = \n ((isScramble(s1[:i], s2[:i])&&isScramble(s1[i:], s2[i:])) || \n (isScramble(s1[:i], s2[len(s2)-i:])&&isScramble(s1[i:], s2[:len(s2)-i])))\n \n \n if output {\n break\n }\n }\n\n m[[2]string{s1,s2}] = output\n return output\n\n}", "func allCombinationsToBuildString(s string, vocabulary []string) [][]string {\n\tvar dp [][][]string\n\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tsubString := s[i:nextIndex]\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tif subString == w {\n\t\t\t\t\tfor _, comb := range dp[i] {\n\t\t\t\t\t\tupdatedComb := append(comb, w)\n\t\t\t\t\t\tdp[nextIndex] = append(dp[nextIndex], updatedComb)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func main() {\n\n\tdna1 := \"GAGCCTACTAACGGGAT\"\n\tdna2 := \"CATCGTAATGACGGCCT\"\n\n\tresult, str := hammingDifference(dna1, dna2)\n\tfmt.Println(str, result)\n}", "func stackCopy(s *string, c int, a [size]int) {\n\tprintln(c, s, *s)\n\n\tc++\n\tif c == size {\n\t\treturn\n\t}\n\n\tstackCopy(s, c, a)\n}", "func doubleMetaphoneLimited(word string, maxLen int) (result *metaphoneWord) {\n\tresult = new(metaphoneWord)\n\tresult.original = word\n\tword = strings.ToUpper(word)\n\t// TODO: Strip punctuation\n\tresult.literal = word\n\tprev, skip, last, slavoGermanic := 0, 0, len(word)-1, false\n\ntestSlavoGermanic: for pos, c := range word {\n\t\tswitch c {\n\t\tcase 'C':\n\t\t\tif pos == last || word[pos+1] != 'Z' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 'W', 'K':\n\t\t\tslavoGermanic = true\n\t\t\tbreak testSlavoGermanic\n\t\t}\n\t}\n\n\tword += \" \" // Allow indexing beyond the end\n\tfor pos, c := range word {\n\t\tif c == ' ' {\n\t\t\tbreak\n\t\t}\n\t\tif skip > 0 {\n\t\t\tprev = 0\n\t\t\tskip--\n\t\t\tcontinue\n\t\t}\n\t\tmp, ms := \"\", \"-\"\n\n\t\tswitch c {\n\t\tcase 'A', 'E', 'I', 'O', 'U', 'Y', 'Ü', 'Ä', 'Ö', 'Å', 'É', 'È', 'Ï':\n\t\t\tif pos == 0 {\n\t\t\t\t// Initial vowel\n\t\t\t\tmp = \"A\"\n\t\t\t} else if pos == 1 && prev == 'W' {\n\t\t\t\t// W + vowel at the start of the word\n\t\t\t\tmp, ms = \"A\", \"F\"\n\t\t\t}\n\t\tcase 'B':\n\t\t\tif prev == 'M' && pos > 1 && word[pos-2] == 'U' &&\n\t\t\t\t(pos == last || (word[pos+1] == 'E' &&\n\t\t\t\t\tword[pos+2] == 'R')) {\n\t\t\t\t// e.g. dumb, thumb\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif prev != 'B' {\n\t\t\t\tmp = \"P\"\n\t\t\t}\n\t\tcase 'C':\n\t\t\tif prev == 'X' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif pos == 0 && strings.HasPrefix(word, \"CAESAR\") {\n\t\t\t\tmp = \"S\"\n\t\t\t\tskip = 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnext := word[pos+1]\n\t\t\tif next == 'H' {\n\t\t\t\tskip = 1\n\t\t\t\tn2, n3 := word[pos+2], word[pos+3]\n\t\t\t\tif pos > 0 {\n\t\t\t\t\tif n2 == 'A' && n3 == 'E' {\n\t\t\t\t\t\t// michael\n\t\t\t\t\t\tmp, ms = \"K\", \"X\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif (pos == 1 && (prev == 'M' || prev == 'S')) ||\n\t\t\t\t\t\tn2 == 'T' || n2 == 'S' {\n\t\t\t\t\t\t// Mc, Sch, -cht, -chs\n\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif (prev == 'A' || prev == 'O' || prev == 'U' ||\n\t\t\t\t\t\tprev == 'E') && (n2 == 'L' || n2 == 'R' || n2 == 'N' ||\n\t\t\t\t\t\tn2 == 'M' || n2 == 'B' || n2 == 'B' ||\n\t\t\t\t\t\tn2 == 'H' || n2 == 'F' || n2 == 'V' ||\n\t\t\t\t\t\tn2 == 'W') {\n\t\t\t\t\t\t// e.g. wachtler, wechsler, but not tichner\n\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif pos > 1 {\n\t\t\t\t\t\tp2 := word[pos-2]\n\t\t\t\t\t\tif prev == 'R' &&\n\t\t\t\t\t\t\t((p2 == 'O' && n2 == 'E' && n3 == 'S') ||\n\t\t\t\t\t\t\t\t(p2 == 'O' && n2 == 'I' && n3 == 'D') ||\n\t\t\t\t\t\t\t\t(p2 == 'A' && n2 == 'I' && n3 == 'T')) {\n\t\t\t\t\t\t\t// orchestra, orchid, architect (but not arch)\n\t\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// pos == 0\n\t\t\t\t\tn4, n5 := word[pos+4], word[pos+5]\n\t\t\t\t\tif (n2 == 'A' && n3 == 'R' && ((n4 == 'A' && n5 == 'C') ||\n\t\t\t\t\t\t(n4 == 'I' && n5 == 'S'))) ||\n\t\t\t\t\t\t(n2 == 'E' && n3 == 'M') || (n2 == 'Y' && n3 == 'M') ||\n\t\t\t\t\t\t(n2 == 'I' && n3 == 'A') ||\n\t\t\t\t\t\t(n2 == 'O' && n3 == 'R' && (n4 != 'O' || n5 != 'E')) {\n\t\t\t\t\t\t// e.g. character, charisma, chorus, chemistry\n\t\t\t\t\t\t// but not \"chore\"\n\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tswitch n2 {\n\t\t\t\t\t\tcase 'L', 'R', 'N', 'M', 'B', 'H', 'F', 'V', 'W', ' ':\n\t\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tmp = \"X\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmp, ms = \"X\", \"K\"\n\t\t\t\tbreak\n\t\t\t} else if next == 'Z' {\n\t\t\t\tif pos < 2 || word[pos-1] != 'I' || word[pos-2] == 'W' {\n\t\t\t\t\t// cz, not wicz\n\t\t\t\t\tmp, ms = \"S\", \"X\"\n\t\t\t\t\tskip = 1\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else if next == 'C' {\n\t\t\t\tn2 := word[pos+2]\n\t\t\t\tif n2 == 'I' && word[pos+3] == 'A' {\n\t\t\t\t\t// -ccia, e.g. focaccia\n\t\t\t\t\tmp = \"X\"\n\t\t\t\t\tskip = 2\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif pos != 2 || prev != 'M' {\n\t\t\t\t\t// -cc, but not e.g. McClellan\n\t\t\t\t\tif n2 == 'I' || n2 == 'E' ||\n\t\t\t\t\t\t(n2 == 'H' && word[pos+3] != 'U') {\n\t\t\t\t\t\t// e.g. bellocchio, but not bacchus\n\t\t\t\t\t\tskip = 3\n\t\t\t\t\t\tif pos == 1 && prev == 'A' {\n\t\t\t\t\t\t\t// e.g. accident\n\t\t\t\t\t\t\tmp = \"KS\"\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t} else if prev == 'U' && n2 == 'E' &&\n\t\t\t\t\t\t\t(word[pos+4] == 'S' || word[pos+4] == 'E') {\n\t\t\t\t\t\t\t// succeed, success\n\t\t\t\t\t\t\tmp = \"KS\"\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmp = \"X\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif n2 != 'I' && n2 != 'E' {\n\t\t\t\t\tskip = 1\n\t\t\t\t}\n\t\t\t} else if next == 'K' || next == 'Q' {\n\t\t\t\tskip = 1\n\t\t\t} else if next == 'I' {\n\t\t\t\tmp = \"S\"\n\t\t\t\tskip = 1\n\t\t\t\tn2 := word[pos+2]\n\t\t\t\tif n2 == 'O' || n2 == 'E' || n2 == 'A' {\n\t\t\t\t\t// cio, cie, cia\n\t\t\t\t\tms = \"X\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t} else if next == 'E' || next == 'Y' {\n\t\t\t\tskip = 1\n\t\t\t\tmp = \"S\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tmp = \"K\"\n\t\tcase 'D':\n\t\t\tif prev != 'D' && prev != 'T' {\n\t\t\t\tif word[pos+1] == 'G' {\n\t\t\t\t\tskip = 1\n\t\t\t\t\tswitch word[pos+2] {\n\t\t\t\t\tcase 'E', 'I', 'Y':\n\t\t\t\t\t\t// e.g. \"edge\"\n\t\t\t\t\t\tmp = \"J\"\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t// e.g. \"edgar\"\n\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmp = \"T\"\n\t\t\t}\n\t\tcase 'F', 'V':\n\t\t\tif prev != c {\n\t\t\t\tmp = \"F\"\n\t\t\t}\n\t\tcase 'G':\n\t\t\tnext := word[pos+1]\n\t\t\tif next == 'H' {\n\t\t\t\tskip = 1\n\t\t\t\tif !isVowel(prev) {\n\t\t\t\t\tmp = \"K\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif pos == 0 {\n\t\t\t\t\tif word[pos+2] == 'I' {\n\t\t\t\t\t\tmp = \"J\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif pos > 1 {\n\t\t\t\t\tif word[pos-2] == 'B' || word[pos-2] == 'H' ||\n\t\t\t\t\t\tword[pos-2] == 'D' {\n\t\t\t\t\t\t// e.g. hugh\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif pos > 2 {\n\t\t\t\t\t\tp3 := word[pos-3]\n\t\t\t\t\t\tif p3 == 'B' || p3 == 'H' || p3 == 'D' {\n\t\t\t\t\t\t\t// e.g. bough\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif pos > 3 && (word[pos-4] == 'B' || word[pos-4] == 'H') {\n\t\t\t\t\t\t\t// e.g. brought\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif prev == 'U' && (p3 == 'C' || p3 == 'G' ||\n\t\t\t\t\t\t\tp3 == 'L' || p3 == 'R' ||\n\t\t\t\t\t\t\tp3 == 'T') {\n\t\t\t\t\t\t\t// e.g. laugh, cough, rough, tough\n\t\t\t\t\t\t\tmp = \"F\"\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif prev != 'I' {\n\t\t\t\t\tmp = \"K\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif next == 'N' {\n\t\t\t\tskip = 1\n\t\t\t\tif !slavoGermanic {\n\t\t\t\t\tif pos == 1 && isVowel(prev) {\n\t\t\t\t\t\tmp, ms = \"KN\", \"N\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else if word[pos+2] != 'E' || word[pos+3] != 'Y' {\n\t\t\t\t\t\t// not e.g. cagney\n\t\t\t\t\t\tmp, ms = \"N\", \"KN\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmp = \"KN\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif next == 'L' {\n\t\t\t\tif word[pos+2] == 'I' && !slavoGermanic {\n\t\t\t\t\t// e.g. tagliaro\n\t\t\t\t\tmp, ms = \"KL\", \"L\"\n\t\t\t\t\tskip = 1\n\t\t\t\t}\n\t\t\t} else if next == 'E' || next == 'I' || next == 'Y' || next == 'G' {\n\t\t\t\tskip = 1\n\t\t\t\tn2 := word[pos+2]\n\t\t\t\tif next != 'G' {\n\t\t\t\t\tif pos == 0 {\n\t\t\t\t\t\tif (next == 'E' && (n2 == 'S' || n2 == 'P' ||\n\t\t\t\t\t\t\tn2 == 'B' || n2 == 'L' ||\n\t\t\t\t\t\t\tn2 == 'Y' || n2 == 'I' ||\n\t\t\t\t\t\t\tn2 == 'R')) || next == 'Y' ||\n\t\t\t\t\t\t\t(next == 'I' && (n2 == 'L' || n2 == 'N')) {\n\t\t\t\t\t\t\tskip = 1\n\t\t\t\t\t\t\tmp, ms = \"K\", \"J\"\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif !(next == 'I' || prev == 'I' || prev == 'E' ||\n\t\t\t\t\t\t(next == 'Y' && (prev == 'R' || prev == 'O')) ||\n\t\t\t\t\t\t(next == 'E' && pos > 0 && word[pos-1] != 'R')) {\n\t\t\t\t\t\t// -ger-, -gy-\n\t\t\t\t\t\tmp = \"K\"\n\t\t\t\t\t\tif !(pos == 3 && next == 'E' &&\n\t\t\t\t\t\t\tstrings.HasPrefix(word, \"DANGER\") ||\n\t\t\t\t\t\t\tstrings.HasPrefix(word, \"RANGER\") ||\n\t\t\t\t\t\t\tstrings.HasPrefix(word, \"MANGER\")) {\n\t\t\t\t\t\t\tms = \"J\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} else if !(n2 == 'I' && (prev == 'A' || prev == 'O')) {\n\t\t\t\t\t// not -aggi -oggi\n\t\t\t\t\tmp = \"K\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif !strings.HasPrefix(word, \"SCH\") ||\n\t\t\t\t\t(next == 'E' && n2 == 'T') {\n\t\t\t\t\t// obvious Germanic\n\t\t\t\t\tmp = \"K\"\n\t\t\t\t} else if next == 'I' && pos == (last-3) &&\n\t\t\t\t\tstrings.HasSuffix(word, \"ER\") {\n\t\t\t\t\t// -gier suffix\n\t\t\t\t\tmp = \"J\"\n\t\t\t\t} else {\n\t\t\t\t\tmp, ms = \"J\", \"K\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tmp = \"K\"\n\t\tcase 'H':\n\t\t\tif pos == 0 || isVowel(prev) {\n\t\t\t\tnext, _ := utf8.DecodeRuneInString(word[pos+1 : len(word)])\n\t\t\t\tif isVowel(next) {\n\t\t\t\t\t// H between two vowels, or at the beginning followed by a vowel\n\t\t\t\t\tmp = \"H\"\n\t\t\t\t\tskip = 1\n\t\t\t\t}\n\t\t\t}\n\t\tcase 'J':\n\t\t\tif prev == 'S' || prev == 'K' || prev == 'L' || prev == 'J' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnext := word[pos+1]\n\t\t\tif pos == 0 {\n\t\t\t\tif next == 'O' && word[pos+2] == 'S' && word[pos+3] == 'E' {\n\t\t\t\t\tif word[pos+4] == ' ' {\n\t\t\t\t\t\t// Jose\n\t\t\t\t\t\tmp = \"H\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmp, ms = \"J\", \"H\"\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmp, ms = \"J\", \"A\"\n\t\t\t} else if !slavoGermanic && isVowel(prev) &&\n\t\t\t\t(next == 'A' || next == 'O') {\n\t\t\t\tmp, ms = \"J\", \"H\"\n\t\t\t} else if pos == last {\n\t\t\t\tmp, ms = \"J\", \"\"\n\t\t\t} else {\n\t\t\t\tswitch next {\n\t\t\t\tcase 'L', 'T', 'K', 'S', 'N', 'M', 'B', 'Z':\n\t\t\t\t\t// NOP\n\t\t\t\tdefault:\n\t\t\t\t\tmp = \"J\"\n\t\t\t\t}\n\t\t\t}\n\t\tcase 'Q', 'K':\n\t\t\tif prev != c && prev != 'C' {\n\t\t\t\tmp = \"K\"\n\t\t\t}\n\t\tcase 'L':\n\t\t\tif word[pos+1] == 'L' {\n\t\t\t\tskip = 1\n\t\t\t\tif pos > 0 && ((word[pos+3] == ' ' &&\n\t\t\t\t\t(((word[pos+2] == 'O' || word[pos+2] == 'A') &&\n\t\t\t\t\t\tword[pos-1] == 'I') || (word[pos+2] == 'E' &&\n\t\t\t\t\t\tword[pos-1] == 'A'))) ||\n\t\t\t\t\t((word[last] == 'S' && (word[last-1] == 'A' ||\n\t\t\t\t\t\tword[last-1] == 'O')) ||\n\t\t\t\t\t\t(word[last] == 'A' || word[last] == 'O') &&\n\t\t\t\t\t\t\t(word[pos-1] == 'A' && word[pos+2] == 'E'))) {\n\t\t\t\t\t// Spanish, -illo, -illa, -alle\n\t\t\t\t\tms = \"\"\n\t\t\t\t}\n\t\t\t}\n\t\t\tmp = \"L\"\n\t\tcase 'M':\n\t\t\tif prev != 'M' {\n\t\t\t\tmp = \"M\"\n\t\t\t}\n\t\tcase 'N':\n\t\t\tif pos == 1 && (prev == 'K' || prev == 'G' || prev == 'P') {\n\t\t\t\t// Skip GN, KN, PN at the start of the word\n\t\t\t\tresult.metaphone, result.secondary = \"\", \"\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 'Ñ':\n\t\t\tif prev != c {\n\t\t\t\tmp = \"N\"\n\t\t\t}\n\t\tcase 'P':\n\t\t\tnext := word[pos+1]\n\t\t\tif next == 'H' {\n\t\t\t\tmp = \"F\"\n\t\t\t\tskip = 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif next == 'S' && pos == 0 {\n\t\t\t\t// Ignore PS at the start of the word\n\t\t\t\tskip = 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif next == 'P' || next == 'B' {\n\t\t\t\tskip = 1\n\t\t\t}\n\t\t\tmp = \"P\"\n\t\t// case 'Q': is grouped with K\n\t\tcase 'R':\n\t\t\tif prev == 'R' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif pos == last && !slavoGermanic && prev == 'E' && pos > 1 &&\n\t\t\t\tword[pos-2] == 'I' && (pos < 4 || word[pos-4] != 'M' ||\n\t\t\t\t!(word[pos-3] == 'E' || word[pos-3] == 'A')) {\n\t\t\t\t// French, e.g. rogier, but not e.g. hochmeier\n\t\t\t\tmp, ms = \"\", \"R\"\n\t\t\t} else {\n\t\t\t\tmp = \"R\"\n\t\t\t}\n\t\tcase 'S', 'ß', 'Š':\n\t\t\tif prev == 'S' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnext := word[pos+1]\n\t\t\tif (prev == 'I' || prev == 'Y') && next == 'L' {\n\t\t\t\t// isl, ysl, e.g. island, isle, carlysle\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif pos == 0 {\n\t\t\t\tif next == 'M' || next == 'N' || next == 'L' || next == 'W' {\n\t\t\t\t\tmp, ms = \"S\", \"X\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif strings.HasPrefix(word, \"SUGAR\") {\n\t\t\t\t\tmp, ms = \"X\", \"S\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif next == 'H' {\n\t\t\t\tif word[pos+2] == 'O' {\n\t\t\t\t\tif (word[pos+3] == 'E' && word[pos+4] == 'K') ||\n\t\t\t\t\t\t(word[pos+3] == 'L' && (word[pos+4] == 'M' ||\n\t\t\t\t\t\t\tword[pos+4] == 'Z')) {\n\t\t\t\t\t\t// holm, holz, hoek\n\t\t\t\t\t\tmp = \"S\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} else if word[pos+2] == 'E' && word[pos+3] == 'I' &&\n\t\t\t\t\tword[pos+4] == 'M' {\n\t\t\t\t\t// heim\n\t\t\t\t\tmp = \"S\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmp = \"X\"\n\t\t\t\tskip = 1\n\t\t\t} else if next == 'I' && (word[pos+2] == 'O' || word[pos+2] == 'A') {\n\t\t\t\t// sio, sia\n\t\t\t\tmp = \"S\"\n\t\t\t\tif !slavoGermanic {\n\t\t\t\t\tms = \"X\"\n\t\t\t\t}\n\t\t\t\tskip = 2\n\t\t\t} else if next == 'Z' {\n\t\t\t\tmp, ms = \"S\", \"X\"\n\t\t\t\tskip = 1\n\t\t\t} else if next == 'C' {\n\t\t\t\tskip = 2\n\t\t\t\tif word[pos+2] == 'H' {\n\t\t\t\t\tn3, n4 := word[pos+3], word[pos+4]\n\t\t\t\t\tif (n3 == 'O' && n4 == 'O') || (n3 == 'U' && n4 == 'Y') ||\n\t\t\t\t\t\t(n3 == 'E' && (n4 == 'D' || n4 == 'M')) {\n\t\t\t\t\t\t// Dutch origin, e.g. \"school\", \"schooner\"\n\t\t\t\t\t\tmp = \"SK\"\n\t\t\t\t\t} else if n3 == 'E' && (n4 == 'R' || n4 == 'N') {\n\t\t\t\t\t\tmp, ms = \"X\", \"SK\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmp = \"X\"\n\t\t\t\t\t\tif pos == 0 && !isVowel(int(word[3])) && word[3] != 'W' {\n\t\t\t\t\t\t\tms = \"S\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if word[pos+2] == 'I' || word[pos+2] == 'E' ||\n\t\t\t\t\tword[pos+2] == 'Y' {\n\t\t\t\t\tmp = \"S\"\n\t\t\t\t} else {\n\t\t\t\t\tmp = \"SK\"\n\t\t\t\t\tskip = 1\n\t\t\t\t\t// TODO: Check correctness of skip\n\t\t\t\t}\n\t\t\t} else if pos == last && prev == 'I' {\n\t\t\t\tif pos > 1 && (word[pos-2] == 'A' || word[pos-2] == 'O') {\n\t\t\t\t\t// French, e.g. artois\n\t\t\t\t\tms = \"S\"\n\t\t\t\t} else {\n\t\t\t\t\tmp = \"S\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmp = \"S\"\n\t\t\t}\n\t\tcase 'T':\n\t\t\tif prev == 'T' {\n\t\t\t\tif word[pos+1] == 'H' {\n\t\t\t\t\t// tth\n\t\t\t\t\tmp, ms = \"0\", \"T\"\n\t\t\t\t\tskip = 1\n\t\t\t\t} else {\n\t\t\t\t\tmp = \"T\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif prev == 'D' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnext := word[pos+1]\n\t\t\tif next == 'I' {\n\t\t\t\tif word[pos+2] == 'A' ||\n\t\t\t\t\t(word[pos+2] == 'O' && word[pos+3] == 'N') {\n\t\t\t\t\t// tia, tion\n\t\t\t\t\tmp = \"X\"\n\t\t\t\t\tskip = 2\n\t\t\t\t}\n\t\t\t} else if next == 'C' && word[pos+2] == 'H' {\n\t\t\t\t// tch\n\t\t\t\tmp = \"X\"\n\t\t\t\tskip = 2\n\t\t\t} else if next == 'H' {\n\t\t\t\tskip = 1\n\t\t\t\tif word[pos+3] == 'M' {\n\t\t\t\t\tif word[pos+2] == 'O' || word[pos+2] == 'A' {\n\t\t\t\t\t\tmp = \"T\"\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmp, ms = \"0\", \"T\"\n\t\t\t} else if next != 'T' {\n\t\t\t\tmp = \"T\"\n\t\t\t}\n\t\t// case 'V': is grouped with F\n\t\tcase 'W':\n\t\t\tnext := word[pos+1]\n\t\t\tif next == 'R' {\n\t\t\t\tif pos != 0 {\n\t\t\t\t\tmp = \"R\"\n\t\t\t\t}\n\t\t\t\tskip = 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif pos == 0 {\n\t\t\t\tif next == 'H' {\n\t\t\t\t\tmp = \"A\"\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (pos == last && isVowel(prev)) ||\n\t\t\t\tstrings.HasPrefix(word, \"SCH\") {\n\t\t\t\tms = \"F\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tn2, n3 := word[pos+2], word[pos+3]\n\t\t\tif (prev == 'E' || prev == 'O') && next == 'S' && n2 == 'K' &&\n\t\t\t\t(n3 == 'I' || n3 == 'Y') {\n\t\t\t\t// -ewski, -ewsky, -owski, -owsky\n\t\t\t\tms = \"F\"\n\t\t\t} else if next == 'I' && n3 == 'Z' && (n2 == 'C' || n2 == 'T') {\n\t\t\t\t// -wicz, -witz\n\t\t\t\tmp, ms = \"TS\", \"FX\"\n\t\t\t\tskip = 3\n\t\t\t}\n\t\tcase 'X':\n\t\t\tif pos == 0 {\n\t\t\t\t// Initial X pronounced like a Z, e.g. Xavier\n\t\t\t\tmp = \"S\"\n\t\t\t} else if prev != 'X' {\n\t\t\t\tif pos == last && prev == 'U' && pos > 1 &&\n\t\t\t\t\t(word[pos-2] == 'A' || word[pos-2] == 'O') {\n\t\t\t\t\t// French, e.g. breaux\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tmp = \"KS\"\n\t\t\t}\n\t\tcase 'Z':\n\t\t\tif prev == 'S' || prev == 'Z' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif word[pos+1] == 'H' {\n\t\t\t\t// Chinese, e.g. Zhao\n\t\t\t\tmp = \"J\"\n\t\t\t\tskip = 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif word[pos+1] == 'I' || word[pos+1] == 'O' || word[pos+1] == 'A' ||\n\t\t\t\t(slavoGermanic && prev != 'T' && pos > 0) {\n\t\t\t\tms = \"TS\"\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 'Ç':\n\t\t\tmp = \"S\"\n\t\tdefault:\n\t\t}\n\t\tprev = c\n\t\tresult.metaphone += mp\n\t\tif ms == \"-\" {\n\t\t\tms = mp\n\t\t}\n\t\tresult.secondary += ms\n\n\t\tif *debugMetaphone {\n\t\t\tfmt.Fprintf(os.Stderr, \"\\t%c -> [%s] [%s]\\n\", c, mp, ms)\n\t\t}\n\n\t\tif len(result.metaphone) >= maxLen && len(result.secondary) >= maxLen {\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(result.metaphone) > maxLen {\n\t\tresult.metaphone = result.metaphone[0:maxLen]\n\t}\n\tif len(result.secondary) > maxLen {\n\t\tresult.secondary = result.secondary[0:maxLen]\n\t}\n\tif result.secondary == result.metaphone {\n\t\tresult.secondary = result.metaphone\n\t}\n\tif *debugMetaphone {\n\t\tfmt.Fprintf(os.Stderr, \"%s: [%s] [%s]\\n\", result.literal, result.metaphone,\n\t\t\tresult.secondary)\n\t}\n\treturn\n}", "func (g AdjacencyList) Copy() (c AdjacencyList, ma int) {\n\tc = make(AdjacencyList, len(g))\n\tfor n, to := range g {\n\t\tc[n] = append([]NI{}, to...)\n\t\tma += len(to)\n\t}\n\treturn\n}", "func Biunigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\tfor unigram := range toUnigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c\", unigram))\n\t}\n\n\treturn tokens\n}", "func Biunigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\tfor unigram := range toUnigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c\", unigram))\n\t}\n\n\treturn tokens\n}", "func MemCopy(dst unsafe.Pointer, src unsafe.Pointer, bytes int) {\n\tfor i := 0; i < bytes; i++ {\n\t\t*(*uint8)(MemAccess(dst, i)) = *(*uint8)(MemAccess(src, i))\n\t}\n}", "func (s Byte) Clone() Byte {\n\tresult := make(Byte, len(s))\n\tfor key := range s {\n\t\tresult.Insert(key)\n\t}\n\treturn result\n}", "func (g LabeledAdjacencyList) Copy() (c LabeledAdjacencyList, ma int) {\n\tc = make(LabeledAdjacencyList, len(g))\n\tfor n, to := range g {\n\t\tc[n] = append([]Half{}, to...)\n\t\tma += len(to)\n\t}\n\treturn\n}", "func CopyBag(b Bag) *MutableBag {\n\tmb := GetMutableBag(nil)\n\tfor _, k := range b.Names() {\n\t\tv, _ := b.Get(k)\n\t\tmb.Set(k, copyValue(v))\n\t}\n\n\treturn mb\n}", "func CopyBag(b Bag) *MutableBag {\n\tmb := GetMutableBag(nil)\n\tfor _, k := range b.Names() {\n\t\tv, _ := b.Get(k)\n\t\tmb.Set(k, copyValue(v))\n\t}\n\n\treturn mb\n}", "func AndInplace(main, arg []byte) {\n\t// This takes ~6-8% longer than AndUnsafeInplace on the short-array benchmark\n\t// on my Mac.\n\tmainLen := len(main)\n\tif len(arg) != mainLen {\n\t\tpanic(\"AndInplace() requires len(arg) == len(main).\")\n\t}\n\tif mainLen < BytesPerWord {\n\t\t// It's probably possible to do better here (e.g. when mainLen is in 4..7,\n\t\t// operate on uint32s), but I won't worry about it unless/until that's\n\t\t// actually a common case.\n\t\tfor pos, argByte := range arg {\n\t\t\tmain[pos] = main[pos] & argByte\n\t\t}\n\t\treturn\n\t}\n\targData := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&arg)).Data)\n\tmainData := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&main)).Data)\n\targWordsIter := argData\n\tmainWordsIter := mainData\n\tif mainLen > 2*BytesPerWord {\n\t\tnWordMinus2 := (mainLen - BytesPerWord - 1) >> Log2BytesPerWord\n\t\tfor widx := 0; widx < nWordMinus2; widx++ {\n\t\t\tmainWord := *((*uintptr)(mainWordsIter))\n\t\t\targWord := *((*uintptr)(argWordsIter))\n\t\t\t*((*uintptr)(mainWordsIter)) = mainWord & argWord\n\t\t\tmainWordsIter = unsafe.Add(mainWordsIter, BytesPerWord)\n\t\t\targWordsIter = unsafe.Add(argWordsIter, BytesPerWord)\n\t\t}\n\t}\n\tmainWord1 := *((*uintptr)(mainWordsIter))\n\targWord1 := *((*uintptr)(argWordsIter))\n\tfinalOffset := uintptr(mainLen - BytesPerWord)\n\tmainFinalWordPtr := unsafe.Add(mainData, finalOffset)\n\targFinalWordPtr := unsafe.Add(argData, finalOffset)\n\tmainWord2 := *((*uintptr)(mainFinalWordPtr))\n\targWord2 := *((*uintptr)(argFinalWordPtr))\n\t*((*uintptr)(mainWordsIter)) = mainWord1 & argWord1\n\t*((*uintptr)(mainFinalWordPtr)) = mainWord2 & argWord2\n}", "func removeDuplicates(s string, k int) string {\n\tstack := make([]ch, 0)\n\tfirstCh := ch{char: s[0], count: 1}\n\tstack = append(stack, firstCh)\n\n\tfor i := 1; i < len(s); i++ {\n\t\tc := s[i]\n\n\t\tvar prev ch\n\t\tif len(stack) > 0 {\n\t\t\tprev = stack[len(stack)-1]\n\t\t}\n\n\t\tif (prev != ch{}) && (prev.char == c) {\n\t\t\tstack = append(stack, ch{\n\t\t\t\tchar: c,\n\t\t\t\tcount: 1 + prev.count,\n\t\t\t})\n\t\t} else {\n\t\t\tstack = append(stack, ch{\n\t\t\t\tchar: c,\n\t\t\t\tcount: 1,\n\t\t\t})\n\t\t}\n\n\t\tif stack[len(stack)-1].count == k {\n\t\t\tfor i := 0; i < k; i++ {\n\t\t\t\tstack = stack[:len(stack)-1]\n\t\t\t}\n\t\t}\n\n\t}\n\n\tres := make([]byte, 0)\n\n\tfor i := 0; i < len(stack); i++ {\n\t\tres = append(res, stack[i].char)\n\t}\n\treturn string(res)\n}", "func BenchmarkLongStrings(b *testing.B) {\n\t// ~2048 bytes (1/2 page) @ ~4ch/word => 512\n\twordsPer := 512\n\tenv := setupJVM(nil)\n\tll := int64(0)\n\twords := len(someWords)\n\tfor i := 0; i < b.N; i++ {\n\t\tstr := \"\"\n\t\tfor j := 0; j < wordsPer; j++ {\n\t\t\tstr += someWords[rand.Int()%words]\n\t\t}\n\t\tobj, err := env.NewStringObject(str)\n\t\tif err == nil {\n\t\t\tenv.DeleteLocalRef(obj)\n\t\t\tll += int64(len(str))\n\t\t} // else why didn't the tests fail...\n\t}\n\n\tb.SetBytes(ll)\n}", "func (a *accessControlAllow) toDeduplicatedString(m map[string]bool) string {\n\tvar newStr string\n\ti := 0\n\tfor str := range m {\n\t\tif i != 0 {\n\t\t\tnewStr += \",\"\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t\tnewStr += str\n\t}\n\treturn newStr\n}", "func Stringinperm(k int, sl []string, s string, mp map[string]bool) error {\n\tif sl == nil || len(sl) == 0 {\n\t\treturn fmt.Errorf(\"Source slice is empty\")\n\t}\n\tif k == 1 {\n\t\tmp[strings.Join(sl, \"\")] = strings.Contains(strings.Join(sl, \"\"), s)\n\t} else {\n\t\tStringinperm(k-1, sl, s, mp)\n\t\tfor i := 0; i < k-1; i++ {\n\t\t\tif k%2 == 0 {\n\t\t\t\tsl[i], sl[k-1] = sl[k-1], sl[i]\n\t\t\t} else {\n\t\t\t\tsl[0], sl[k-1] = sl[k-1], sl[0]\n\t\t\t}\n\t\t\tStringinperm(k-1, sl, s, mp)\n\t\t}\n\t}\n\treturn nil\n\n}", "func (this *WordDictionary) AddWord(word string) {\n\tvar nowChar *WordDictionary = this\n\tvar next *WordDictionary\n\tfor i, char := range word {\n\t\tcharIdx := char - a\n\t\tnext = nowChar.Nexts[charIdx]\n\t\tif next == nil {\n\t\t\twordDict := Constructor()\n\t\t\tnowChar.Nexts[charIdx] = &wordDict\n\t\t\tnext = &wordDict\n\t\t}\n\t\tnowChar = next\n\t\tif i == len(word)-1 {\n\t\t\tnowChar.HasTerminate = true\n\t\t}\n\t}\n}", "func appendRepeatedBytes(dst []byte, repeatedBytes []byte, number int) []byte {\n\tfor number > 0 {\n\t\tn := number\n\t\tif n > len(repeatedBytes) {\n\t\t\tn = len(repeatedBytes)\n\t\t}\n\t\tdst = append(dst, repeatedBytes[:n]...)\n\t\tnumber -= n\n\t}\n\treturn dst\n}", "func BenchmarkGoShortStringsReference(b *testing.B) {\n\tll := int64(0)\n\twords := len(someWords)\n\tfor i := 0; i < b.N; i++ {\n\t\tstr := someWords[rand.Int()%words] + strconv.Itoa(i)\n\t\tll += int64(len(str))\n\t}\n\tb.SetBytes(ll)\n}", "func oneEditAway(str1 string, str2 string) bool {\n\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\tvar smaller, bigger string\n\n\tif math.Abs(float64(len1-len2)) > 1 {\n\t\treturn false\n\t}\n\n\tif len1 < len2 {\n\t\tsmaller = str1\n\t\tbigger = str2\n\t} else {\n\t\tsmaller = str2\n\t\tbigger = str1\n\n\t}\n\n\tvar i, j int\n\tmismatchDone := false\n\n\tfor i < len(smaller) && j < len(bigger) {\n\n\t\tif smaller[i] != bigger[j] {\n\t\t\tif mismatchDone {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tmismatchDone = true\n\t\t\tif len1 == len2 {\n\t\t\t\ti++ //case of replace\n\t\t\t} // else case of replace.dont move small pointer\n\t\t} else {\n\t\t\ti++ //move short pointer if its a match, dont move it in case of first mismatch\n\t\t}\n\t\tj++ //always move long string pointer.\n\t}\n\treturn true\n}", "func AlienDictonary(words []string) {\n\tdict := make(map[string][]string)\n\tfor i := 0; i < len(words); i++ {\n\t\tcurrent := string(words[i])\n\t\tfor j := 0; j < len(current); j++ {\n\t\t\t_, found := dict[string(current[j])]\n\t\t\tif !found {\n\t\t\t\tdict[string(current[j])] = []string{}\n\t\t\t}\n\n\t\t}\n\t}\n\tinEdges := make(map[string]int)\n\tfor key := range dict {\n\t\tinEdges[key] = 0\n\t}\n\tfor i := 1; i < len(words); i++ {\n\t\tfirst := words[i-1]\n\t\tsecond := words[i]\n\t\tl := int(math.Min(float64(len(first)), float64(len(second))))\n\t\tfor j := 0; j < l; j++ {\n\t\t\tif first[j] != second[j] {\n\t\t\t\tdict[string(first[j])] = append(dict[string(first[j])], string(second[j]))\n\t\t\t\tinEdges[string(second[j])]++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tq := []string{}\n\tfor key := range inEdges {\n\t\tif inEdges[key] == 0 {\n\t\t\tq = append(q, key)\n\t\t}\n\t}\n\tans := \"\"\n\tfor len(q) > 0 {\n\t\tremoved := q[0]\n\t\tq = q[1:]\n\t\tans += removed\n\t\tcurrent := dict[removed]\n\t\tfor i := 0; i < len(current); i++ {\n\t\t\tinEdges[string(current[i])]--\n\t\t\tif inEdges[string(current[i])] == 0 {\n\t\t\t\tq = append(q, string(current[i]))\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Println(ans)\n}", "func (a *Graph) copy() *Graph {\n\tthis := &Graph{}\n\tthis.n = a.n\n\tthis.e = a.e\n\tthis.edge = make([]int, this.n*this.n)\n\tfor i, v := range a.edge {\n\t\tthis.edge[i] = v\n\t}\n\treturn this\n}", "func stackCopy(c int, s *string, a [size]int) {\n\tprintln(c, s, *s)\n\n\tc++\n\tif c == 10 {\n\t\treturn\n\t}\n\n\tstackCopy(c, s, a)\n}", "func StringSliceSubstract(a, b []string) []string {\n\taMap := make(map[string]struct{})\n\tfor _, item := range a {\n\t\taMap[item] = struct{}{}\n\t}\n\tfor _, item := range b {\n\t\tdelete(aMap, item)\n\t}\n\tres := make([]string, 0, len(aMap))\n\tfor key := range aMap {\n\t\tres = append(res, key)\n\t}\n\treturn res\n}", "func groupAnagramsOptimal(strs []string) [][]string {\n result := make([][]string, 0)\n\n if len(strs) == 0 {\n return result\n }\n\n tracker := make(map[string][]string)\n\n for _, s := range strs {\n count := make([]int, 26)\n for _, char := range s {\n count[char - 'a']++\n }\n\n sb := \"\"\n for i := 0; i < 26; i++ {\n sb += \"#\"\n sb += string(count[i])\n }\n\n tracker[sb] = append(tracker[sb], s)\n }\n\n for _, val := range tracker {\n result = append(result, val)\n }\n\n return result\n}", "func fillWordsInBlanks(blanks []blank, blankIndex int, wordsMap map[string]bool, crosswordBytes [][]byte) bool {\n\tif blankIndex >= len(blanks) && len(wordsMap) == 0 {\n\t\treturn true\n\t}\n\tif blankIndex >= len(blanks) {\n\t\treturn false\n\t}\n\t//list of all words to be tried out\n\tfor word := range wordsMap {\n\t\tcrosswordBytesCopy := createNewCopy(crosswordBytes)\n\t\t//if word fits in blank\n\t\tif addWordToBlank(blanks[blankIndex], word, crosswordBytesCopy) {\n\t\t\twordsMapCopy := make(map[string]bool)\n\t\t\tcopymap(wordsMapCopy, wordsMap)\n\t\t\t//remove word that fit from future recursive calls\n\t\t\tdelete(wordsMapCopy, word)\n\t\t\t//recursively try to fill remaining words in remaining blanks\n\t\t\tif fillWordsInBlanks(blanks, blankIndex+1, wordsMapCopy, crosswordBytesCopy) {\n\t\t\t\tcopy(crosswordBytes, crosswordBytesCopy)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t//if we faced a problem, act as if this word never fit, move on to other words\n\t\t}\n\t}\n\t// fmt.Println(\"false returned after loop\")\n\treturn false\n}", "func copyStrings(src []string) []string {\n\tif src == nil {\n\t\treturn nil\n\t}\n\tdst := make([]string, len(src))\n\tcopy(dst, src)\n\treturn dst\n}", "func (b *Builder) Copy(size uint64) {\n\tb.popStackMulti(2)\n\tb.instructions = append(b.instructions, asm.Copy{\n\t\tCount: size,\n\t})\n}", "func neighbours(word string, words map[string]int64) []string {\n\tvar adj []string\n\tfor j := range word {\n\t\tfor d := byte('a'); d <= 'z'; d++ {\n\t\t\tb := make([]byte, len(word))\n\t\t\tfor i, c := range []byte(word) {\n\t\t\t\tif i == j {\n\t\t\t\t\tb[i] = d\n\t\t\t\t} else {\n\t\t\t\t\tb[i] = c\n\t\t\t\t}\n\t\t\t}\n\t\t\tw := string(b)\n\t\t\tif w != word {\n\t\t\t\tif _, ok := words[w]; ok {\n\t\t\t\t\t// We have found a neighbouring word so we\n\t\t\t\t\t// can add it to our list of neighbours.\n\t\t\t\t\tadj = append(adj, w)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn adj\n}", "func (jbobject *JavaNioCharBuffer) Duplicate() *JavaNioCharBuffer {\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"duplicate\", \"java/nio/CharBuffer\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tretconv := javabind.NewJavaToGoCallable()\n\tdst := &javabind.Callable{}\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\tunique_x := &JavaNioCharBuffer{}\n\tunique_x.Callable = dst\n\treturn unique_x\n}", "func foldString(maxLength int, prefix, s string) string {\n\tvar foldedBuffer bytes.Buffer\n\tlineBuffer := bytes.NewBufferString(prefix)\n\tlineLength := lineBuffer.Len()\n\n\tfor _, word := range strings.Split(s, \" \") {\n\t\twordLength := len(word)\n\t\tif wordLength+lineLength+1 <= maxLength {\n\t\t\tlineBuffer.WriteString(word)\n\t\t\tlineBuffer.WriteString(\" \")\n\t\t\tlineLength += wordLength + 1\n\t\t} else {\n\t\t\tfoldedBuffer.Write(lineBuffer.Bytes())\n\t\t\tfoldedBuffer.WriteString(\"\\r\\n \")\n\t\t\tlineBuffer.Reset()\n\t\t\tlineBuffer.WriteString(word)\n\t\t\tlineBuffer.WriteString(\" \")\n\t\t\tlineLength = wordLength + 1\n\t\t}\n\t}\n\tfoldedBuffer.Write(lineBuffer.Bytes())\n\tfoldedBuffer.WriteString(\"\\r\\n\")\n\treturn foldedBuffer.String()\n}", "func newBitmapFrom(other *bitmap, size int) *bitmap {\n\tbitmap := newBitmap(size)\n\n\tif size > other.Size {\n\t\tsize = other.Size\n\t}\n\n\tdiv := size / 8\n\n\tfor i := 0; i < div; i++ {\n\t\tbitmap.data[i] = other.data[i]\n\t}\n\n\tfor i := div * 8; i < size; i++ {\n\t\tif other.Bit(i) == 1 {\n\t\t\tbitmap.Set(i)\n\t\t}\n\t}\n\n\treturn bitmap\n}", "func (t *translator) copyBytes(\n\tirBlock *ir.Block, irPtr, irLen irvalue.Value,\n) irvalue.Value {\n\tirNewPtr := irBlock.NewCall(t.builtins.Malloc(t), irLen)\n\tirBlock.NewCall(t.builtins.Memcpy(t), irNewPtr, irPtr, irLen, irconstant.False)\n\treturn irNewPtr\n}", "func (wq *WordQuery) Clone() *WordQuery {\n\tif wq == nil {\n\t\treturn nil\n\t}\n\treturn &WordQuery{\n\t\tconfig: wq.config,\n\t\tlimit: wq.limit,\n\t\toffset: wq.offset,\n\t\torder: append([]OrderFunc{}, wq.order...),\n\t\tunique: append([]string{}, wq.unique...),\n\t\tpredicates: append([]predicate.Word{}, wq.predicates...),\n\t\twithCardLogs: wq.withCardLogs.Clone(),\n\t\twithCardSchedules: wq.withCardSchedules.Clone(),\n\t\t// clone intermediate query.\n\t\tsql: wq.sql.Clone(),\n\t\tpath: wq.path,\n\t}\n}", "func bufApp(buf *[]byte, s string, w int, c byte) {\n\tif *buf == nil {\n\t\tif s[w] == c {\n\t\t\treturn\n\t\t}\n\n\t\t*buf = make([]byte, len(s))\n\t\tcopy(*buf, s[:w])\n\t}\n\t(*buf)[w] = c\n}", "func bufApp(buf *[]byte, s string, w int, c byte) {\n\tif *buf == nil {\n\t\tif s[w] == c {\n\t\t\treturn\n\t\t}\n\n\t\t*buf = make([]byte, len(s))\n\t\tcopy(*buf, s[:w])\n\t}\n\t(*buf)[w] = c\n}", "func CopyAndAppend(s [][]byte, e []byte) [][]byte {\n\tline := make([]byte, len(e))\n\tcopy(line, e)\n\treturn append(s, line)\n}", "func stackCopy(s *string, c int, a [size]int) {\r\n\tprintln(c, s, *s)\r\n\r\n\tc++\r\n\tif c == 10 {\r\n\t\treturn\r\n\t}\r\n\r\n\tstackCopy(s, c, a)\r\n}", "func permutations(w string) []string {\n\tif w == \"\" {\n\t\treturn []string{\" \"}\n\t}\n\tperms := []string{}\n\tfor i, r := range w {\n\t\tremain := w[:i] + w[i+1:]\n\t\t//fmt.Println(remain)\n\t\tfor _, result := range permutations(remain) {\n\t\t\tperms = append(perms, fmt.Sprintf(\"%c\", r)+result)\n\t\t}\n\t\t//perms = append(perms, fmt.Sprintf(\"%c\\n\", r))\n\t}\n\treturn perms\n}", "func groupAnagrams2(strs []string) [][]string {\n\thash := make(map[string]int)\n\tvar result [][]string\n\tkey := make([]rune, 26)\n\tfor _, str := range strs {\n\t\tfor _, r := range str {\n\t\t\tkey[r-'a']++\n\t\t}\n\t\tstrKey := string(key)\n\t\tif index, ok := hash[strKey]; ok {\n\t\t\tresult[index] = append(result[index], str)\n\t\t} else {\n\t\t\thash[strKey] = len(result)\n\t\t\tresult = append(result, []string{str})\n\t\t}\n\t}\n\treturn result\n}", "func copySlice(s []string) []string {\n\tret := make([]string, len(s), (len(s)+1)*2)\n\tcopy(ret, s)\n\treturn ret\n}", "func copyUpToNull(b []byte) (s string) {\n\tfor _, val := range b {\n\t\tif val == 0 {\n\t\t\treturn\n\t\t}\n\t\ts = s + string(val)\n\t}\n\treturn\n}", "func swap(s string, pair []int) string {\n\t// Collect bytes for new string\n\ti, j := pair[0], pair[1]\n\tbytes := []byte{}\n\tfor k := range s {\n\t\tif k == i {\n\t\t\tbytes = append(bytes, s[j])\n\t\t} else if k == j {\n\t\t\tbytes = append(bytes, s[i])\n\t\t} else {\n\t\t\tbytes = append(bytes, s[k])\n\t\t}\n\t}\n\n\t// Build string\n\tbuilder := strings.Builder{}\n\tbuilder.Write(bytes)\n\treturn builder.String()\n}", "func generateAdjectiveNounPair() []string {\n\tvar ret []string\n\treg, err := regexp.Compile(\"[^a-zA-Z]+\")\n\tisError(err)\n\n\tadj := reg.ReplaceAllLiteralString(strings.Title(pickRandomWord(adjectives)), \"\")\n\tnou := reg.ReplaceAllLiteralString(strings.Title(pickRandomWord(nouns)), \"\")\n\tret = append(ret, []string{adj, nou}...)\n\treturn ret\n}", "func (p Prefix) Shift(word string) {\n\tcopy(p, p[1:])\n\tp[len(p)-1] = word\n}", "func (dd *dictDecoder) writeCopy(dist, length int) int {\n\tdstBase := dd.wrPos\n\tdstPos := dstBase\n\tsrcPos := dstPos - dist\n\tendPos := dstPos + length\n\tif endPos > len(dd.hist) {\n\t\tendPos = len(dd.hist)\n\t}\n\n\t// Copy non-overlapping section after destination position.\n\t//\n\t// This section is non-overlapping in that the copy length for this section\n\t// is always less than or equal to the backwards distance. This can occur\n\t// if a distance refers to data that wraps-around in the buffer.\n\t// Thus, a backwards copy is performed here; that is, the exact bytes in\n\t// the source prior to the copy is placed in the destination.\n\tif srcPos < 0 {\n\t\tsrcPos += len(dd.hist)\n\t\tdstPos += copy(dd.hist[dstPos:endPos], dd.hist[srcPos:])\n\t\tsrcPos = 0\n\t}\n\n\t// Copy possibly overlapping section before destination position.\n\t//\n\t// This section can overlap if the copy length for this section is larger\n\t// than the backwards distance. This is allowed by LZ77 so that repeated\n\t// strings can be succinctly represented using (dist, length) pairs.\n\t// Thus, a forwards copy is performed here; that is, the bytes copied is\n\t// possibly dependent on the resulting bytes in the destination as the copy\n\t// progresses along. This is functionally equivalent to the following:\n\t//\n\t//\tfor i := 0; i < endPos-dstPos; i++ {\n\t//\t\tdd.hist[dstPos+i] = dd.hist[srcPos+i]\n\t//\t}\n\t//\tdstPos = endPos\n\t//\n\tfor dstPos < endPos {\n\t\tdstPos += copy(dd.hist[dstPos:endPos], dd.hist[srcPos:dstPos])\n\t}\n\n\tdd.wrPos = dstPos\n\treturn dstPos - dstBase\n}", "func Copy(x []byte) []byte {\n\tr := make([]byte, len(x))\n\tcopy(r, x)\n\treturn r\n}" ]
[ "0.5800434", "0.5727833", "0.54212874", "0.52668625", "0.5137672", "0.5091352", "0.50865716", "0.47963905", "0.47856638", "0.4722009", "0.46957615", "0.46068934", "0.4593441", "0.45838994", "0.45664155", "0.45664144", "0.45522085", "0.45507455", "0.45397383", "0.45167142", "0.4512966", "0.44911152", "0.44847292", "0.44556016", "0.44449648", "0.44158226", "0.4395286", "0.43884623", "0.4387638", "0.43814647", "0.43433505", "0.43425325", "0.43414265", "0.4324141", "0.432349", "0.43155283", "0.4306743", "0.42946577", "0.42800242", "0.42749417", "0.42724794", "0.42700675", "0.42665628", "0.42557266", "0.42550766", "0.42528778", "0.42409047", "0.4234466", "0.42248738", "0.42190313", "0.4218601", "0.42159247", "0.42158", "0.4209958", "0.42019826", "0.4189338", "0.4187536", "0.4186821", "0.4186821", "0.41843218", "0.41808826", "0.4178346", "0.4176269", "0.4176269", "0.41618928", "0.41616163", "0.41566163", "0.41558492", "0.41539323", "0.41505545", "0.41460782", "0.41441143", "0.414298", "0.41323063", "0.4132144", "0.41269875", "0.41257304", "0.41115484", "0.41108158", "0.40964368", "0.40936458", "0.40921557", "0.40891996", "0.40800217", "0.40769434", "0.40768328", "0.40741673", "0.40716383", "0.40716383", "0.4068902", "0.4067641", "0.40628803", "0.4060675", "0.40596312", "0.40570486", "0.40558025", "0.40499306", "0.40487507", "0.4048127", "0.40450576" ]
0.69708395
0
bigramWordByConcat concatenates adjecent pairs of word just by using plus operator.
func bigramWordByConcat(str string) []string { ss := strings.Split(str, " ") // Handle unexpected string input: // ss = "" => []string{""} // ss = "foobar" => []string{"foobar"} if len(ss) <= 1 { return ss } bigram := make([]string, len(ss)-1) for i := 0; i < len(ss)-1; i++ { bigram[i] = ss[i] + " " + ss[i+1] } return bigram }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func bigramWordByAppend(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tvar tmp string\n\tvar bigram []string\n\tfor i, s := range ss {\n\t\tif i != 0 {\n\t\t\tbigram = append(bigram, strings.Join([]string{tmp, s}, \" \"))\n\t\t}\n\t\ttmp = s\n\t}\n\treturn bigram\n}", "func biGramCharByConcat(s string) []string {\n\tr := []rune(strings.Replace(s, \" \", \"\", -1))\n\t// Handle unexpected string input.\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(r) <= 1 {\n\t\treturn []string{string(r)}\n\t}\n\n\tlist := make([]string, len(r)-1)\n\tfor i := 0; i < len(r)-1; i++ {\n\t\tlist[i] = string(r[i : i+2])\n\t}\n\treturn list\n}", "func concat(a string, b string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func ConcatWord(a, b uint8) uint16 {\n\treturn (uint16(a) << 8) | uint16(b)\n}", "func (self *codeGen) cgConcatExp(exp *BinopExp, a int) {\n\tallocator := self.newTmpAllocator(a)\n\tline, b, c := exp.Line, -1, -1\n\n\tfor {\n\t\ttmp := allocator.allocTmp()\n\t\tself.cgExp(exp.Exp1, tmp, 1)\n\t\tif b < 0 {\n\t\t\tb = tmp\n\t\t\tc = b\n\t\t} else {\n\t\t\tc++\n\t\t}\n\n\t\tif exp2, ok := castToConcatExp(exp.Exp2); ok {\n\t\t\texp = exp2\n\t\t} else {\n\t\t\ttmp := allocator.allocTmp()\n\t\t\tself.cgExp(exp.Exp2, tmp, 1)\n\t\t\tc++\n\t\t\tbreak\n\t\t}\n\t}\n\n\tallocator.freeAll()\n\tself.emit(line, OP_CONCAT, a, b, c)\n}", "func bigramWordByJoin(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\tbigram[i] = strings.Join([]string{ss[i], ss[i+1]}, \" \")\n\t}\n\treturn bigram\n}", "func Concat(s string, next Mapper) (value string, ok bool) {\n\tif inner, ok := ParseFunction(\"concat\", s); ok && len(inner) > 0 {\n\t\targs := strings.Split(inner, \"+\")\n\t\toutput := \"\"\n\t\tfor _, arg := range args {\n\t\t\tif value, ok := next(arg, next); ok {\n\t\t\t\toutput += value\n\t\t\t} else {\n\t\t\t\treturn \"\", false\n\t\t\t}\n\t\t}\n\t\treturn output, true\n\t}\n\treturn \"\", false\n}", "func Concat(in []string) (rv string) {\n\n\tswitch len(in) {\n\n\tcase 0:\n\t\treturn \"\"\n\n\tcase 1:\n\t\treturn in[0]\n\n\tcase 2:\n\t\treturn in[0] + in[1]\n\n\tcase 3:\n\t\treturn in[0] + in[1] + in[2]\n\t}\n\n\tn := 0\n\n\tfor i := 0; i < len(in); i++ {\n\t\tn += len(in[i])\n\t}\n\n\tb := make([]byte, n)\n\n\tbp := copy(b, in[0])\n\n\tfor _, s := range in[1:] {\n\t\tbp += copy(b[bp:], s)\n\t}\n\n\treturn string(b)\n}", "func Concat(s, t []rune) []rune {\n\tn := make([]rune, 0, len(s)+len(t))\n\tn = append(n, s...)\n\tn = append(n, t...)\n\treturn n\n}", "func Bvconcat(t []TermT) TermT {\n\tcount := C.uint32_t(len(t))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif count == 0 {\n\t\treturn NullTerm\n\t}\n\treturn TermT(C.yices_bvconcat(count, (*C.term_t)(&t[0])))\n}", "func Concat(x string, y string) (z bytes.Buffer) {\n\tz.Write([]byte(x))\n\tz.Write([]byte(y))\n\treturn\n}", "func Bvconcat2(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_bvconcat2(C.term_t(t1), C.term_t(t2)))\n}", "func (c *compiler) concatOp(expr *ast.BinaryExpr) {\n\tvar values []ast.Expr\n\tfor {\n\t\tvalues = append(values, expr.Right)\n\t\tleft, isBinary := expr.Left.(*ast.BinaryExpr)\n\t\tif !isBinary || left.Op != lexer.CONCAT {\n\t\t\tbreak\n\t\t}\n\t\texpr = left\n\t}\n\tvalues = append(values, expr.Left)\n\n\t// values are appended right to left\n\t// but need to pushed left to right\n\n\tif len(values) == 2 {\n\t\tc.expr(values[1])\n\t\tc.expr(values[0])\n\t\tc.add(Concat)\n\t\treturn\n\t}\n\n\tfor i := len(values) - 1; i >= 0; i-- {\n\t\tc.expr(values[i])\n\t}\n\n\tc.add(ConcatMulti, opcodeInt(len(values)))\n}", "func (g *Graph) Concat(xs ...Node) Node {\n\treturn g.NewOperator(fn.NewConcat(Operands(xs)), xs...)\n}", "func (q Query) Concat(q2 Query) Query {\n\treturn q.UnionAll(q2)\n}", "func BenchmarkConcatStrByAdd(b *testing.B) {\n\telements := []string{ \"1\", \"2\", \"3\", \"4\" }\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tret := \"\"\n\t\tfor _, element := range elements {\n\t\t\tret += element\n\t\t}\n\t}\n\tb.StopTimer()\n}", "func (p *reParser) concat() *reSyntax {\n\t// Scan down to find pseudo-operator || or ((.\n\ti := len(p.stack)\n\tfor i > 0 && p.stack[i-1].op < opPseudo {\n\t\ti--\n\t}\n\tsubs := p.stack[i:]\n\tp.stack = p.stack[:i]\n\n\t// Empty concatenation is special case.\n\tif len(subs) == 0 {\n\t\treturn p.push(&reSyntax{op: opEmpty})\n\t}\n\n\treturn p.push(p.collapse(opConcat, subs))\n}", "func mergeAlternately(word1 string, word2 string) string {\n\tvar buf bytes.Buffer\n\tfor i := range word1 {\n\t\tbuf.WriteByte(word1[i])\n\t\tif i < len(word2) {\n\t\t\tbuf.WriteByte(word2[i])\n\t\t}\n\t}\n\n\tif len(word1) < len(word2) {\n\t\tbuf.WriteString(word2[len(word1):])\n\t}\n\treturn buf.String()\n}", "func concat(args ...[]string) []string {\n\tvar buf []string\n\tfor _, arg := range args {\n\t\tbuf = append(buf, arg...)\n\t}\n\tsort.Strings(buf)\n\n\treturn buf\n}", "func (ref Ref) Concat(terms []*Term) Ref {\n\tif len(terms) == 0 {\n\t\treturn ref\n\t}\n\tcpy := make(Ref, len(ref)+len(terms))\n\tcopy(cpy, ref)\n\tcopy(cpy[len(ref):], terms)\n\treturn cpy\n}", "func ExampleConcat() {\n\tvar buf1 bytes.Buffer\n\tvar buf2 bytes.Buffer\n\n\tbuf1.WriteString(\"ciao\\n\")\n\tbuf1.WriteString(\"salve\\n\")\n\n\tbuf2.WriteString(\"Andre\\n\")\n\tbuf2.WriteString(\"Parro\\n\")\n\tbuf2.WriteString(\"The end\\n\")\n\n\terr := horzcat.Concat(horzcat.Options{\n\t\tSep: \",\",\n\t\tTail: \"!\",\n\t}, &buf1, &buf2)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// Output: ciao,Andre!\n\t// salve,Parro!\n\t// The end!\n}", "func (ad *stubAddService) Concat(ctx context.Context, a string, b string) (res string, err error) {\n\tres = a + b\n\terr = ad.nc.Publish(addTopic, []byte(res))\n\tif err != nil {\n\t\tlevel.Error(ad.logger).Log(\"method\", \"ad.nc.Publish\", \"value\", res, \"err\", err)\n\t\treturn\n\t}\n\n\treturn res, err\n}", "func SortAndConcat(param map[string]string) string {\n\tvar keys []string\n\tfor k := range param {\n\t\tkeys = append(keys, k)\n\t}\n\n\tvar sortedParam []string\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\t// fmt.Println(k, \"=\", param[k])\n\t\tsortedParam = append(sortedParam, k+\"=\"+param[k])\n\t}\n\n\treturn strings.Join(sortedParam, \"&\")\n}", "func (comp *Compressor) Concat(uncompressed string) {\n\tdictSize := 256\n\tvar w []byte\n\tfor i := 0; i < len(uncompressed); i++ {\n\t\tch := uncompressed[i]\n\t\tappended := append(w, ch)\n\t\tif _, ok := comp.Dictionary[string(appended)]; ok {\n\t\t\tw = appended\n\t\t} else {\n\t\t\tcomp.Yield = append(comp.Yield, comp.Dictionary[string(w)])\n\t\t\t// Add appended to the dictionary.\n\t\t\tcomp.Dictionary[string(appended)] = byte(dictSize)\n\t\t\tdictSize++\n\t\t\t//w = []byte{ch}, but re-using appended\n\t\t\tappended[0] = ch\n\t\t\tw = appended[:1]\n\t\t}\n\t}\n\n\tif len(w) > 0 {\n\t\t// Output the code for w.\n\t\tcomp.Yield = append(comp.Yield, comp.Dictionary[string(w)])\n\t}\n}", "func Concat(patts ...Pattern) Pattern {\n\tif len(patts) <= 0 {\n\t\treturn &EmptyNode{}\n\t}\n\n\tacc := patts[0]\n\tfor _, p := range patts[1:] {\n\t\tacc = &SeqNode{\n\t\t\tLeft: acc,\n\t\t\tRight: p,\n\t\t}\n\t}\n\n\treturn acc\n}", "func (nGramMap NGramMap) CombineDistinctiveNGrams(words []string, maxN int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tfor i := 2; i <= maxN; i++ {\n\t\terr := nGramMap.addDistinctiveNGrams(words, i, distinctiveWords, threshold)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (e *ConstantExpr) Concat(lsb *ConstantExpr) *ConstantExpr {\n\treturn NewConstantExpr((e.Value<<lsb.Width)|lsb.Value, ExprWidth(e)+ExprWidth(lsb))\n}", "func bigramWordByCopy(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\t// Counts the length of primary and secondary words and whitespace\n\t\t// and copy it to the element of slice.\n\t\tbigram[i] = str[:(len(ss[i])+1)+len(ss[i+1])]\n\t\t// Drop the primary word and whitespace.\n\t\tstr = str[len(ss[i])+1:]\n\t}\n\treturn bigram\n}", "func Concat(path, path2 []string) []string {\n\tpathCopy := make([]string, len(path))\n\tcopy(pathCopy, path)\n\n\tif len(path) == 0 {\n\t\tpath2Copy := make([]string, len(path2))\n\t\tcopy(path2Copy, path)\n\t\treturn path2Copy\n\t}\n\n\tif len(path2) == 0 {\n\t\treturn pathCopy\n\t}\n\n\tif path[len(path)-1] != path2[0] {\n\t\tlog.Fatalln(\"Tried to compute\", path, \"+\", path2, \"but their ends differ\")\n\t}\n\n\tpathCopy = append(pathCopy[:len(pathCopy)-1], path2...)\n\treturn pathCopy\n}", "func combine(str1, str2 string) string {\n\tvar res string\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\t//mark the number of same chars\n\tvar sameNum int = 0\n\tfor len1 > 0 && sameNum < len2 {\n\t\tif str1[len1-1] == str2[sameNum] {\n\t\t\tlen1--\n\t\t\tsameNum++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\t//combine str1 and str2\n\tres = str1[0:len1] + str2[sameNum:len2]\n\treturn res\n\n}", "func concat(args ...[]string) []string {\n\tvar buf []string\n\tfor _, arg := range args {\n\t\tbuf = append(buf, arg...)\n\t}\n\n\treturn buf\n}", "func Concat(x, y meta.ConstValue) meta.ConstValue {\n\tv1, ok1 := x.ToString()\n\tv2, ok2 := y.ToString()\n\tif ok1 && ok2 {\n\t\treturn meta.NewStringConst(v1 + v2)\n\t}\n\treturn meta.UnknownValue\n}", "func adjoin(strs []string, add string) []string {\n\tfor _, s := range strs {\n\t\tif s == add {\n\t\t\treturn strs\n\t\t}\n\t}\n\tstrs = append(strs, add)\n\treturn strs\n}", "func Concat(input []string) string {\n\treturn strings.Join(input, \" \")\n}", "func largestMerge(word1 string, word2 string) string {\n\tvar i, j int\n\tans := make([]byte, 0, len(word1)+len(word2))\n\tfor i < len(word1) && j < len(word2) {\n\t\tcomp := strings.Compare(word1[i:], word2[j:])\n\t\tif comp > 0 {\n\t\t\tans = append(ans, word1[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tans = append(ans, word2[j])\n\t\t\tj++\n\t\t}\n\t}\n\tfor i < len(word1) {\n\t\tans = append(ans, word1[i])\n\t\ti++\n\t}\n\tfor j < len(word2) {\n\t\tans = append(ans, word2[j])\n\t\tj++\n\t}\n\treturn string(ans)\n}", "func tabConcat(ls *LuaState) int {\n\ttabLen := _auxGetN(ls, 1, TAB_R)\n\tsep := luaOptString(ls, 2, \"\")\n\ti := luaOptInteger(ls, 3, 1)\n\tj := luaOptInteger(ls, 4, tabLen)\n\n\tif i > j {\n\t\tls.Push(LuaString(\"\"))\n\t\treturn 1\n\t}\n\n\tbuf := make([]string, j-i+1)\n\tfor k := i; k > 0 && k <= j; k++ {\n\t\tluaGetI(ls, 1, k)\n\t\tif !luaIsString(ls, -1) {\n\t\t\tls.Error2(\"invalid value (%s) at index %d in table for 'concat'\",\n\t\t\t\tluaTypeName2(ls, -1), i)\n\t\t}\n\t\tbuf[k-i] = luaToString(ls, -1)\n\t\tluaPop(ls, 1)\n\t}\n\tls.Push(LuaString(strings.Join(buf, sep)))\n\n\treturn 1\n}", "func ConcatBySpace(str ...interface{}) string {\n\tvar buffer bytes.Buffer\n\tfor i := 0; i < len(str); i++ {\n\t\tbuffer.WriteString(fmt.Sprint(str[i]))\n\t\tbuffer.WriteString(\" \")\n\t}\n\treturn strings.TrimSpace(buffer.String())\n}", "func addBinary(a string, b string) string {\n\taL, bL, plus, res := len(a)-1, len(b)-1, 0, \"\"\n\tfor plus > 0 || (aL >= 0 && bL >= 0) {\n\t\ttmp := plus\n\t\tif aL >= 0 {\n\t\t\ttmp += int(a[aL] - '0')\n\t\t}\n\t\tif bL >= 0 {\n\t\t\ttmp += int(b[bL] - '0')\n\t\t}\n\t\tres = strconv.Itoa(tmp%2) + res\n\t\tplus = tmp / 2\n\n\t\t//fmt.Println(\"=======\", a[aL] - '0', \"==\", b[bL] - '0', \"===\", tmp % 2, \"==\", tmp / 2, \"==\", strconv.Itoa(tmp % 2), \"==\", res)\n\n\t\taL--\n\t\tbL--\n\t}\n\tif aL >= 0 {\n\t\tres = a[:aL+1] + res\n\t}\n\tif bL >= 0 {\n\t\tres = b[:bL+1] + res\n\t}\n\treturn res\n}", "func Concat(back, front List) List {\n\tfoldFunc := func(carry, elem interface{}) interface{} {\n\t\treturn Cons(elem, carry)\n\t}\n\treturn Foldr(foldFunc, front, back).(List)\n}", "func BCat(b1, b2 []byte) []byte {\n\treturn append(b1, b2...)\n}", "func concat(i Instruction, ls *LuaState) {\n\ta, b, c := i.ABC()\n\ta += 1\n\tb += 1\n\tc += 1\n\n\tn := c - b + 1\n\tluaCheckStack(ls, n)\n\tfor i := b; i <= c; i++ {\n\t\tluaPushValue(ls, i)\n\t}\n\tluaConcat(ls, n)\n\tluaReplace(ls, a)\n}", "func (g *wordGraph) include(word string) {\n\tif len(word) != g.n || !isWord(word) {\n\t\treturn\n\t}\n\tword = strings.ToLower(word)\n\tif _, exists := g.ids[word]; exists {\n\t\treturn\n\t}\n\n\t// We know the node is not yet in the graph, so we can add it.\n\tu := g.UndirectedGraph.NewNode()\n\tuid := u.ID()\n\tu = node{word: word, id: uid}\n\tg.UndirectedGraph.AddNode(u)\n\tg.ids[word] = uid\n\n\t// Join to all the neighbours from words we already know.\n\tfor _, v := range neighbours(word, g.ids) {\n\t\tv := g.UndirectedGraph.Node(g.ids[v])\n\t\tg.SetEdge(simple.Edge{F: u, T: v})\n\t}\n}", "func add(a string, b string) string {\n\tevenPad(&a, &b)\n\n\tsum := \"\"\n\tc := 0\n\tfor i := len(a) - 1; i >= 0; i-- {\n\t\taint, _ := strconv.Atoi(string(a[i]))\n\t\tbint, _ := strconv.Atoi(string(b[i]))\n\t\ts := aint + bint + c\n\t\tif s >= 10 {\n\t\t\tc = 1\n\t\t\ts -= 10\n\t\t} else {\n\t\t\tc = 0\n\t\t}\n\t\tsum = strconv.Itoa(s) + sum\n\t}\n\n\tif c > 0 {\n\t\tsum = strconv.Itoa(c) + sum\n\t}\n\n\treturn sum\n}", "func ConcatString(left []string, right []string) []string {\n\tresult := make([]string, 0)\n\tresult = append(result, left...)\n\tresult = append(result, right...)\n\treturn result\n}", "func biGramChar(str string) []string {\n\ts := strings.Replace(str, \" \", \"\", -1)\n\n\tif len(str) <= 1 {\n\t\treturn []string{str}\n\t}\n\n\tbigram := make([]string, len(s)-1)\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tbigram[i] = s[i : i+2]\n\t}\n\treturn bigram\n}", "func (ns *NumStar) Concat(m, n string, s int) string {\n\tmLines := strings.Split(m, \"\\n\")\n\tnLines := strings.Split(n, \"\\n\")\n\tmLineCount := len(mLines)\n\tnLineCount := len(nLines)\n\tmWidth := len(mLines[0])\n\tnWidth := len(nLines[0])\n\n\tif mWidth == 0 {\n\t\treturn n\n\t}\n\n\tif nWidth == 0 {\n\t\treturn m\n\t}\n\n\tspaces := strings.Repeat(ns.space, s)\n\tif mLineCount < nLineCount {\n\t\tfor i := mLineCount; i < nLineCount; i++ {\n\t\t\tmLines = append(mLines, strings.Repeat(ns.space, mWidth))\n\t\t}\n\t} else {\n\t\tif nLineCount < mLineCount {\n\t\t\tfor i := nLineCount; i < mLineCount; i++ {\n\t\t\t\tnLines = append(nLines, strings.Repeat(ns.space, nWidth))\n\t\t\t}\n\t\t}\n\t}\n\n\tbuff := []string{}\n\n\tfor i, n := 0, len(mLines); i < n; i++ {\n\t\tbuff = append(buff, mLines[i]+spaces+nLines[i])\n\t}\n\n\treturn strings.Join(buff, \"\\n\")\n}", "func CombinePrefixAndSuffix(prefix, suffix string, itself, hyphenate, fuse bool, minLength int) []string {\n\tvar output []string\n\tif prefix == suffix && !itself {\n\t\treturn output\n\t}\n\tstr := prefix + suffix\n\tif len(str) >= minLength {\n\t\toutput = append(output, str)\n\t}\n\tif fuse {\n\t\tif strings.HasSuffix(prefix, suffix[0:1]) {\n\t\t\toutput = append(output, prefix+suffix[1:])\n\t\t}\n\t\tif strings.HasSuffix(prefix, suffix[0:2]) {\n\t\t\toutput = append(output, prefix+suffix[2:])\n\t\t}\n\t}\n\tif hyphenate {\n\t\tstr := prefix + \"-\" + suffix\n\t\tif len(str) >= minLength {\n\t\t\toutput = append(output, prefix+\"-\"+suffix)\n\t\t}\n\t}\n\treturn output\n}", "func Concat(seqs ...cty.Value) (cty.Value, error) {\n\treturn ConcatFunc.Call(seqs)\n}", "func union(a, b []string) [][]rune {\n\tm := make(map[string]bool)\n\tfor _, item := range a {\n\t\tm[item] = true\n\t}\n\tfor _, item := range b {\n\t\tif _, ok := m[item]; !ok {\n\t\t\ta = append(a, item)\n\t\t}\n\t}\n\n\t// Convert a to rune matrix (with x -> words and y -> characters)\n\tout := make([][]rune, len(a))\n\tfor i, word := range a {\n\t\tout[i] = []rune(word)\n\t}\n\treturn out\n}", "func MarshalConcat(va interface{}, vbs ...interface{}) ([]byte, error) {\n\tunique, err := marshalConcat(nil, va, vbs...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn json.Marshal(unique)\n}", "func Concat(args ...interface{}) (out []byte) {\n\tfor _, arg := range args {\n\t\tswitch v := arg.(type) {\n\t\tcase string:\n\t\t\tout = append(out, []byte(v)...)\n\t\tcase []byte:\n\t\t\tout = append(out, v...)\n\t\t}\n\t}\n\treturn out\n}", "func PlusConcatLiteral(src string) bool {\n\tidx := 0\n\tisMatching := true\n\n\tplusBoolResult58 := false\n\tplusBoolResult62 := false\n\n\tstaticStr57 := \"a\"\n\tstaticStr57Len := len(staticStr57)\n\n\tif staticStr57Len+idx > len(src) {\n\t\tisMatching = false\n\t} else if staticStr57 == src[idx:idx+staticStr57Len] {\n\t\tidx += staticStr57Len\n\t\tisMatching = true\n\t} else {\n\t\tisMatching = false\n\t}\n\tplusIdxResult59 := idx\n\n\tif isMatching {\n\t\tfor {\n\n\t\t\tstaticStr60 := \"a\"\n\t\t\tstaticStr60Len := len(staticStr60)\n\n\t\t\tif staticStr60Len+plusIdxResult59 > len(src) {\n\t\t\t\tplusBoolResult58 = false\n\t\t\t} else if staticStr60 == src[plusIdxResult59:plusIdxResult59+staticStr60Len] {\n\t\t\t\tplusIdxResult59 += staticStr60Len\n\t\t\t\tplusBoolResult58 = true\n\t\t\t} else {\n\t\t\t\tplusBoolResult58 = false\n\t\t\t}\n\n\t\t\tif !plusBoolResult58 {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tisMatching = plusBoolResult58\n\t\t\t\tidx = plusIdxResult59\n\t\t\t}\n\t\t}\n\t}\n\tif isMatching {\n\n\t\tstaticStr61 := \"b\"\n\t\tstaticStr61Len := len(staticStr61)\n\n\t\tif staticStr61Len+idx > len(src) {\n\t\t\tisMatching = false\n\t\t} else if staticStr61 == src[idx:idx+staticStr61Len] {\n\t\t\tidx += staticStr61Len\n\t\t\tisMatching = true\n\t\t} else {\n\t\t\tisMatching = false\n\t\t}\n\t\tplusIdxResult63 := idx\n\n\t\tif isMatching {\n\t\t\tfor {\n\n\t\t\t\tstaticStr64 := \"b\"\n\t\t\t\tstaticStr64Len := len(staticStr64)\n\n\t\t\t\tif staticStr64Len+plusIdxResult63 > len(src) {\n\t\t\t\t\tplusBoolResult62 = false\n\t\t\t\t} else if staticStr64 == src[plusIdxResult63:plusIdxResult63+staticStr64Len] {\n\t\t\t\t\tplusIdxResult63 += staticStr64Len\n\t\t\t\t\tplusBoolResult62 = true\n\t\t\t\t} else {\n\t\t\t\t\tplusBoolResult62 = false\n\t\t\t\t}\n\n\t\t\t\tif !plusBoolResult62 {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tisMatching = plusBoolResult62\n\t\t\t\t\tidx = plusIdxResult63\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif idx != len(src) {\n\t\tisMatching = false\n\t}\n\n\treturn isMatching\n\t// End of PlusConcatLiteral\n}", "func Concat(strings []string) string {\n\ts, sep := \"\", \"\"\n\tfor _, str := range strings {\n\t\ts += sep + str // NB: inefficient!\n\t\tsep = \" \"\n\t}\n\treturn s\n}", "func BookListConcat(key, id string, page string) string {\n\tvar booklist bytes.Buffer\n\n\tbooklist.WriteString(\"https://www.goodreads.com/author/list.xml?key=\")\n\tbooklist.WriteString(key)\n\tbooklist.WriteString(\"&id=\")\n\tbooklist.WriteString(id)\n\tbooklist.WriteString(\"&page=\")\n\tbooklist.WriteString(page)\n\n\treturn booklist.String()\n}", "func Accumulate(words []string, converter Converter) []string {\n\tresult := make([]string, len(words))\n\tfor i, word := range words {\n\t\tresult[i] = converter(word)\n\t}\n\treturn result\n}", "func NewConcat(l, r Regex) Regex {\n\tswitch l.(type) {\n\tcase *empty:\n\t\treturn NewEmpty()\n\tcase *epsilon:\n\t\treturn r\n\tdefault:\n\t\treturn &concat{\n\t\t\tl: l,\n\t\t\tr: r,\n\t\t}\n\t}\n}", "func Concatenate(strings ...string) string {\n\n\tfinalStr := \"\"\n\n\tfor _, str := range strings {\n\t\tfinalStr = finalStr + str\n\t}\n\treturn finalStr\n\n}", "func (fn *formulaFuncs) CONCAT(argsList *list.List) formulaArg {\n\treturn fn.concat(\"CONCAT\", argsList)\n}", "func SafeConcat(s, t []rune) []rune {\n\tn := make([]rune, 0, len(s)+len(t))\n\tfor _, e := range s {\n\t\tn = append(n, e)\n\t}\n\tfor _, e := range t {\n\t\tn = append(n, e)\n\t}\n\treturn n\n}", "func StringConcat(s1, s2 string) string {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(s1)\n\tbuffer.WriteString(s2)\n\treturn buffer.String()\n}", "func concatRepetition(r *syntax.Regexp) (bool, *syntax.Regexp) {\n\tif r.Op != syntax.OpConcat {\n\t\t// don't iterate sub-expressions if top-level is no OpConcat\n\t\treturn false, r\n\t}\n\n\t// check if concatenated op is already a repetition\n\tif isConcatRepetition(r) {\n\t\treturn false, r\n\t}\n\n\t// concatenate repetitions in sub-expressions first\n\tvar subs []*syntax.Regexp\n\tchanged := false\n\tfor _, sub := range r.Sub {\n\t\tchangedSub, tmp := concatRepetition(sub)\n\t\tchanged = changed || changedSub\n\t\tsubs = append(subs, tmp)\n\t}\n\n\tvar concat []*syntax.Regexp\n\tlastMerged := -1\n\tfor i, j := 0, 1; j < len(subs); i, j = j, j+1 {\n\t\tif subs[i].Op == syntax.OpRepeat && eqRegex(subs[i].Sub[0], subs[j]) {\n\t\t\tr := subs[i]\n\t\t\tconcat = append(concat,\n\t\t\t\t&syntax.Regexp{\n\t\t\t\t\tOp: syntax.OpRepeat,\n\t\t\t\t\tSub: r.Sub,\n\t\t\t\t\tMin: r.Min + 1,\n\t\t\t\t\tMax: r.Max + 1,\n\t\t\t\t\tFlags: r.Flags,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tlastMerged = j\n\t\t\tchanged = true\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\t\tif isConcatRepetition(subs[i]) && eqRegex(subs[i].Sub[0], subs[j]) {\n\t\t\tr := subs[i]\n\t\t\tconcat = append(concat,\n\t\t\t\t&syntax.Regexp{\n\t\t\t\t\tOp: syntax.OpConcat,\n\t\t\t\t\tSub: append(r.Sub, r.Sub[0]),\n\t\t\t\t\tFlags: r.Flags,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tlastMerged = j\n\t\t\tchanged = true\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\t\tif eqRegex(subs[i], subs[j]) {\n\t\t\tr := subs[i]\n\t\t\tconcat = append(concat,\n\t\t\t\t&syntax.Regexp{\n\t\t\t\t\tOp: syntax.OpRepeat,\n\t\t\t\t\tSub: []*syntax.Regexp{r},\n\t\t\t\t\tMin: 2,\n\t\t\t\t\tMax: 2,\n\t\t\t\t\tFlags: r.Flags,\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tlastMerged = j\n\t\t\tchanged = true\n\t\t\tj++\n\t\t\tcontinue\n\t\t}\n\n\t\tconcat = append(concat, subs[i])\n\t}\n\n\tif lastMerged+1 != len(subs) {\n\t\tconcat = append(concat, subs[len(subs)-1])\n\t}\n\n\tr = &syntax.Regexp{\n\t\tOp: syntax.OpConcat,\n\t\tSub: concat,\n\t\tFlags: r.Flags,\n\t}\n\treturn changed, r\n}", "func conc(lhs, rhs node, lhsLength, rhsLength int64) node {\n\tif lhs == emptyNode {\n\t\treturn rhs\n\t}\n\tif rhs == emptyNode {\n\t\treturn lhs\n\t}\n\n\tdepth := lhs.depth()\n\tif d := rhs.depth(); d > depth {\n\t\tdepth = d\n\t}\n\n\tif lhsLength <= 0 {\n\t\tlhsLength = lhs.length()\n\t}\n\tif rhsLength <= 0 {\n\t\trhsLength = rhs.length()\n\t}\n\n\t// Optimize small + small\n\tif lhsLength+rhsLength <= concatThreshold {\n\t\tbuf := bytes.NewBuffer(make([]byte, 0, lhsLength+rhsLength))\n\t\tlhs.WriteTo(buf)\n\t\trhs.WriteTo(buf)\n\t\treturn leaf(buf.String())\n\t}\n\t// Re-associate (large+small) + small ==> large + (small+small)\n\tif cc, ok := lhs.(*concat); ok {\n\t\tccrlen := cc.rLength()\n\t\tif ccrlen+rhsLength <= concatThreshold {\n\t\t\treturn conc(cc.Left, conc(cc.Right, rhs, ccrlen, rhsLength), cc.Split, ccrlen+rhsLength)\n\t\t}\n\t}\n\t// Re-associate small + (small+large) ==> (small+small) + large\n\tif cc, ok := rhs.(*concat); ok {\n\t\tif lhsLength+cc.Split <= concatThreshold {\n\t\t\treturn conc(conc(lhs, cc.Left, lhsLength, cc.Split), cc.Right, cc.Split, cc.rLength())\n\t\t}\n\t}\n\n\tif rhsLength > int64(^rLenT(0)) {\n\t\t// Out of range\n\t\trhsLength = 0\n\t}\n\n\treturn &concat{\n\t\tLeft: lhs,\n\t\tRight: rhs,\n\t\tTreeDepth: depth + 1,\n\t\tSplit: lhsLength,\n\t\tRLen: rLenT(rhsLength),\n\t}\n}", "func Concat(parts ...string) (string, error) {\n\tif len(parts) == 0 {\n\t\treturn \"\", errors.New(\"No strings supplied\") // it is good practice to always return a useable value\n\t}\n\n\treturn strings.Join(parts, \" \"), nil\n}", "func DefConcat() {\n\tbuiltin(Concat, \"(s, t)\")\n}", "func Concat(ss ...Sequence) Sequence {\n\tswitch len(ss) {\n\tcase 0:\n\t\treturn New(nil, nil, nil)\n\tcase 1:\n\t\treturn ss[0]\n\tdefault:\n\t\thead, tail := ss[0], ss[1:]\n\t\tff, p := head.Features(), head.Bytes()\n\n\t\tfor _, seq := range tail {\n\t\t\tfor _, f := range seq.Features() {\n\t\t\t\tf.Loc = f.Loc.Expand(0, len(p))\n\t\t\t\tff = ff.Insert(f)\n\t\t\t}\n\t\t\tp = append(p, seq.Bytes()...)\n\t\t}\n\n\t\thead = WithFeatures(head, ff)\n\t\thead = WithBytes(head, p)\n\n\t\treturn head\n\t}\n}", "func BigProduct(a string, b string) string {\n\tnum1 := BigNum{a}.Digits(baseZeros)\n\tnum2 := BigNum{b}.Digits(baseZeros)\n\n\tbase := uint(math.Pow10(baseZeros))\n\tzeroPadding := strings.Repeat(\"0\", baseZeros)\n\n\taddends := make([]string, len(num2))\n\n\tfor n2i := len(num2) - 1; n2i >= 0; n2i-- {\n\t\tcarryOver := uint(0)\n\t\ttempSum := uint(0)\n\t\taddend := \"\"\n\t\tprod := uint(0)\n\t\tfor n1i := len(num1) - 1; n1i >= 0; n1i-- {\n\t\t\ttempSum = num1[n1i]*num2[n2i] + carryOver\n\n\t\t\tcarryOver = tempSum / base\n\t\t\tprod = tempSum % base\n\n\t\t\tif prod > 0 {\n\t\t\t\tprodS := fmt.Sprintf(\"%d\", prod)\n\t\t\t\taddend = prodS + addend\n\t\t\t\tif len(prodS) < baseZeros {\n\t\t\t\t\taddend = strings.Repeat(\"0\", baseZeros-len(prodS)) + addend\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddend = zeroPadding + addend\n\t\t\t}\n\t\t}\n\t\taddend += strings.Repeat(zeroPadding, len(num2)-n2i-1)\n\t\tif carryOver > 0 {\n\t\t\taddend = fmt.Sprintf(\"%d\", carryOver) + addend\n\t\t}\n\t\taddends[n2i] = addend\n\n\t}\n\n\treturn BigSum(addends)\n}", "func newRawConcat() concat {\n\tnl := []byte{byte('\\n')}\n\treturn concat{\n\t\tjoin: func(element store.Element) ([]byte, error) {\n\t\t\tb, err := Concat(len(element.Value)+len(nl), element.Value, nl)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not serialize value %w\", err)\n\t\t\t}\n\t\t\treturn b, nil\n\t\t},\n\t\tsplit: func(key store.Key, data []byte) (store.Element, error) {\n\t\t\tn := len(data) - len(nl)\n\t\t\treturn store.NewElement(key, data[0:n+1]), nil\n\t\t},\n\t}\n}", "func concatenate() (end int64) {\n var s, sep string\n start := time.Now()\n for i := 0; i < len(os.Args); i++ {\n s += sep + os.Args[i]\n sep = \" || \"\n }\n end = time.Since(start).Nanoseconds()\n return\n}", "func cat(a, b string) string {\n\tif (a != \"\") && (b != \"\") {\n\t\treturn a + \" \" + b\n\t} else {\n\t\treturn a + b\n\t}\n}", "func BigSum(addends []string) string {\n\n\tmaxLen := getMaxLen(addends)\n\tvar co uint64\n\tsum := \"\"\n\n\tfor i := 0; i < maxLen; i++ {\n\t\trem := uint64(0) + co\n\t\tfor _, addend := range addends {\n\t\t\taIndex := len(addend) - 1 - i\n\t\t\tif aIndex >= 0 {\n\t\t\t\trem += uint64(addend[aIndex] - 48)\n\t\t\t}\n\t\t}\n\t\tco = rem / 10\n\t\tsum = strconv.Itoa(int(rem%10)) + sum\n\t}\n\n\tif co > 0 {\n\t\tsum = strconv.Itoa(int(co)) + sum\n\t}\n\n\treturn sum\n}", "func addedge(from *BasicBlock, to *BasicBlock) {\n\tif from == nil {\n\t\tFatal(\"addedge: from is nil\")\n\t}\n\tif to == nil {\n\t\tFatal(\"addedge: to is nil\")\n\t}\n\tfrom.succ = append(from.succ, to)\n\tto.pred = append(to.pred, from)\n}", "func (c *Client) Concat(ctx context.Context, p *ConcatPayload) (res string, err error) {\n\tvar ires any\n\tires, err = c.ConcatEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ires.(string), nil\n}", "func ffmpegConcatTris(dirIn, f1, f2, f3, dirOut, f4 string) {\n\tf1 = dirIn + \"/\" + f1\n\tf2 = dirIn + \"/\" + f2\n\tf3 = dirIn + \"/\" + f3\n\tf4 = dirOut + \"/\" + f4\n\tcmd := exec.Command(\"ffmpeg\", \"-i\", f1, \"-i\", f2, \"-i\", f3, \"-filter_complex\", \"[0:0][1:0][2:0]concat=n=3:v=0:a=1[out]\", \"-map\", \"[out]\", f4)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func Concat(vars, params map[string]interface{}, str string) string {\n\tconst (\n\t\tstart = \"concat(\"\n\t\tend = \")\"\n\t)\n\n\tkey := strings.TrimPrefix(str, \"[\")\n\tkey = strings.TrimRight(key, \"]\")\n\tresults := exp.New().\n\t\tStartOfLine().Find(start).\n\t\tBeginCapture().Anything().EndCapture().\n\t\tFind(end).EndOfLine().\n\t\tCaptures(key)\n\n\tif len(results) == 0 {\n\t\tzap.S().Debugf(\"failed to parse expression: %s\", str)\n\t\treturn \"\"\n\t}\n\n\tsb := &strings.Builder{}\n\tcs := strings.Split(results[0][1], \",\")\n\tfor _, s := range cs {\n\t\ts = strings.TrimSpace(s)\n\t\ts = strings.Trim(s, \"'\")\n\t\tif _, err := sb.WriteString(LookUpString(vars, params, s)); err != nil {\n\t\t\tzap.S().Debugf(\"failed to parse expression: %s\", str)\n\t\t\treturn \"\"\n\t\t}\n\t}\n\treturn sb.String()\n}", "func TestCheckConcatenation(t *testing.T) {\n\tvar tests = []struct {\n\t\tpermutation string\n\t\tstr string\n\t\texpected []int\n\t}{\n\t\t{\"123\", \"2a123b321\", []int{2}},\n\t\t{\"123\", \"21123a\", []int{2}},\n\t\t{\"123\", \"a12321\", []int{1}},\n\t\t{\"123\", \"24143424\", []int{}},\n\t}\n\tfor _, test := range tests {\n\t\tanswers := Check(test.permutation, test.str)\n\t\tfor i, v := range test.expected {\n\t\t\tif answers[i] != v {\n\t\t\t\tt.Error(`CheckConcatenation {} expected, {} result,`, v, answers[i])\n\t\t\t}\n\t\t}\n\t}\n}", "func Bvadd(t1 TermT, t2 TermT) TermT {\n\treturn TermT(C.yices_bvadd(C.term_t(t1), C.term_t(t2)))\n}", "func combineText(labelsList []string) string {\n\tbeforeLength := 0\n\tfor _, s := range labelsList {\n\t\tbeforeLength += len(s)\n\t}\n\n\ttext := crush(removeSubstrings(labelsList))\n\tif *v {\n\t\tfmt.Fprintf(os.Stderr, \"crushed %d bytes to become %d bytes\\n\", beforeLength, len(text))\n\t}\n\treturn text\n}", "func (nGramMap NGramMap) addDistinctiveNGrams(words []string, n int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tnGrams, err := createNGrams(words, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, gram := range nGrams {\n\t\tif gram.IsDistinctive(distinctiveWords, threshold) {\n\t\t\tnGramMap[gram.Key()]++\n\t\t}\n\t}\n\treturn nil\n}", "func transformAdd(n *ir.BinaryExpr) ir.Node {\n\tassert(n.Type() != nil && n.Typecheck() == 1)\n\tl := n.X\n\tif l.Type().IsString() {\n\t\tvar add *ir.AddStringExpr\n\t\tif l.Op() == ir.OADDSTR {\n\t\t\tadd = l.(*ir.AddStringExpr)\n\t\t\tadd.SetPos(n.Pos())\n\t\t} else {\n\t\t\tadd = ir.NewAddStringExpr(n.Pos(), []ir.Node{l})\n\t\t}\n\t\tr := n.Y\n\t\tif r.Op() == ir.OADDSTR {\n\t\t\tr := r.(*ir.AddStringExpr)\n\t\t\tadd.List.Append(r.List.Take()...)\n\t\t} else {\n\t\t\tadd.List.Append(r)\n\t\t}\n\t\ttyped(l.Type(), add)\n\t\treturn add\n\t}\n\treturn n\n}", "func matchprefix(a, b string) string {\n\tres := \"\"\n\tsmallest := len(a)\n\tif smallest > len(b) {\n\t\tsmallest = len(b)\n\t}\n\tfor i := 0; i < smallest; i++ {\n\t\tif a[i] == b[i] {\n\t\t\tres += string(a[i])\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn res\n}", "func permutations(w string) []string {\n\tif w == \"\" {\n\t\treturn []string{\" \"}\n\t}\n\tperms := []string{}\n\tfor i, r := range w {\n\t\tremain := w[:i] + w[i+1:]\n\t\t//fmt.Println(remain)\n\t\tfor _, result := range permutations(remain) {\n\t\t\tperms = append(perms, fmt.Sprintf(\"%c\", r)+result)\n\t\t}\n\t\t//perms = append(perms, fmt.Sprintf(\"%c\\n\", r))\n\t}\n\treturn perms\n}", "func compose(dict map[string]bool, word []byte) []string {\n\n\t// The approach is to find all words in the dictionary\n\t// that are prefixes of the argument word and then recurse\n\t// to perform the rest of the word's parsing.\n\n\t// Search for prefixes by prefix length.\n\t//\n\tword_len := len(word)\n\tfor prefix_len := 1; prefix_len <= word_len; prefix_len++ {\n\n\t\tprefix := string(word[0:prefix_len])\n\n\t\t// Lookup the prefix in the dictionary.\n\t\t// If the prefix does not match, try the next length of prefix.\n\t\tif !dict[prefix] {\n\t\t\tcontinue\n\t\t}\n\n\t\tprefix_word_list := []string{prefix}\n\n\t\t// If the prefix consumed the entire string, then the parse succeeded.\n\t\tif prefix_len == word_len {\n\t\t\treturn prefix_word_list\n\t\t}\n\n\t\t// If the prefix did not consume the entire string,\n\t\t// attempt to parse the suffix by recursing.\n\t\tsuffix_word_list := compose(dict, []byte(word[prefix_len:word_len]))\n\n\t\t// If the suffix parsed, then the parse succeeded.\n\t\tif len(suffix_word_list) > 0 {\n\t\t\treturn append(prefix_word_list, suffix_word_list...)\n\t\t}\n\n\t\t// If the suffix parse failed, this parse has failed, but we\n\t\t// still need to go around to try the remaining prefix lengths.\n\t}\n\n\treturn []string{}\n}", "func BAdd(a, b []int) []int {\n\tif len(a) != len(b) {\n\t\treturn nil\n\t}\n\n\tc := make([]int, len(a)+1)\n\tcarry := 0\n\n\tfor i := len(a) - 1; i >= 0; i-- {\n\t\tc[i+1] = a[i] + b[i] + carry\n\t\tif c[i+1] > 1 {\n\t\t\tc[i+1] = 0\n\t\t\tcarry = 1\n\t\t} else {\n\t\t\tcarry = 0\n\t\t}\n\t}\n\tc[0] = carry\n\n\treturn c\n}", "func NewConcatExpr(msb, lsb Expr) Expr {\n\t// Combine expressions if they are both constants.\n\tif msb, ok := msb.(*ConstantExpr); ok {\n\t\tif lsb, ok := lsb.(*ConstantExpr); ok {\n\t\t\treturn msb.Concat(lsb)\n\t\t}\n\t}\n\n\t// Combine extract expressions if they are contiguous.\n\tif msb, ok := msb.(*ExtractExpr); ok {\n\t\tif lsb, ok := lsb.(*ExtractExpr); ok {\n\t\t\tif msb.Expr == lsb.Expr && lsb.Offset+lsb.Width == msb.Offset {\n\t\t\t\treturn NewExtractExpr(msb.Expr, lsb.Offset, msb.Width+lsb.Width)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &ConcatExpr{\n\t\tMSB: msb,\n\t\tLSB: lsb,\n\t}\n}", "func gfAdd(a, b gfElement) gfElement {\n\treturn a ^ b\n}", "func QuantizedConcat(scope *Scope, concat_dim tf.Output, values []tf.Output, input_mins []tf.Output, input_maxes []tf.Output) (output tf.Output, output_min tf.Output, output_max tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"QuantizedConcat\",\n\t\tInput: []tf.Input{\n\t\t\tconcat_dim, tf.OutputList(values), tf.OutputList(input_mins), tf.OutputList(input_maxes),\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0), op.Output(1), op.Output(2)\n}", "func Concat(size int, arrays ...[]byte) ([]byte, error) {\n\tarr := make([]byte, size)\n\ti := 0\n\tfor _, array := range arrays {\n\t\tfor _, b := range array {\n\t\t\tarr[i] = b\n\t\t\ti++\n\t\t}\n\t}\n\tif i != size {\n\t\treturn nil, fmt.Errorf(\"size argument does not match %d vs %d\", size, i)\n\t}\n\treturn arr, nil\n}", "func (t Text) Concat(v interface{}) (interface{}, error) {\n\tswitch rhs := v.(type) {\n\tcase string:\n\t\treturn Text(append(t, Segment{Text: rhs})), nil\n\tcase *Segment:\n\t\treturn Text(append(t, *rhs)), nil\n\tcase *Text:\n\t\treturn Text(append(t, *rhs...)), nil\n\t}\n\n\treturn nil, vals.ErrConcatNotImplemented\n}", "func (fn *formulaFuncs) concat(name string, argsList *list.List) formulaArg {\n\tbuf := bytes.Buffer{}\n\tfor arg := argsList.Front(); arg != nil; arg = arg.Next() {\n\t\ttoken := arg.Value.(formulaArg)\n\t\tswitch token.Type {\n\t\tcase ArgString:\n\t\t\tbuf.WriteString(token.String)\n\t\tcase ArgNumber:\n\t\t\tif token.Boolean {\n\t\t\t\tif token.Number == 0 {\n\t\t\t\t\tbuf.WriteString(\"FALSE\")\n\t\t\t\t} else {\n\t\t\t\t\tbuf.WriteString(\"TRUE\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbuf.WriteString(token.Value())\n\t\t\t}\n\t\tdefault:\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires arguments to be strings\", name))\n\t\t}\n\t}\n\treturn newStringFormulaArg(buf.String())\n}", "func Accum(s string) string {\n\tvar result []string\n\tfor index, r := range s {\n\t\tstr := string(r)\n\t\tresult = append(result, strings.ToUpper(str)+strings.Repeat(strings.ToLower(str), index))\n\t}\n\treturn strings.Join(result, \"-\")\n}", "func combine(a, b string, xoffset, yoffset int) string {\n\taW, aH := size(a)\n\tbW, bH := size(b)\n\tmaxW := max(aW, bW+xoffset)\n\tmaxH := max(aH, bH+yoffset)\n\taMap := toMap(a, aW)\n\tbMap := toMap(b, bW)\n\tvar sb strings.Builder\n\tfor y := 0; y < maxH; y++ {\n\t\tfor x := 0; x < maxW; x++ {\n\t\t\tif get(bMap, x-xoffset, y-yoffset, bW, bH) == ' ' {\n\t\t\t\tsb.WriteRune(get(aMap, x, y, aW, aH))\n\t\t\t} else {\n\t\t\t\tsb.WriteRune(get(bMap, x-xoffset, y-yoffset, bW, bH))\n\t\t\t}\n\t\t}\n\t\tsb.WriteRune('\\n')\n\t}\n\treturn sb.String()\n}", "func newIndexedConcat() concat {\n\tnl := []byte{byte('\\n')}\n\treturn concat{\n\t\tjoin: func(element store.Element) ([]byte, error) {\n\t\t\tb, err := Concat(len(element.Value)+len(nl), element.Value, nl)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not serialize value %w\", err)\n\t\t\t}\n\t\t\treturn b, nil\n\t\t},\n\t\tsplit: func(key store.Key, data []byte) (store.Element, error) {\n\t\t\tn := len(data) - len(nl)\n\t\t\treturn store.NewElement(key, data[0:n]), nil\n\t\t},\n\t}\n}", "func (b *Bag) union(c Bag) Bag {\n\tbag := make(Bag)\n\tfor k, v := range *b {\n\t\tbag[k] += v\n\t}\n\tfor k, v := range c {\n\t\tbag[k] += v\n\t}\n\treturn bag\n}", "func PADDSB(mx, x operand.Op) { ctx.PADDSB(mx, x) }", "func (array Array) Concat(others ...Array) Array {\n\tconcatenatedArray := array\n\tfor _, other := range others {\n\t\tconcatenatedArray = concatenatedArray.Push(other...)\n\t}\n\treturn concatenatedArray\n}", "func (v Variant) Concat() string {\n\tvar output string\n\toutput = fmt.Sprintf(\"%s:%d%s>%s\", v.chrom, v.pos, v.ref, v.alt)\n\treturn output\n}", "func appendMessageCodeword(word uint32) uint32 {\n\treturn calcBchAndParity(word | 1<<31)\n}", "func allCombinationsToBuildString(s string, vocabulary []string) [][]string {\n\tvar dp [][][]string\n\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tsubString := s[i:nextIndex]\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tif subString == w {\n\t\t\t\t\tfor _, comb := range dp[i] {\n\t\t\t\t\t\tupdatedComb := append(comb, w)\n\t\t\t\t\t\tdp[nextIndex] = append(dp[nextIndex], updatedComb)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func (this *WordDictionary) AddWord(word string) {\n\tvar nowChar *WordDictionary = this\n\tvar next *WordDictionary\n\tfor i, char := range word {\n\t\tcharIdx := char - a\n\t\tnext = nowChar.Nexts[charIdx]\n\t\tif next == nil {\n\t\t\twordDict := Constructor()\n\t\t\tnowChar.Nexts[charIdx] = &wordDict\n\t\t\tnext = &wordDict\n\t\t}\n\t\tnowChar = next\n\t\tif i == len(word)-1 {\n\t\t\tnowChar.HasTerminate = true\n\t\t}\n\t}\n}", "func Biunigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\tfor unigram := range toUnigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c\", unigram))\n\t}\n\n\treturn tokens\n}" ]
[ "0.6186775", "0.617156", "0.6004593", "0.58910674", "0.5868411", "0.5799477", "0.56004256", "0.5538303", "0.55113024", "0.54897165", "0.54454404", "0.54269725", "0.5422925", "0.5394519", "0.5383755", "0.53743744", "0.537224", "0.5281358", "0.5256899", "0.52460384", "0.52190584", "0.521481", "0.51885056", "0.51841205", "0.5165728", "0.515944", "0.51544124", "0.51410335", "0.512551", "0.5112585", "0.5066035", "0.5065455", "0.505207", "0.50467557", "0.5033298", "0.5023129", "0.4972718", "0.49710813", "0.49392483", "0.49324533", "0.4911729", "0.48892343", "0.48650858", "0.48200658", "0.4793022", "0.47429115", "0.4742293", "0.47419846", "0.47219956", "0.4704905", "0.4688745", "0.46755037", "0.46651724", "0.46392173", "0.4635393", "0.46351156", "0.4624945", "0.46222812", "0.4616228", "0.45961794", "0.45855385", "0.4576967", "0.45551613", "0.45535034", "0.45256087", "0.45055157", "0.44938332", "0.4473584", "0.4450541", "0.44496274", "0.44472718", "0.44394577", "0.4422292", "0.4422039", "0.4419816", "0.4419223", "0.4417288", "0.43839285", "0.4378745", "0.43784195", "0.43756127", "0.43652844", "0.43608138", "0.43492067", "0.43332684", "0.43268242", "0.43231988", "0.4310473", "0.43053672", "0.43041572", "0.4303588", "0.4295604", "0.42941043", "0.4289425", "0.4276661", "0.42729005", "0.426218", "0.42609555", "0.42596373", "0.42595643" ]
0.7001356
0
bigramWordByJoin concatenates adjecent pairs of string by using strings.Join function.
func bigramWordByJoin(str string) []string { ss := strings.Split(str, " ") // Handle unexpected string input: // ss = "" => []string{""} // ss = "foobar" => []string{"foobar"} if len(ss) <= 1 { return ss } bigram := make([]string, len(ss)-1) for i := 0; i < len(ss)-1; i++ { bigram[i] = strings.Join([]string{ss[i], ss[i+1]}, " ") } return bigram }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func bigramWordByAppend(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tvar tmp string\n\tvar bigram []string\n\tfor i, s := range ss {\n\t\tif i != 0 {\n\t\t\tbigram = append(bigram, strings.Join([]string{tmp, s}, \" \"))\n\t\t}\n\t\ttmp = s\n\t}\n\treturn bigram\n}", "func bigramWordByConcat(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\tbigram[i] = ss[i] + \" \" + ss[i+1]\n\t}\n\treturn bigram\n}", "func Join(words []string) string {\n\tvar buf bytes.Buffer\n\tfor i, w := range words {\n\t\tif i != 0 {\n\t\t\tbuf.WriteByte(' ')\n\t\t}\n\t\tbuf.WriteString(Escape(w))\n\t}\n\treturn buf.String()\n}", "func adjoin(strs []string, add string) []string {\n\tfor _, s := range strs {\n\t\tif s == add {\n\t\t\treturn strs\n\t\t}\n\t}\n\tstrs = append(strs, add)\n\treturn strs\n}", "func biGramCharByConcat(s string) []string {\n\tr := []rune(strings.Replace(s, \" \", \"\", -1))\n\t// Handle unexpected string input.\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(r) <= 1 {\n\t\treturn []string{string(r)}\n\t}\n\n\tlist := make([]string, len(r)-1)\n\tfor i := 0; i < len(r)-1; i++ {\n\t\tlist[i] = string(r[i : i+2])\n\t}\n\treturn list\n}", "func join(a string, b string, separator string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, separator...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func join(ins []rune, c rune) (result []string) {\n\tfor i := 0; i <= len(ins); i++ {\n\t\tresult = append(result, string(ins[:i])+string(c)+string(ins[i:]))\n\t}\n\treturn\n}", "func NormalizeJoin(l []string, d, f string) string {\n n := len(l)\n var s string\n for i, e := range l {\n if i > 0 {\n if n - (i + 1) == 0 {\n s += f\n }else{\n s += d\n }\n }\n s += e\n }\n return s\n}", "func join(sep string, a ...string) string {\n\tswitch len(a) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn a[0]\n\t}\n\n\tres := bytes.NewBufferString(a[0])\n\tfor _, s := range a[1:] {\n\t\tres.WriteString(sep + s)\n\t}\n\n\treturn res.String()\n}", "func spaceJoin(a string, b string) string {\n\treturn join(a, b, ` `)\n}", "func joinDemo(l []string, s string) string {\n\treturn strings.Join(l, s)\n}", "func join(str ...string) string {\n\tvar joined string\n\n\tfor n, s := range str {\n\t\tswitch n {\n\t\t\tcase 0: joined = s\n\t\t\tcase 1: joined = joined + \" \" + s\n\t\t\tdefault: joined = joined + \", \" + s\n\t\t}\n\t}\n\treturn joined\n}", "func JoinWordSeries(items []string) string {\n\tif len(items) == 0 {\n\t\treturn \"\"\n\t} else if len(items) == 1 {\n\t\treturn items[0]\n\t} else {\n\t\treturn strings.Join(items[:len(items)-1], \", \") + \", and \" + items[len(items)-1]\n\t}\n}", "func Join(sep string, strs ...string) string {\n\tswitch len(strs) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn strs[0]\n\tcase 2:\n\t\t// Special case for common small values.\n\t\t// Remove if golang.org/issue/6714 is fixed\n\t\treturn strs[0] + sep + strs[1]\n\tcase 3:\n\t\t// Special case for common small values.\n\t\t// Remove if golang.org/issue/6714 is fixed\n\t\treturn strs[0] + sep + strs[1] + sep + strs[2]\n\t}\n\tn := len(sep) * (len(strs) - 1)\n\tfor i := 0; i < len(strs); i++ {\n\t\tn += len(strs[i])\n\t}\n\n\tb := make([]byte, n)\n\tbp := copy(b, strs[0])\n\tfor _, s := range strs[1:] {\n\t\tbp += copy(b[bp:], sep)\n\t\tbp += copy(b[bp:], s)\n\t}\n\treturn string(b)\n}", "func Join(elem ...string) string {\n\treturn std.Join(elem...)\n}", "func textJoin(arg *list.Element, arr []string, ignoreEmpty bool) ([]string, formulaArg) {\n\tfor arg.Next(); arg != nil; arg = arg.Next() {\n\t\tswitch arg.Value.(formulaArg).Type {\n\t\tcase ArgError:\n\t\t\treturn arr, arg.Value.(formulaArg)\n\t\tcase ArgString, ArgEmpty:\n\t\t\tval := arg.Value.(formulaArg).Value()\n\t\t\tif val != \"\" || !ignoreEmpty {\n\t\t\t\tarr = append(arr, val)\n\t\t\t}\n\t\tcase ArgNumber:\n\t\t\tarr = append(arr, arg.Value.(formulaArg).Value())\n\t\tcase ArgMatrix:\n\t\t\tfor _, row := range arg.Value.(formulaArg).Matrix {\n\t\t\t\targList := list.New().Init()\n\t\t\t\tfor _, ele := range row {\n\t\t\t\t\targList.PushBack(ele)\n\t\t\t\t}\n\t\t\t\tif argList.Len() > 0 {\n\t\t\t\t\targs, _ := textJoin(argList.Front(), []string{}, ignoreEmpty)\n\t\t\t\t\tarr = append(arr, args...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn arr, newBoolFormulaArg(true)\n}", "func Join(s []string, sep string) string {\n\tvar buf string\n\tfor _, v := range s[:len(s)-1] {\n\t\tbuf += fmt.Sprintf(\"%s%s\", v, sep)\n\t}\n\n\tbuf += s[len(s)-1]\n\treturn buf\n}", "func mergeAlternately(word1 string, word2 string) string {\n\tvar buf bytes.Buffer\n\tfor i := range word1 {\n\t\tbuf.WriteByte(word1[i])\n\t\tif i < len(word2) {\n\t\t\tbuf.WriteByte(word2[i])\n\t\t}\n\t}\n\n\tif len(word1) < len(word2) {\n\t\tbuf.WriteString(word2[len(word1):])\n\t}\n\treturn buf.String()\n}", "func (m MultiString) Join(separator string) string {\n\treturn strings.Join(m, separator)\n}", "func JoinWords(w string, words ...string) (path string) {\n\tpath = w\n\tif path[0] != '/' {\n\t\tpath = \"/\" + path\n\t}\n\tfor _, s := range words {\n\t\tpath += \"/\" + s\n\t}\n\treturn\n}", "func biGramChar(str string) []string {\n\ts := strings.Replace(str, \" \", \"\", -1)\n\n\tif len(str) <= 1 {\n\t\treturn []string{str}\n\t}\n\n\tbigram := make([]string, len(s)-1)\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tbigram[i] = s[i : i+2]\n\t}\n\treturn bigram\n}", "func Join(sep string, operand []string) string { return strings.Join(operand, sep) }", "func BenchmarkStringsJoin(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = strings.Join(arr, \",\")\n\t}\n}", "func repeatJoin(a string, separator string, count int) string {\n\tif count == 0 {\n\t\treturn ``\n\t}\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tfor i := 1; i < count; i++ {\n\t\tvals = append(vals, separator...)\n\t\tvals = append(vals, a...)\n\t}\n\treturn string(vals)\n}", "func StringJoin(a []string, sep string) string { return strings.Join(a, sep) }", "func (c StringArrayCollection) Join(delimiter string) string {\n\ts := \"\"\n\tfor i := 0; i < len(c.value); i++ {\n\t\tif i != len(c.value)-1 {\n\t\t\ts += c.value[i] + delimiter\n\t\t} else {\n\t\t\ts += c.value[i]\n\t\t}\n\t}\n\treturn s\n}", "func Join(sep string, strs ...string) string {\n\tvar buf bytes.Buffer\n\tif len(strs) == 0 {\n\t\treturn \"\"\n\t}\n\tfor _, str := range strs {\n\t\tbuf.WriteString(str + sep)\n\t}\n\treturn strings.TrimRight(buf.String(), sep)\n}", "func spaceJoins(values ...string) string {\n\tif len(values) == 0 {\n\t\treturn ``\n\t}\n\tvals := make([]byte, 0, 10)\n\tfor index, val := range values {\n\t\tif index == 0 {\n\t\t\tvals = append(vals, val...)\n\t\t} else {\n\t\t\tvals = append(vals, ' ')\n\t\t\tvals = append(vals, val...)\n\t\t}\n\t}\n\treturn string(vals)\n}", "func bigramWordByCopy(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\t// Counts the length of primary and secondary words and whitespace\n\t\t// and copy it to the element of slice.\n\t\tbigram[i] = str[:(len(ss[i])+1)+len(ss[i+1])]\n\t\t// Drop the primary word and whitespace.\n\t\tstr = str[len(ss[i])+1:]\n\t}\n\treturn bigram\n}", "func largestMerge(word1 string, word2 string) string {\n\tvar i, j int\n\tans := make([]byte, 0, len(word1)+len(word2))\n\tfor i < len(word1) && j < len(word2) {\n\t\tcomp := strings.Compare(word1[i:], word2[j:])\n\t\tif comp > 0 {\n\t\t\tans = append(ans, word1[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tans = append(ans, word2[j])\n\t\t\tj++\n\t\t}\n\t}\n\tfor i < len(word1) {\n\t\tans = append(ans, word1[i])\n\t\ti++\n\t}\n\tfor j < len(word2) {\n\t\tans = append(ans, word2[j])\n\t\tj++\n\t}\n\treturn string(ans)\n}", "func JoinStrings(separator string, stringArray ...string) string {\n\n\tvar buffer bytes.Buffer\n\tvar max int = len(stringArray) - 1\n\tfor vi, v := range stringArray {\n\t\tbuffer.WriteString(v)\n\t\tif vi < max {\n\t\t\tbuffer.WriteString(separator)\n\t\t}\n\t}\n\treturn buffer.String()\n\n}", "func JoinStringsReversed(separator string, stringArray ...string) string {\n\n\tvar buffer bytes.Buffer\n\n\tfor vi := len(stringArray) - 1; vi >= 0; vi-- {\n\t\tbuffer.WriteString(stringArray[vi])\n\t\tif vi > 0 {\n\t\t\tbuffer.WriteString(separator)\n\t\t}\n\t}\n\n\treturn buffer.String()\n\n}", "func prefixJoin(prefix string, array []string, separator string) (result string) {\n\tif len(array) == 0 {\n\t\treturn\n\t}\n\tfor index, val := range array {\n\t\tif index == 0 {\n\t\t\tresult = val\n\t\t} else {\n\t\t\tresult = join(result, concat(prefix, val), separator)\n\t\t}\n\t}\n\treturn\n}", "func allCombinationsToBuildString(s string, vocabulary []string) [][]string {\n\tvar dp [][][]string\n\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tsubString := s[i:nextIndex]\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tif subString == w {\n\t\t\t\t\tfor _, comb := range dp[i] {\n\t\t\t\t\t\tupdatedComb := append(comb, w)\n\t\t\t\t\t\tdp[nextIndex] = append(dp[nextIndex], updatedComb)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func joinAlleles(alleles AlleleResult) string {\n\tkeys := make([]string, 0, len(alleles))\n\tfor k := range alleles {\n\t\tkeys = append(keys, k)\n\t}\n\treturn strings.Join(keys, \",\")\n}", "func join(elems ...string) string {\n\tvar result string\n\tfor i, v := range elems {\n\t\tif len(v) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif i == 0 {\n\t\t\tresult = strings.TrimRight(v, \"/\")\n\t\t\tcontinue\n\t\t}\n\t\tresult += \"/\" + strings.Trim(v, \"/\")\n\t}\n\treturn result\n}", "func JoinToMaxLength(toJoin []string, sep string, maxLength int) []string {\n\tvar out []string\n\n\tcurBuilder := strings.Builder{}\n\tcurBuilder.Grow(maxLength)\n\n\tfor _, s := range toJoin {\n\t\tentryLen := len(s)\n\t\tif curBuilder.Len() == 0 && entryLen > maxLength {\n\t\t\tout = append(out, s)\n\t\t\tcontinue\n\t\t}\n\n\t\tif curBuilder.Len() > 0 && curBuilder.Len()+len(sep)+entryLen > maxLength {\n\t\t\tout = append(out, curBuilder.String())\n\t\t\tcurBuilder.Reset()\n\t\t}\n\n\t\tif curBuilder.Len() != 0 {\n\t\t\tcurBuilder.WriteString(sep)\n\t\t}\n\n\t\tcurBuilder.WriteString(s)\n\t}\n\n\tif curBuilder.Len() > 0 {\n\t\tout = append(out, curBuilder.String())\n\t}\n\n\treturn out\n}", "func (lss *ListStrings) Join(lsep string, ssep string) (s string) {\n\tlsslen := len(*lss) - 1\n\n\tfor x, ls := range *lss {\n\t\ts += strings.Join(ls, ssep)\n\n\t\tif x < lsslen {\n\t\t\ts += lsep\n\t\t}\n\t}\n\treturn\n}", "func Biunigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\tfor unigram := range toUnigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c\", unigram))\n\t}\n\n\treturn tokens\n}", "func Biunigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\tfor unigram := range toUnigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c\", unigram))\n\t}\n\n\treturn tokens\n}", "func QuoteJoin(elems []string, sep string) string {\n\tswitch len(elems) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn elems[0]\n\t}\n\tn := len(sep) * (len(elems) - 1)\n\tfor i := 0; i < len(elems); i++ {\n\t\tn += len(elems[i]) + 2\n\t}\n\n\tvar b strings.Builder\n\tb.Grow(n)\n\tb.WriteByte('\"')\n\tb.WriteString(elems[0])\n\tb.WriteByte('\"')\n\tfor _, s := range elems[1:] {\n\t\tb.WriteString(sep)\n\t\tb.WriteByte('\"')\n\t\tb.WriteString(s)\n\t\tb.WriteByte('\"')\n\t}\n\treturn b.String()\n}", "func SliceJoin(a []Stringer, sep string) string {\n\tswitch len(a) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn a[0].String()\n\tcase 2:\n\t\t// Special case for common small values.\n\t\t// Remove if golang.org/issue/6714 is fixed\n\t\treturn a[0].String() + sep + a[1].String()\n\tcase 3:\n\t\t// Special case for common small values.\n\t\t// Remove if golang.org/issue/6714 is fixed\n\t\treturn a[0].String() + sep + a[1].String() + sep + a[2].String()\n\t}\n\tn := len(sep) * (len(a) - 1)\n\tfor i := 0; i < len(a); i++ {\n\t\tn += len(a[i].String())\n\t}\n\n\tb := make([]byte, n)\n\tbp := copy(b, a[0].String())\n\tfor _, s := range a[1:] {\n\t\tbp += copy(b[bp:], sep)\n\t\tbp += copy(b[bp:], s.String())\n\t}\n\treturn string(b)\n}", "func joinLeft(g []string) string {\n\tif g == nil || len(g) == 0 {\n\t\treturn \"\"\n\t}\n\tvar bf bytes.Buffer\n\tfor i := range g {\n\t\tc := strings.Index(g[i], \"#\")\n\t\tif c == -1 {\n\t\t\tbf.WriteString(g[i])\n\t\t} else {\n\t\t\tbf.WriteString(g[i][0:c])\n\t\t\tbreak\n\t\t}\n\t}\n\treturn string(bf.Bytes())\n}", "func QuotedJoin(terms []string, conjunction, none string) string {\n\tswitch len(terms) {\n\tcase 0:\n\t\treturn none\n\tcase 1:\n\t\treturn fmt.Sprintf(\"%q\", terms[0])\n\tcase 2:\n\t\treturn fmt.Sprintf(\"%q %s %q\", terms[0], conjunction, terms[1])\n\tdefault:\n\t\ti := 1\n\t\tinner := \"\"\n\t\tfor ; i < len(terms)-1; i++ {\n\t\t\tinner = fmt.Sprintf(\"%s, %q\", inner, terms[i])\n\t\t}\n\t\t// first, inner, inner, and/or last\n\t\treturn fmt.Sprintf(\"%q%s, %s %q\", terms[0], inner, conjunction, terms[i])\n\t}\n}", "func Join(a []string, sep string) string {\n\treturn strings.Join(a, sep)\n}", "func StringerJoin(elems []interface{ String() string }, sep string) string {\n\tswitch len(elems) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn elems[0].String()\n\t}\n\tn := len(sep) * (len(elems) - 1)\n\tfor i := 0; i < len(elems); i++ {\n\t\tn += len(elems[i].String())\n\t}\n\n\tvar b strings.Builder\n\tb.Grow(n)\n\tb.WriteString(elems[0].String())\n\tfor _, s := range elems[1:] {\n\t\tb.WriteString(sep)\n\t\tb.WriteString(s.String())\n\t}\n\treturn b.String()\n}", "func ShellJoin(args ...string) string {\n\tvar buf bytes.Buffer\n\tfor i, arg := range args {\n\t\tif i != 0 {\n\t\t\tbuf.WriteByte(' ')\n\t\t}\n\t\tquote(arg, &buf)\n\t}\n\treturn buf.String()\n}", "func RepeatJoin(s string, count int, sep string) string {\n\tif s == \"\" || count == 0 {\n\t\treturn \"\"\n\t}\n\tif count == 1 {\n\t\treturn s\n\t}\n\n\tvar b strings.Builder\n\tb.Grow(len(s)*count + len(sep)*(count-1))\n\tfor i := 0; i < count; i++ {\n\t\tb.WriteString(s)\n\t\tif i < count-1 {\n\t\t\tb.WriteString(sep)\n\t\t}\n\t}\n\n\treturn b.String()\n}", "func combine(str1, str2 string) string {\n\tvar res string\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\t//mark the number of same chars\n\tvar sameNum int = 0\n\tfor len1 > 0 && sameNum < len2 {\n\t\tif str1[len1-1] == str2[sameNum] {\n\t\t\tlen1--\n\t\t\tsameNum++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\t//combine str1 and str2\n\tres = str1[0:len1] + str2[sameNum:len2]\n\treturn res\n\n}", "func join(prefix, suffix string) string {\n\tif prefix == \"/\" {\n\t\treturn suffix\n\t}\n\tif suffix == \"/\" {\n\t\treturn prefix\n\t}\n\treturn prefix + suffix\n}", "func JoinGenerator(sep string, mapping func(s string) string) func(r string) string {\n\tvar written bool\n\treturn func(s string) string {\n\t\tif mapping != nil {\n\t\t\ts = mapping(s)\n\t\t}\n\t\tif written {\n\t\t\ts = sep + s\n\t\t}\n\t\twritten = true\n\t\treturn s\n\t}\n}", "func (fn *formulaFuncs) TEXTJOIN(argsList *list.List) formulaArg {\n\tif argsList.Len() < 3 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"TEXTJOIN requires at least 3 arguments\")\n\t}\n\tif argsList.Len() > 252 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"TEXTJOIN accepts at most 252 arguments\")\n\t}\n\tdelimiter := argsList.Front().Value.(formulaArg)\n\tignoreEmpty := argsList.Front().Next().Value.(formulaArg)\n\tif ignoreEmpty.Type != ArgNumber || !ignoreEmpty.Boolean {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n\t}\n\targs, ok := textJoin(argsList.Front().Next().Next(), []string{}, ignoreEmpty.Number != 0)\n\tif ok.Type != ArgNumber {\n\t\treturn ok\n\t}\n\tresult := strings.Join(args, delimiter.Value())\n\tif len(result) > TotalCellChars {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"TEXTJOIN function exceeds %d characters\", TotalCellChars))\n\t}\n\treturn newStringFormulaArg(result)\n}", "func joinStrings(sep string, a ...interface{}) (o string) {\n\tfor i := range a {\n\t\to += fmt.Sprint(a[i])\n\t\tif i < len(a)-1 {\n\t\t\to += sep\n\t\t}\n\t}\n\treturn\n}", "func StringJoin(scope *Scope, inputs []tf.Output, optional ...StringJoinAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"StringJoin\",\n\t\tInput: []tf.Input{\n\t\t\ttf.OutputList(inputs),\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func joins(sep string, inputs Inputs) (string, error) {\n\tvar buf bytes.Buffer\n\tvar errJoin error\n\tfirst := true\n\tinputs(func(v interface{}) {\n\t\tif errJoin != nil {\n\t\t\treturn\n\t\t}\n\t\tif s, ok := v.(string); ok {\n\t\t\tif first {\n\t\t\t\tfirst = false\n\t\t\t} else {\n\t\t\t\tbuf.WriteString(sep)\n\t\t\t}\n\t\t\tbuf.WriteString(s)\n\t\t} else {\n\t\t\terrJoin = fmt.Errorf(\"join wants string input, got %s\", vals.Kind(v))\n\t\t}\n\t})\n\treturn buf.String(), errJoin\n}", "func Of(s ...string) string { return strings.Join(s, \" \") }", "func Bigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\n\treturn tokens\n}", "func Bigrams(s string) []string {\n\ttokens := make([]string, 0, 32)\n\n\tfor bigram := range toBigrams(s) {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%c%c\", bigram.a, bigram.b))\n\t}\n\n\treturn tokens\n}", "func concat(a string, b string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func (array Array) Join(separator string) string {\n\tstr := fmt.Sprint()\n\tfor i, v := range array {\n\t\tstr += fmt.Sprintf(\"%v\", v)\n\t\tif i != len(array) - 1 {\n\t\t\tstr += fmt.Sprintf(\"%s\", separator)\n\t\t}\n\t}\n\treturn str\n}", "func Concat(in []string) (rv string) {\n\n\tswitch len(in) {\n\n\tcase 0:\n\t\treturn \"\"\n\n\tcase 1:\n\t\treturn in[0]\n\n\tcase 2:\n\t\treturn in[0] + in[1]\n\n\tcase 3:\n\t\treturn in[0] + in[1] + in[2]\n\t}\n\n\tn := 0\n\n\tfor i := 0; i < len(in); i++ {\n\t\tn += len(in[i])\n\t}\n\n\tb := make([]byte, n)\n\n\tbp := copy(b, in[0])\n\n\tfor _, s := range in[1:] {\n\t\tbp += copy(b[bp:], s)\n\t}\n\n\treturn string(b)\n}", "func joinStrings(str ...string) string {\n\treturn strings.Join(str, \"\")\n}", "func union(a, b []string) [][]rune {\n\tm := make(map[string]bool)\n\tfor _, item := range a {\n\t\tm[item] = true\n\t}\n\tfor _, item := range b {\n\t\tif _, ok := m[item]; !ok {\n\t\t\ta = append(a, item)\n\t\t}\n\t}\n\n\t// Convert a to rune matrix (with x -> words and y -> characters)\n\tout := make([][]rune, len(a))\n\tfor i, word := range a {\n\t\tout[i] = []rune(word)\n\t}\n\treturn out\n}", "func Join(fs FileSystem, elem ...string) string {\n\tsep := string(fs.PathSeparator())\n\tfor i, e := range elem {\n\t\tif e != \"\" {\n\t\t\treturn filepath.Clean(strings.Join(elem[i:], sep))\n\t\t}\n\t}\n\treturn \"\"\n}", "func Join(k, v string) string {\n\treturn fmt.Sprintf(\"%s=%s\", k, v)\n}", "func (*Mysqlfs) Join(elem ...string) string {\n\treturn filepath.Join(elem...)\n}", "func waysToBuildString(s string, vocabulary []string) int {\n\tvar dp []int\n\tfor i := 0; i < len(s)+1; i++ {\n\t\tdp = append(dp, 0)\n\t}\n\tdp[0] = 1\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tsubString := s[i:nextIndex]\n\t\t\t\tif subString == w {\n\t\t\t\t\tdp[nextIndex] += dp[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func Test_Splitter_Join(t *testing.T) {\n\tgiven := bdd.Sentences().Golden()\n\n\tinput, gold := &struct {\n\t\tArr []string `yaml:\"arr\"`\n\t\tConn string `yaml:\"conn\"`\n\t}{}, &struct {\n\t\tStr string `yaml:\"str\"`\n\t}{}\n\n\tgiven(t, \"a set that equal %[input.arr]v\", func(when bdd.When, golden bdd.Golden) {\n\t\tgolden.Load(input, gold)\n\t\tset := input.Arr\n\n\t\twhen(\"sa := str.With(set) is called\", func(it bdd.It) {\n\t\t\tsa := str.With(set)\n\t\t\ttext := sa.Join(input.Conn).String()\n\n\t\t\tgolden.Update(func() interface{} {\n\t\t\t\tgold.Str = text\n\t\t\t\treturn gold\n\t\t\t})\n\n\t\t\tit(\"should have sa.Join(%[input.conn]q) equal to %[golden.str]q\", func(assert bdd.Assert) {\n\t\t\t\tassert.Equal(gold.Str, text)\n\t\t\t})\n\t\t})\n\t})\n}", "func Join(sep string, parts ...string) string {\n\treturn strings.Join(parts, sep)\n}", "func JoinString(array []string, slim string) string {\n\tstr := array[0]\n\tfor index, val := range array {\n\t\tif index != 0 {\n\t\t\tstr = fmt.Sprintf(\"%s%s%s\", str, slim, val)\n\t\t}\n\t}\n\treturn str\n}", "func permutations(w string) []string {\n\tif w == \"\" {\n\t\treturn []string{\" \"}\n\t}\n\tperms := []string{}\n\tfor i, r := range w {\n\t\tremain := w[:i] + w[i+1:]\n\t\t//fmt.Println(remain)\n\t\tfor _, result := range permutations(remain) {\n\t\t\tperms = append(perms, fmt.Sprintf(\"%c\", r)+result)\n\t\t}\n\t\t//perms = append(perms, fmt.Sprintf(\"%c\\n\", r))\n\t}\n\treturn perms\n}", "func join(fields []string) string {\n\tvar b strings.Builder\n\tc := csv.NewWriter(&b)\n\terr := c.Write(fields)\n\tif err != nil {\n\t\tpanic(err) // this ideally shouldn't happen!\n\t}\n\tc.Flush()\n\treturn strings.TrimSpace(b.String())\n}", "func groupAnagramsOptimal(strs []string) [][]string {\n result := make([][]string, 0)\n\n if len(strs) == 0 {\n return result\n }\n\n tracker := make(map[string][]string)\n\n for _, s := range strs {\n count := make([]int, 26)\n for _, char := range s {\n count[char - 'a']++\n }\n\n sb := \"\"\n for i := 0; i < 26; i++ {\n sb += \"#\"\n sb += string(count[i])\n }\n\n tracker[sb] = append(tracker[sb], s)\n }\n\n for _, val := range tracker {\n result = append(result, val)\n }\n\n return result\n}", "func groupAnagrams(strs []string) [][]string {\n var result [][]string\n if len(strs)==0{\n return result\n }\n resultMap := make(map[string][]string)\n count := make([]string,26)\n for _, str := range strs{\n fillArrayWithZero(count)\n for _, c := range str{\n val := count[c-'a']\n iVal,_ := strconv.Atoi(val)\n count[c-'a']=strconv.Itoa(iVal+1) \n }\n key :=strings.Join(count,\"\")\n resultMap[key]=append(resultMap[key], str) \n }\n for _,val := range resultMap{\n result = append(result, val)\n }\n return result\n}", "func (nGramMap NGramMap) CombineDistinctiveNGrams(words []string, maxN int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tfor i := 2; i <= maxN; i++ {\n\t\terr := nGramMap.addDistinctiveNGrams(words, i, distinctiveWords, threshold)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func GroupAnagrams(strs []string) [][]string {\n groups := [][]string{}\n strHash := map[string][]string{}\n for _, str := range strs {\n sArr := strings.Split(str, \"\"); sort.Strings(sArr); s := strings.Join(sArr, \"\")\n if _, ok := strHash[s]; !ok { strHash[s] = []string{} }\n strHash[s] = append(strHash[s], str)\n }\n for _, sArr := range strHash {\n groups = append(groups, sArr)\n }\n return groups\n}", "func (sc SameCaseConvention) Join(names []string) string {\n\treturn strings.Join(names, \"\")\n}", "func JoinString(arr []string, delimiter string) string {\n\treturn strings.Join(arr, delimiter)\n}", "func Concat(input []string) string {\n\treturn strings.Join(input, \" \")\n}", "func ConcatString(left []string, right []string) []string {\n\tresult := make([]string, 0)\n\tresult = append(result, left...)\n\tresult = append(result, right...)\n\treturn result\n}", "func (o Operator) Join(arr []string) string {\n\tvar str string\n\n\tswitch o {\n\tcase \"/\":\n\t\tfor i, v := range arr {\n\t\t\tif v[:1] != \"{\" {\n\t\t\t\tarr[i] = \"/\" + v\n\t\t\t}\n\t\t}\n\t\tstr = filepath.Join(strings.Join(arr, \"\"))\n\n\tcase \"#\", \"?\", \".\", \";\", \"&\":\n\t\tm := opmap[o]\n\t\tfor i, v := range arr {\n\t\t\tif i > 0 && v[:1] != \"{\" {\n\t\t\t\tarr[i] = m[1] + v\n\t\t\t}\n\t\t}\n\t\tstr = m[0] + strings.Join(arr, \"\")\n\n\t\t// TODO revisit, not particularly pretty\n\t\tif str[:2] == \"&{\" {\n\t\t\tstr = str[1:] // remove extra &\n\t\t}\n\n\tdefault: // handles +, `{+var}` and blank, `{var}`\n\t\tstr = strings.Join(arr, \",\")\n\t}\n\n\treturn str\n}", "func Concatenate(strings ...string) string {\n\n\tfinalStr := \"\"\n\n\tfor _, str := range strings {\n\t\tfinalStr = finalStr + str\n\t}\n\treturn finalStr\n\n}", "func Join[T any](tt []T) string {\n\tvar str []string\n\tfor _, t := range tt {\n\t\tstr = append(str, fmt.Sprintf(\"%v\", t))\n\t}\n\n\treturn strings.Join(str, \", \")\n}", "func funcLabelJoin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\tvar (\n\t\tvector = vals[0].(Vector)\n\t\tdst = stringFromArg(args[1])\n\t\tsep = stringFromArg(args[2])\n\t\tsrcLabels = make([]string, len(args)-3)\n\t)\n\n\tif enh.Dmn == nil {\n\t\tenh.Dmn = make(map[uint64]labels.Labels, len(enh.Out))\n\t}\n\n\tfor i := 3; i < len(args); i++ {\n\t\tsrc := stringFromArg(args[i])\n\t\tif !model.LabelName(src).IsValid() {\n\t\t\tpanic(fmt.Errorf(\"invalid source label name in label_join(): %s\", src))\n\t\t}\n\t\tsrcLabels[i-3] = src\n\t}\n\n\tif !model.LabelName(dst).IsValid() {\n\t\tpanic(fmt.Errorf(\"invalid destination label name in label_join(): %s\", dst))\n\t}\n\n\tsrcVals := make([]string, len(srcLabels))\n\tfor _, el := range vector {\n\t\th := el.Metric.Hash()\n\t\tvar outMetric labels.Labels\n\t\tif l, ok := enh.Dmn[h]; ok {\n\t\t\toutMetric = l\n\t\t} else {\n\n\t\t\tfor i, src := range srcLabels {\n\t\t\t\tsrcVals[i] = el.Metric.Get(src)\n\t\t\t}\n\n\t\t\tlb := labels.NewBuilder(el.Metric)\n\n\t\t\tstrval := strings.Join(srcVals, sep)\n\t\t\tif strval == \"\" {\n\t\t\t\tlb.Del(dst)\n\t\t\t} else {\n\t\t\t\tlb.Set(dst, strval)\n\t\t\t}\n\n\t\t\toutMetric = lb.Labels()\n\t\t\tenh.Dmn[h] = outMetric\n\t\t}\n\n\t\tenh.Out = append(enh.Out, Sample{\n\t\t\tMetric: outMetric,\n\t\t\tF: el.F,\n\t\t\tH: el.H,\n\t\t})\n\t}\n\treturn enh.Out\n}", "func (lc LowerCaseConvention) Join(names []string) string {\n\treturn strings.Join(names, \"\")\n}", "func JoinStrings(ss ...string) string {\n\treturn strings.Join(ss, \"\")\n}", "func (g *Generator) mapToAssociations() string {\n\tvar output string\n\tvar blockSize int\n\tfor _, runeValue := range g.converted {\n\t\tblockSize = len(librarian.Associations[string(runeValue)])\n\t\tif blockSize > 0 {\n\t\t\toutput = output + librarian.Associations[string(runeValue)][helpers.Random(blockSize)]\n\t\t} else {\n\t\t\toutput = output + string(runeValue)\n\t\t}\n\t}\n\n\treturn output\n}", "func (m *Map) ReduceString(\n\treduce func(map[interface{}]interface{}) string,\n\tjoin func(x, y string) string,\n) string {\n\tsplits := m.splits\n\t// NewMap ensures that len(splits) > 0\n\tresult := splits[0].reduceString(reduce)\n\tfor i := 1; i < len(splits); i++ {\n\t\tresult = join(result, splits[i].reduceString(reduce))\n\t}\n\treturn result\n}", "func JoinWithDot(ks []string) string { return strings.Join(ks, \".\") }", "func trimSpaceAndJoin(args []string, sep string) string {\n\ttrimmedArgs := make([]string, len(args))\n\tfor i, arg := range args {\n\t\ttrimmedArgs[i] = strings.TrimSpace(arg)\n\t}\n\treturn strings.TrimSpace(strings.Join(trimmedArgs, sep))\n}", "func AlienDictonary(words []string) {\n\tdict := make(map[string][]string)\n\tfor i := 0; i < len(words); i++ {\n\t\tcurrent := string(words[i])\n\t\tfor j := 0; j < len(current); j++ {\n\t\t\t_, found := dict[string(current[j])]\n\t\t\tif !found {\n\t\t\t\tdict[string(current[j])] = []string{}\n\t\t\t}\n\n\t\t}\n\t}\n\tinEdges := make(map[string]int)\n\tfor key := range dict {\n\t\tinEdges[key] = 0\n\t}\n\tfor i := 1; i < len(words); i++ {\n\t\tfirst := words[i-1]\n\t\tsecond := words[i]\n\t\tl := int(math.Min(float64(len(first)), float64(len(second))))\n\t\tfor j := 0; j < l; j++ {\n\t\t\tif first[j] != second[j] {\n\t\t\t\tdict[string(first[j])] = append(dict[string(first[j])], string(second[j]))\n\t\t\t\tinEdges[string(second[j])]++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tq := []string{}\n\tfor key := range inEdges {\n\t\tif inEdges[key] == 0 {\n\t\t\tq = append(q, key)\n\t\t}\n\t}\n\tans := \"\"\n\tfor len(q) > 0 {\n\t\tremoved := q[0]\n\t\tq = q[1:]\n\t\tans += removed\n\t\tcurrent := dict[removed]\n\t\tfor i := 0; i < len(current); i++ {\n\t\t\tinEdges[string(current[i])]--\n\t\t\tif inEdges[string(current[i])] == 0 {\n\t\t\t\tq = append(q, string(current[i]))\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Println(ans)\n}", "func join(elem ...string) string {\n\tresult := path.Join(elem...)\n\tif result == \".\" {\n\t\treturn \"\"\n\t}\n\tif len(result) > 0 && result[0] == '/' {\n\t\tresult = result[1:]\n\t}\n\treturn result\n}", "func simpleJoin(dir, path string) string {\n\treturn dir + string(filepath.Separator) + path\n}", "func Join(paths ...string) string {\n\tunnormalized := make([]string, len(paths))\n\tfor i, path := range paths {\n\t\tunnormalized[i] = Unnormalize(path)\n\t}\n\tvalue := filepath.Join(unnormalized...)\n\tif value == \"\" {\n\t\treturn \"\"\n\t}\n\treturn Normalize(value)\n}", "func joinIDs(ids []WKID, separator string) string {\n\tvar s string\n\n\tfor i, n := range ids {\n\t\tif i != 0 {\n\t\t\ts += \",\"\n\t\t}\n\n\t\ts += strconv.FormatInt(int64(n), 10)\n\t}\n\n\treturn s\n}", "func justify(text string, l int, even bool) string {\n\tt := strings.Trim(text, \" \\t\\n\")\n\td := l - len(t)\n\tif d == 0 {\n\t\treturn t // fit\n\t} else if d < 0 { // overfull box\n\t\treturn text + \"\\u25ae\"\n\t}\n\ts := strings.Fields(text)\n\tif len(s) == 1 {\n\t\treturn text\n\t}\n\tvar b bytes.Buffer\n\tW := 0 // length of all words\n\tfor _, w := range s {\n\t\tW += len(w)\n\t}\n\td = l - W // amount of WS to distribute\n\tws := d / (len(s) - 1)\n\tr := d - ws*(len(s)-1) + 1\n\tb.WriteString(s[0])\n\tif even {\n\t\tfor j := 1; j < r; j++ {\n\t\t\tfor i := 0; i < ws+1; i++ {\n\t\t\t\tb.WriteString(\" \")\n\t\t\t}\n\t\t\tb.WriteString(s[j])\n\t\t}\n\t\tfor j := r; j < len(s); j++ {\n\t\t\tfor i := 0; i < ws; i++ {\n\t\t\t\tb.WriteString(\" \")\n\t\t\t}\n\t\t\tb.WriteString(s[j])\n\t\t}\n\t} else {\n\t\tfor j := 1; j <= len(s)-r; j++ {\n\t\t\tfor i := 0; i < ws; i++ {\n\t\t\t\tb.WriteString(\" \")\n\t\t\t}\n\t\t\tb.WriteString(s[j])\n\t\t}\n\t\tfor j := len(s) - r + 1; j < len(s); j++ {\n\t\t\tfor i := 0; i < ws+1; i++ {\n\t\t\t\tb.WriteString(\" \")\n\t\t\t}\n\t\t\tb.WriteString(s[j])\n\t\t}\n\t}\n\treturn b.String()\n}", "func Concat(strings []string) string {\n\ts, sep := \"\", \"\"\n\tfor _, str := range strings {\n\t\ts += sep + str // NB: inefficient!\n\t\tsep = \" \"\n\t}\n\treturn s\n}", "func combineText(labelsList []string) string {\n\tbeforeLength := 0\n\tfor _, s := range labelsList {\n\t\tbeforeLength += len(s)\n\t}\n\n\ttext := crush(removeSubstrings(labelsList))\n\tif *v {\n\t\tfmt.Fprintf(os.Stderr, \"crushed %d bytes to become %d bytes\\n\", beforeLength, len(text))\n\t}\n\treturn text\n}", "func Join(parts ...[]byte) []byte {\n\tvar b bytes.Buffer\n\n\tvar lastIsNewLine bool\n\tfor _, p := range parts {\n\t\tif len(p) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif b.Len() != 0 {\n\t\t\tif !lastIsNewLine {\n\t\t\t\t_, _ = b.WriteString(\"\\n\")\n\t\t\t}\n\t\t\tb.WriteString(yamlSeparator)\n\t\t}\n\t\t_, _ = b.Write(p)\n\t\ts := string(p)\n\t\tlastIsNewLine = s[len(s)-1] == '\\n'\n\t}\n\n\treturn b.Bytes()\n}", "func groupAnagrams(strs []string) [][]string {\n\tvar set = make(map[[math.MaxUint8]int][]string)\n\tfor _, str := range strs {\n\t\tvar charSet = [math.MaxUint8]int{}\n\t\tfor _, letter := range []byte(str) {\n\t\t\tcharSet[letter]++\n\t\t}\n\t\tif _, ok := set[charSet]; !ok {\n\t\t\tset[charSet] = []string{str}\n\t\t} else {\n\t\t\tset[charSet] = append(set[charSet], str)\n\t\t}\n\t}\n\tres := make([][]string, 0, len(set))\n\tfor _, v := range set {\n\t\tres = append(res, v)\n\t}\n\treturn res\n}" ]
[ "0.66665906", "0.66610605", "0.61865735", "0.61223364", "0.60511523", "0.60123986", "0.59851575", "0.5955917", "0.58678406", "0.5808041", "0.57088685", "0.5674272", "0.56346524", "0.5621613", "0.55867535", "0.55749595", "0.5506919", "0.5492988", "0.5458885", "0.54253215", "0.5393998", "0.53889155", "0.5377006", "0.53657615", "0.53440833", "0.53254056", "0.5306214", "0.52818614", "0.5280572", "0.52791023", "0.5278813", "0.52635264", "0.5261144", "0.5260484", "0.5258045", "0.5220777", "0.5213072", "0.51959467", "0.5182348", "0.5182348", "0.5175063", "0.51654696", "0.51605594", "0.515427", "0.5132396", "0.5120804", "0.5092392", "0.5086907", "0.50855446", "0.50244975", "0.49908173", "0.49845576", "0.49815708", "0.49691573", "0.49631467", "0.49378932", "0.4936523", "0.4936523", "0.4920812", "0.49081808", "0.4904145", "0.48927456", "0.4870581", "0.48629022", "0.48556784", "0.48520207", "0.484412", "0.4832867", "0.4809657", "0.4803121", "0.4793773", "0.4787917", "0.47876957", "0.47855887", "0.47673947", "0.4756046", "0.4742605", "0.4737795", "0.47297245", "0.47249845", "0.4718787", "0.46998298", "0.4682751", "0.46653298", "0.46430284", "0.46425426", "0.4637755", "0.4632141", "0.46309596", "0.4614041", "0.46125802", "0.45926502", "0.45905554", "0.45849568", "0.45799667", "0.45676464", "0.45638818", "0.45582563", "0.4555142", "0.45486012" ]
0.7665968
0
bigramWordByAppend concatenates adjecent pairs of string by using variablelength array and append. Append creates new instance at each time when called, so it is high cost...
func bigramWordByAppend(str string) []string { ss := strings.Split(str, " ") // Handle unexpected string input: // ss = "" => []string{""} // ss = "foobar" => []string{"foobar"} if len(ss) <= 1 { return ss } var tmp string var bigram []string for i, s := range ss { if i != 0 { bigram = append(bigram, strings.Join([]string{tmp, s}, " ")) } tmp = s } return bigram }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func bigramWordByConcat(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\tbigram[i] = ss[i] + \" \" + ss[i+1]\n\t}\n\treturn bigram\n}", "func bigramWordByJoin(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\tbigram[i] = strings.Join([]string{ss[i], ss[i+1]}, \" \")\n\t}\n\treturn bigram\n}", "func concat(a string, b string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func (s Slice) Append(elems ...byte) Slice {\n\tif cap(s) < len(s)+len(elems) {\n\t\tslice := append(make([]byte, wordSize), append(s, elems...)...)\n\t\treturn slice[wordSize:]\n\t}\n\treturn append(s, elems...)\n}", "func append(arr1 []byte, arr2 []byte) []byte {\n\tarr1Len := len(arr1);\n\tnewLen := len(arr1) + len(arr2);\n\tresult := make([]byte, newLen);\n\t\n\tfor i:= 0; i < arr1Len; i++ {\n\t\tresult[i] = arr1[i];\n\t};\n\t\n\tfor i := 0; i < len(arr2); i++ {\n\t\tresult[i + arr1Len] = arr2[i];\n\t};\n\treturn result;\n}", "func bigramWordByCopy(str string) []string {\n\tss := strings.Split(str, \" \")\n\n\t// Handle unexpected string input:\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(ss) <= 1 {\n\t\treturn ss\n\t}\n\n\tbigram := make([]string, len(ss)-1)\n\tfor i := 0; i < len(ss)-1; i++ {\n\t\t// Counts the length of primary and secondary words and whitespace\n\t\t// and copy it to the element of slice.\n\t\tbigram[i] = str[:(len(ss[i])+1)+len(ss[i+1])]\n\t\t// Drop the primary word and whitespace.\n\t\tstr = str[len(ss[i])+1:]\n\t}\n\treturn bigram\n}", "func mergeAlternately(word1 string, word2 string) string {\n\tvar buf bytes.Buffer\n\tfor i := range word1 {\n\t\tbuf.WriteByte(word1[i])\n\t\tif i < len(word2) {\n\t\t\tbuf.WriteByte(word2[i])\n\t\t}\n\t}\n\n\tif len(word1) < len(word2) {\n\t\tbuf.WriteString(word2[len(word1):])\n\t}\n\treturn buf.String()\n}", "func TextAppend(l, r Term) Op {\n\treturn Op{OpCode: TextAppendOp, L: l, R: r}\n}", "func (b *Builder) append(data []byte) {\n\tdst := b.allocate(len(data))\n\ty.AssertTrue(len(data) == copy(dst, data))\n}", "func (nGramMap NGramMap) addDistinctiveNGrams(words []string, n int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tnGrams, err := createNGrams(words, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, gram := range nGrams {\n\t\tif gram.IsDistinctive(distinctiveWords, threshold) {\n\t\t\tnGramMap[gram.Key()]++\n\t\t}\n\t}\n\treturn nil\n}", "func multiAppend(slices ...[]byte) []byte {\n\tvar length int\n\tfor _, s := range slices {\n\t\tlength += len(s)\n\t}\n\ttmp := make([]byte, length)\n\tvar i int\n\tfor _, s := range slices {\n\t\ti += copy(tmp[i:], s)\n\t}\n\treturn tmp\n}", "func (nGramMap NGramMap) CombineDistinctiveNGrams(words []string, maxN int,\n\tdistinctiveWords map[string]int, threshold int) error {\n\tfor i := 2; i <= maxN; i++ {\n\t\terr := nGramMap.addDistinctiveNGrams(words, i, distinctiveWords, threshold)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func appendRepeat(buf []byte, s string, n int) []byte {\n\tfor i := 0; i < n; i++ {\n\t\tbuf = append(buf, s...)\n\t}\n\treturn buf\n}", "func appendString(dst, src []byte, encode bool) []byte {\n\tvar b []byte\n\tif !encode {\n\t\tb = src\n\t} else {\n\t\tb = bytePool.Get().([]byte)\n\t\tb = HuffmanEncode(b[:0], src)\n\t}\n\t// TODO: Encode only if length is lower with the string encoded\n\n\tn := uint64(len(b))\n\tnn := len(dst) - 1 // peek last byte\n\tif nn >= 0 && dst[nn] != 0 {\n\t\tdst = append(dst, 0)\n\t\tnn++\n\t}\n\tdst = appendInt(dst, 7, n)\n\tdst = append(dst, b...)\n\n\tif encode {\n\t\tbytePool.Put(b)\n\t\tdst[nn] |= 128 // setting H bit\n\t}\n\treturn dst\n}", "func (arr *Array) Append(v *Term) *Array {\n\tcpy := *arr\n\tcpy.elems = append(arr.elems, v)\n\tcpy.hashs = append(arr.hashs, v.Value.Hash())\n\tcpy.hash = arr.hash + v.Value.Hash()\n\tcpy.ground = arr.ground && v.IsGround()\n\treturn &cpy\n}", "func adjoin(strs []string, add string) []string {\n\tfor _, s := range strs {\n\t\tif s == add {\n\t\t\treturn strs\n\t\t}\n\t}\n\tstrs = append(strs, add)\n\treturn strs\n}", "func BenchmarkConcatStrByAdd(b *testing.B) {\n\telements := []string{ \"1\", \"2\", \"3\", \"4\" }\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tret := \"\"\n\t\tfor _, element := range elements {\n\t\t\tret += element\n\t\t}\n\t}\n\tb.StopTimer()\n}", "func biGramCharByConcat(s string) []string {\n\tr := []rune(strings.Replace(s, \" \", \"\", -1))\n\t// Handle unexpected string input.\n\t// ss = \"\" => []string{\"\"}\n\t// ss = \"foobar\" => []string{\"foobar\"}\n\tif len(r) <= 1 {\n\t\treturn []string{string(r)}\n\t}\n\n\tlist := make([]string, len(r)-1)\n\tfor i := 0; i < len(r)-1; i++ {\n\t\tlist[i] = string(r[i : i+2])\n\t}\n\treturn list\n}", "func testAppendStringToByteSlice() {\n\tfmt.Println(\"testAppendStringToByteSlice\")\n\ts := []byte(\"hello\")\n\ts = append(s, \" world\"...)\n\tfmt.Println(s)\n\tfmt.Println()\n}", "func addWord(root *TrieNode, word string, idx int) {\n for i := 0; i < len(word); i++ {\n if isPalindrome(word[i:]) {\n root.match[idx] = true\n }\n offset := word[i]-'a'\n if root.nodes[offset] == nil {\n root.nodes[offset] = &TrieNode{idx:-1, match: make(map[int]bool)} \n }\n root = root.nodes[offset]\n }\n root.idx = idx\n root.match[idx] = true // \"\" is the rest of any string, and is also a palindrome.\n}", "func TestAppendSplit(t *testing.T) {\n\ttests := []string{\n\t\t\"\",\n\t\t\"Hello, World\",\n\t\t\"Hello, 世界\",\n\t\tstrings.Repeat(\"Hello, 世界\", smallSize*2/len(\"Hello, 世界\")),\n\t}\n\tfor _, test := range tests {\n\t\tfor i := range test {\n\t\t\tr := Append(New(test[:i]), New(test[i:]))\n\t\t\tok := true\n\t\t\tif got := r.String(); got != test {\n\t\t\t\tt.Errorf(\"Append(%q, %q)=%q\", test[:i], test[i:], got)\n\t\t\t\tok = false\n\t\t\t}\n\t\t\tif r.Len() != int64(len(test)) {\n\t\t\t\tt.Errorf(\"Append(%q, %q).Len()=%d, want %d\",\n\t\t\t\t\ttest[:i], test[i:], r.Len(), len(test))\n\t\t\t\tok = false\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor j := range test {\n\t\t\t\tleft, right := Split(r, int64(j))\n\t\t\t\tgotLeft := left.String()\n\t\t\t\tgotRight := right.String()\n\t\t\t\tif gotLeft != test[:j] || gotRight != test[j:] {\n\t\t\t\t\tt.Errorf(\"Split(Append(%q, %q))=%q,%q\",\n\t\t\t\t\t\ttest[:i], test[i:], gotLeft, gotRight)\n\t\t\t\t}\n\t\t\t\tif left.Len() != int64(j) {\n\t\t\t\t\tt.Errorf(\"Split(Append(%q, %q)).left.Len()=%d, want %d\",\n\t\t\t\t\t\ttest[:i], test[i:], left.Len(), j)\n\t\t\t\t}\n\t\t\t\tif right.Len() != int64(len(test)-j) {\n\t\t\t\t\tt.Errorf(\"Split(Append(%q, %q)).right.Len()=%d, want %d\",\n\t\t\t\t\t\ttest[:i], test[i:], right.Len(), len(test)-j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (ref Ref) Append(term *Term) Ref {\n\tn := len(ref)\n\tdst := make(Ref, n+1)\n\tcopy(dst, ref)\n\tdst[n] = term\n\treturn dst\n}", "func (f *bloomFilter) Append(buf *bytes.Buffer, keys [][]byte) {\n\tvar g bloomGenerator\n\tg.k = f.k\n\tg.bitsPerKey = f.bitsPerKey\n\tg.hashs = make([]uint32, 0, len(keys))\n\tfor _, k := range keys {\n\t\tg.Add(k)\n\t}\n\tg.Append(buf)\n}", "func append(href string) string {\n\tbuffer := new(bytes.Buffer)\n\tbuffer.WriteString(\"http://simple.wikipedia.org\")\n\tbuffer.WriteString(href)\n\treturn buffer.String()\n}", "func largestMerge(word1 string, word2 string) string {\n\tvar i, j int\n\tans := make([]byte, 0, len(word1)+len(word2))\n\tfor i < len(word1) && j < len(word2) {\n\t\tcomp := strings.Compare(word1[i:], word2[j:])\n\t\tif comp > 0 {\n\t\t\tans = append(ans, word1[i])\n\t\t\ti++\n\t\t} else {\n\t\t\tans = append(ans, word2[j])\n\t\t\tj++\n\t\t}\n\t}\n\tfor i < len(word1) {\n\t\tans = append(ans, word1[i])\n\t\ti++\n\t}\n\tfor j < len(word2) {\n\t\tans = append(ans, word2[j])\n\t\tj++\n\t}\n\treturn string(ans)\n}", "func TestAppend(t *T) {\n\t// Normal case\n\tintl := []interface{}{3, 2, 1}\n\tl := NewList(intl...)\n\tnl := l.Append(0)\n\tassertSaneList(l, t)\n\tassertSaneList(nl, t)\n\tassertSeqContents(l, intl, t)\n\tassertSeqContents(nl, []interface{}{3, 2, 1, 0}, t)\n\n\t// Edge case (algorithm gets weird here)\n\tl = NewList(1)\n\tnl = l.Append(0)\n\tassertSaneList(l, t)\n\tassertSaneList(nl, t)\n\tassertSeqContents(l, []interface{}{1}, t)\n\tassertSeqContents(nl, []interface{}{1, 0}, t)\n\n\t// Degenerate case\n\tl = NewList()\n\tnl = l.Append(0)\n\tassertEmpty(l, t)\n\tassertSaneList(nl, t)\n\tassertSeqContents(nl, []interface{}{0}, t)\n}", "func AppendRandomString(str *[]rune) {\n\tcharNum := 26\n\n\t// generate random string\n\tlength := rand.Intn(maxLen)\n\tfor i := 0; i < length; i++ {\n\t\tc := rune(int('a') + rand.Intn(charNum))\n\t\t*str = append(*str, c)\n\t}\n}", "func (w *BytesWriter) Append(args ...interface{}) {\r\n\tw.args = append(w.args, args...)\r\n}", "func (m *Markov) Add(sentence Sentence) {\n\tfor i := 0; i < len(sentence)-m.params.Ngram+1; i++ {\n\t\tmorphs := sentence[i : i+m.params.Ngram]\n\t\tm.learning.Add(morphs)\n\n\t\tif len(m.learning) >= m.params.ChainMorphsNum {\n\t\t\tm.shiftChain()\n\t\t}\n\t}\n}", "func (this *WordDictionary) AddWord(word string) {\n\tvar nowChar *WordDictionary = this\n\tvar next *WordDictionary\n\tfor i, char := range word {\n\t\tcharIdx := char - a\n\t\tnext = nowChar.Nexts[charIdx]\n\t\tif next == nil {\n\t\t\twordDict := Constructor()\n\t\t\tnowChar.Nexts[charIdx] = &wordDict\n\t\t\tnext = &wordDict\n\t\t}\n\t\tnowChar = next\n\t\tif i == len(word)-1 {\n\t\t\tnowChar.HasTerminate = true\n\t\t}\n\t}\n}", "func (w *Writer) Append(prog []byte, n int64)", "func appendString(x []string, y ...string) []string {\n\tvar z []string\n\tzlen := len(x) + len(y)\n\t// var z [zlen]string X: non-constant array bound zlen\n\t// expand z to at least zlen\n\tz = make([]string, zlen)\n\tcopy(z, x)\n\tcopy(z[len(x):], y)\n\treturn z\n}", "func groupAnagrams(strs []string) [][]string {\n var result [][]string\n if len(strs)==0{\n return result\n }\n resultMap := make(map[string][]string)\n count := make([]string,26)\n for _, str := range strs{\n fillArrayWithZero(count)\n for _, c := range str{\n val := count[c-'a']\n iVal,_ := strconv.Atoi(val)\n count[c-'a']=strconv.Itoa(iVal+1) \n }\n key :=strings.Join(count,\"\")\n resultMap[key]=append(resultMap[key], str) \n }\n for _,val := range resultMap{\n result = append(result, val)\n }\n return result\n}", "func Concat(in []string) (rv string) {\n\n\tswitch len(in) {\n\n\tcase 0:\n\t\treturn \"\"\n\n\tcase 1:\n\t\treturn in[0]\n\n\tcase 2:\n\t\treturn in[0] + in[1]\n\n\tcase 3:\n\t\treturn in[0] + in[1] + in[2]\n\t}\n\n\tn := 0\n\n\tfor i := 0; i < len(in); i++ {\n\t\tn += len(in[i])\n\t}\n\n\tb := make([]byte, n)\n\n\tbp := copy(b, in[0])\n\n\tfor _, s := range in[1:] {\n\t\tbp += copy(b[bp:], s)\n\t}\n\n\treturn string(b)\n}", "func (this *WordDictionary) AddWord(word string) {\n\tnode := this.root\n\tfor _, c := range word {\n\t\tif node.next[c-'a'] != nil {\n\t\t\tnode = node.next[c-'a']\n\t\t} else {\n\t\t\tnewNode := TrieNode{}\n\t\t\tnewNode.next = make([]*TrieNode, 26)\n\t\t\tnode.next[c-'a'] = &newNode\n\t\t\tnode = &newNode\n\t\t}\n\t}\n\tnode.finished = true\n}", "func (this *WordDictionary) AddWord(word string) {\n \n}", "func AppendR2B(dst []byte, r []rune) []byte {\n\treturn AppendRunesToBytes(dst, r)\n}", "func biGramChar(str string) []string {\n\ts := strings.Replace(str, \" \", \"\", -1)\n\n\tif len(str) <= 1 {\n\t\treturn []string{str}\n\t}\n\n\tbigram := make([]string, len(s)-1)\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tbigram[i] = s[i : i+2]\n\t}\n\treturn bigram\n}", "func groupAnagramsOptimal(strs []string) [][]string {\n result := make([][]string, 0)\n\n if len(strs) == 0 {\n return result\n }\n\n tracker := make(map[string][]string)\n\n for _, s := range strs {\n count := make([]int, 26)\n for _, char := range s {\n count[char - 'a']++\n }\n\n sb := \"\"\n for i := 0; i < 26; i++ {\n sb += \"#\"\n sb += string(count[i])\n }\n\n tracker[sb] = append(tracker[sb], s)\n }\n\n for _, val := range tracker {\n result = append(result, val)\n }\n\n return result\n}", "func Append(v1 Vector, v2 Vector) Vector {\n\tbaseDim := v1.Size()\n\tv1.dim = baseDim + v2.Size()\n\tfor n, d := range v2.data {\n\t\tv1.Set(baseDim+n, d)\n\t}\n\n\treturn v1\n}", "func (w *Writer) append(key, value []byte, restart bool) {\n\tnShared := 0\n\tif restart {\n\t\tw.restarts = append(w.restarts, uint32(w.buf.Len()))\n\t} else {\n\t\tnShared = db.SharedPrefixLen(w.prevKey, key)\n\t}\n\tw.prevKey = append(w.prevKey[:0], key...)\n\tw.nEntries++\n\tn := binary.PutUvarint(w.tmp[0:], uint64(nShared))\n\tn += binary.PutUvarint(w.tmp[n:], uint64(len(key)-nShared))\n\tn += binary.PutUvarint(w.tmp[n:], uint64(len(value)))\n\tw.buf.Write(w.tmp[:n])\n\tw.buf.Write(key[nShared:])\n\tw.buf.Write(value)\n}", "func Bvconcat(t []TermT) TermT {\n\tcount := C.uint32_t(len(t))\n\t//iam: FIXME need to unify the yices errors and the go errors...\n\tif count == 0 {\n\t\treturn NullTerm\n\t}\n\treturn TermT(C.yices_bvconcat(count, (*C.term_t)(&t[0])))\n}", "func ladderLength(beginWord string, endWord string, wordList []string) int {\n\tdict := make(map[string]bool) // 把word存入字典\n\tfor _, word := range wordList {\n\t\tdict[word] = true // 可以利用字典快速添加、删除和查找单词\n\t}\n\tif _, ok := dict[endWord]; !ok {\n\t\treturn 0\n\t}\n\t// queue := []string{beginWord} 定义辅助队列\n\tvar queue []string\n\tqueue = append(queue, beginWord)\n\n\tl := len(beginWord)\n\tsteps := 0\n\n\tfor len(queue) > 0 {\n\t\tsteps++\n\t\tsize := len(queue)\n\t\tfor i := size; i > 0; i-- { // 当前层级节点\n\t\t\ts := queue[0] // 原始单词\n\t\t\tqueue = queue[1:]\n\t\t\tchs := []rune(s)\n\t\t\tfor i := 0; i < l; i++ { // 对单词的每一位进行修改\n\t\t\t\tch := chs[i] // 对当前单词的一位\n\t\t\t\tfor c := 'a'; c <= 'z'; c++ { // 尝试从a-z\n\t\t\t\t\tif c == ch { // 跳过本身比如hot修改为hot\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tchs[i] = c\n\t\t\t\t\tt := string(chs)\n\t\t\t\t\tif t == endWord { // 找到结果\n\t\t\t\t\t\treturn steps + 1\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := dict[t]; !ok { // 不在dict中,跳过\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tdelete(dict, t) // 从字典中删除该单词,因为已经访问过,若重复访问路径一定不是最短的\n\t\t\t\t\tqueue = append(queue, t) // 将新的单词添加到队列\n\t\t\t\t}\n\t\t\t\tchs[i] = ch // 单词的第i位复位,再进行下面的操作\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func (self *Dll) Append(str string){\n\tnewNode := new(node)\n\tnewNode.data = str\n\tself.pushBack(newNode)\n}", "func (vb *Builder) Append(fieldName string, value string) {\n\tvb.Accumulated = append(vb.Accumulated, mapping{fieldName, value})\n}", "func (g String) append(str string) String {\n\tg.string += str\n\treturn g\n}", "func appendBuffer(elements []interface{}, buf *bytes.Buffer) ([]interface{}, *bytes.Buffer) {\n\tif buf.Len() > 0 {\n\t\ts, _ := NewStringElement(buf.String())\n\t\treturn append(elements, s), bytes.NewBuffer(nil)\n\t}\n\treturn elements, buf\n}", "func (b *Buffer) Append(p []byte) int {\n\tb.B = append(b.B, p...)\n\treturn len(p)\n}", "func main() {\n\ts1 := stringAppender(\"hoo\")\n\tfmt.Println(s1(\"woo\"))\n\n\ts2 := stringAppender(\"Orioles\")\n\tfmt.Println(s2(\"Baltimore \"))\n\n}", "func (s *BytesWriter) Append(args ...interface{}) {\n\ts.args = append(s.args, args...)\n}", "func (s *BytesWriter) Append(args ...interface{}) {\n\ts.args = append(s.args, args...)\n}", "func (this *WordDictionary) AddWord(word string) {\n\tp := &this.root\n\tfor i := 0; i < len(word); i++ {\n\t\tj := word[i] - 'a'\n\t\tif p.children[j] == nil {\n\t\t\tp.children[j] = new(trieNode)\n\t\t}\n\t\tp = p.children[j]\n\t}\n\tp.exist = true\n}", "func (b *Builder) append(data []byte) {\n\tdst := b.allocate(len(data))\n\tutils.AssertTrue(len(data) == copy(dst, data))\n\n\t/*\n\t\tif b.currentBlock == nil {\n\t\t\tb.currentBlock = &pb.Block{\n\t\t\t\tData: make([]byte, 64*KB),\n\t\t\t\t//BlockLength: uint32(size),\n\t\t\t}\n\t\t\tb.blocks = append(b.blocks, b.currentBlock)\n\t\t}\n\t\t// Ensure we have enough spa\t to store new data.\n\t\tif uint32(len(b.currentBlock.Data)) < b.sz+uint32(len(data)) {\n\t\t\tblockGrow(b.currentBlock, uint32(len(data)))\n\t\t}\n\n\t\tcopy(b.currentBlock.Data[b.sz:], data)\n\t\tb.sz += uint32(len(data))\n\t*/\n}", "func join(a string, b string, separator string) string {\n\tvals := make([]byte, 0, 10)\n\tvals = append(vals, a...)\n\tvals = append(vals, separator...)\n\tvals = append(vals, b...)\n\treturn string(vals)\n}", "func (w *tWriter) append(key, value []byte) error {\n\tif w.first == nil {\n\t\tw.first = append([]byte{}, key...)\n\t}\n\tw.last = append(w.last[:0], key...)\n\treturn w.tw.Append(key, value)\n}", "func (redisStore *RedisStore) AppendGob(uid string, data []byte) error {\n\tclient, err := redisStore.Get()\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Get gobInfo\n\treply := client.Cmd(\"GET\", gobInfoKey(uid))\n\tif reply.Err != nil {\n\t\treturn reply.Err\n\t}\n\tgobInfoBytes, _ := reply.Bytes()\n\tgobInfo, err := gobInfoDecode(gobInfoBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Append or set depending on if length of old + new data > MAX_LEN\n\tlength, err := getStrLen(client, gobKey(uid))\n\tif err != nil {\n\t\treturn err\n\t}\n\tlength += len(data)\n\tif length > MAX_LEN {\n\t\tgslog.Debug(\"REDIS: tuncating gob length %d MAX_LEN %d\", length, MAX_LEN)\n\t\treply := client.Cmd(\"GET\", gobKey(uid))\n\t\tif reply.Err != nil {\n\t\t\treturn reply.Err\n\t\t}\n\t\toldData, _ := reply.Bytes()\n\t\t// TODO: Best way to do this?\n\t\tdata = bytes.Join([][]byte{oldData[length-MAX_LEN : len(oldData)], data}, []byte{})\n\t\tif reply := client.Cmd(\"SET\", gobKey(uid), data); reply.Err != nil {\n\t\t\treturn reply.Err\n\t\t}\n\t} else {\n\t\tgslog.Debug(\"REDIS: appending gob length %d MAX_LEN %d\", length, MAX_LEN)\n\t\tif reply := client.Cmd(\"APPEND\", gobKey(uid), data); reply.Err != nil {\n\t\t\treturn reply.Err\n\t\t}\n\t}\n\tgo redisStore.setTTLRoutine(client, gobInfo, data)\n\treturn nil\n}", "func ConcatWord(a, b uint8) uint16 {\n\treturn (uint16(a) << 8) | uint16(b)\n}", "func TestAppend(t *T) {\n\t// Normal case\n\tintl := []interface{}{3, 2, 1}\n\tl := NewList(intl...)\n\tnl := l.Append(0)\n\tassertSaneList(l, t)\n\tassertSaneList(nl, t)\n\tassert.Equal(t, intl, ToSlice(l))\n\tassert.Equal(t, []interface{}{3, 2, 1, 0}, ToSlice(nl))\n\n\t// Edge case (algorithm gets weird here)\n\tl = NewList(1)\n\tnl = l.Append(0)\n\tassertSaneList(l, t)\n\tassertSaneList(nl, t)\n\tassert.Equal(t, []interface{}{1}, ToSlice(l))\n\tassert.Equal(t, []interface{}{1, 0}, ToSlice(nl))\n\n\t// Degenerate case\n\tl = NewList()\n\tnl = l.Append(0)\n\tassert.Equal(t, 0, Size(l))\n\tassertSaneList(nl, t)\n\tassert.Equal(t, []interface{}{0}, ToSlice(nl))\n}", "func newAltWords(h *RunList, i, j int) interface{} {\n\tcanon := h.At(i).(*wordPair).canon;\n\talts := make([]string, j-i);\n\tk := 0;\n\tfor ; i < j; i++ {\n\t\talts[k] = h.At(i).(*wordPair).alt;\n\t\tk++;\n\t}\n\treturn &AltWords{canon, alts};\n}", "func create_lists(words []string) ([676]wordlists, [676]wordlists) {\n sp := [676]wordlists{}\n ep := [676]wordlists{}\n\n // initialize list with start and end pair of literals\n for i:='a'; i<='z'; i++ {\n for j:='a'; j<='z'; j++ {\n sp[26*(i-'a') + (j-'a')].char = string(i) + string(j)\n ep[26*(i-'a') + (j-'a')].char = string(i) + string(j)\n }\n }\n\n var index uint16\n for i:=0; i<len(words); i++ {\n wlen := len(words[i])\n if wlen >= 2 {\n index = 26*(uint16(words[i][0])-'a') + (uint16(words[i][1])-'a')\n sp[index].word = append(sp[index].word, words[i])\n\n index = 26*(uint16(words[i][wlen-2])-'a') + (uint16(words[i][wlen-1])-'a')\n ep[index].word = append(ep[index].word, words[i])\n }\n }\n\n return sp, ep\n}", "func combineText(labelsList []string) string {\n\tbeforeLength := 0\n\tfor _, s := range labelsList {\n\t\tbeforeLength += len(s)\n\t}\n\n\ttext := crush(removeSubstrings(labelsList))\n\tif *v {\n\t\tfmt.Fprintf(os.Stderr, \"crushed %d bytes to become %d bytes\\n\", beforeLength, len(text))\n\t}\n\treturn text\n}", "func appendAndDelete(s string, t string, k int32) string {\n if int32(len(s) + len(t)) <= k {\n return \"Yes\"\n }\n i := 0\n for i < len(s) && i < len(t) && s[i] == t[i] {\n i++\n }\n ops := int32(len(s[i:]) + len(t[i:]))\n for j := i; j > 0; j-- {\n if int32(2*(i-j)) + ops == k {\n return \"Yes\"\n }\n }\n return \"No\"\n}", "func concat(args ...[]string) []string {\n\tvar buf []string\n\tfor _, arg := range args {\n\t\tbuf = append(buf, arg...)\n\t}\n\tsort.Strings(buf)\n\n\treturn buf\n}", "func Concat(s, t []rune) []rune {\n\tn := make([]rune, 0, len(s)+len(t))\n\tn = append(n, s...)\n\tn = append(n, t...)\n\treturn n\n}", "func Append(s []interface{}, val interface{}, grow int) []interface{} {\n\tl := len(s)\n\ttarget := s\n\tif l == cap(target) {\n\t\t// will grow by specified size instead of default cap*2\n\t\ttarget = make([]interface{}, l, l+grow)\n\t\tcopy(target, s[:])\n\t}\n\n\ttarget = append(target, val)\n\treturn target\n}", "func tcAppend(n *ir.CallExpr) ir.Node {\n\ttypecheckargs(n)\n\targs := n.Args\n\tif len(args) == 0 {\n\t\tbase.Errorf(\"missing arguments to append\")\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tt := args[0].Type()\n\tif t == nil {\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tn.SetType(t)\n\tif !t.IsSlice() {\n\t\tif ir.IsNil(args[0]) {\n\t\t\tbase.Errorf(\"first argument to append must be typed slice; have untyped nil\")\n\t\t\tn.SetType(nil)\n\t\t\treturn n\n\t\t}\n\n\t\tbase.Errorf(\"first argument to append must be slice; have %L\", t)\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tif n.IsDDD {\n\t\tif len(args) == 1 {\n\t\t\tbase.Errorf(\"cannot use ... on first argument to append\")\n\t\t\tn.SetType(nil)\n\t\t\treturn n\n\t\t}\n\n\t\tif len(args) != 2 {\n\t\t\tbase.Errorf(\"too many arguments to append\")\n\t\t\tn.SetType(nil)\n\t\t\treturn n\n\t\t}\n\n\t\tif t.Elem().IsKind(types.TUINT8) && args[1].Type().IsString() {\n\t\t\targs[1] = DefaultLit(args[1], types.Types[types.TSTRING])\n\t\t\treturn n\n\t\t}\n\n\t\targs[1] = AssignConv(args[1], t.Underlying(), \"append\")\n\t\treturn n\n\t}\n\n\tas := args[1:]\n\tfor i, n := range as {\n\t\tif n.Type() == nil {\n\t\t\tcontinue\n\t\t}\n\t\tas[i] = AssignConv(n, t.Elem(), \"append\")\n\t\ttypes.CheckSize(as[i].Type()) // ensure width is calculated for backend\n\t}\n\treturn n\n}", "func (f *FacebookMessages) Append(addition ...*FacebookMessage) *FacebookMessages {\n\tfor _, a := range addition {\n\t\t*f = append(*f, *a)\n\t}\n\treturn f\n}", "func bufApp(buf *[]byte, s string, w int, c byte) {\n\tif *buf == nil {\n\t\tif s[w] == c {\n\t\t\treturn\n\t\t}\n\n\t\t*buf = make([]byte, len(s))\n\t\tcopy(*buf, s[:w])\n\t}\n\t(*buf)[w] = c\n}", "func bufApp(buf *[]byte, s string, w int, c byte) {\n\tif *buf == nil {\n\t\tif s[w] == c {\n\t\t\treturn\n\t\t}\n\n\t\t*buf = make([]byte, len(s))\n\t\tcopy(*buf, s[:w])\n\t}\n\t(*buf)[w] = c\n}", "func groupAnagrams2(strs []string) [][]string {\n\thash := make(map[string]int)\n\tvar result [][]string\n\tkey := make([]rune, 26)\n\tfor _, str := range strs {\n\t\tfor _, r := range str {\n\t\t\tkey[r-'a']++\n\t\t}\n\t\tstrKey := string(key)\n\t\tif index, ok := hash[strKey]; ok {\n\t\t\tresult[index] = append(result[index], str)\n\t\t} else {\n\t\t\thash[strKey] = len(result)\n\t\t\tresult = append(result, []string{str})\n\t\t}\n\t}\n\treturn result\n}", "func (v CMap) Append(key, value string) CMap {\n\tvs := v.Get(key)\n\tif vs == \"\" || len(strings.Trim(vs, \" \")) == 0 {\n\t\tv.Set(key, value)\n\t\treturn v\n\t}\n\treturn v.Set(key, vs+value)\n}", "func (d *Dense) Append(d2 Dense) {\n\toff := d.len % byteSize\n\tif off == 0 {\n\t\td.bits = append(d.bits, d2.bits...)\n\t\td.len += d2.len\n\t\td.fixLastByte()\n\t\treturn\n\t}\n\tneeded := BytesFor(d.len+d2.len) - d.SizeBytes()\n\tif needed > 0 {\n\t\tif d.negated {\n\t\t\td.bits = append(d.bits, ones(needed)...)\n\t\t} else {\n\t\t\td.bits = append(d.bits, zeros(needed)...)\n\t\t}\n\t}\n\tdj := d.len / byteSize\n\td2j := 0\n\tfor ; dj+1 < len(d.bits); dj++ {\n\t\tb := d2.bits[d2j]\n\t\tif d.negated {\n\t\t\td.bits[dj] &= (b << off) | (0xFF >> (byteSize - off))\n\t\t\td.bits[dj+1] &= (b >> (byteSize - off)) | (0xFF << off)\n\t\t} else {\n\t\t\td.bits[dj] |= b << off\n\t\t\td.bits[dj+1] |= b >> (byteSize - off)\n\t\t}\n\t\td2j++\n\t}\n\tif d2j < d2.SizeBytes() {\n\t\tb := d2.bits[d2j]\n\t\tif d.negated {\n\t\t\td.bits[dj] &= (b << off) | (0xFF >> (byteSize - off))\n\t\t} else {\n\t\t\td.bits[dj] |= b << off\n\t\t}\n\t}\n\td.len += d2.len\n\td.fixLastByte()\n}", "func groupAnagrams(strs []string) [][]string {\n\tmp := map[string][]string{}\n\tfor _, str := range strs {\n\t\tkey := std2(str)\n\t\tmp[key] = append(mp[key], str)\n\t}\n\t//make(Type, len, cap)\n\tans := make([][]string, 0, len(mp))\n\tfor _, v := range mp {\n\t\tans = append(ans, v)\n\t}\n\treturn ans\n\n}", "func AlienDictonary(words []string) {\n\tdict := make(map[string][]string)\n\tfor i := 0; i < len(words); i++ {\n\t\tcurrent := string(words[i])\n\t\tfor j := 0; j < len(current); j++ {\n\t\t\t_, found := dict[string(current[j])]\n\t\t\tif !found {\n\t\t\t\tdict[string(current[j])] = []string{}\n\t\t\t}\n\n\t\t}\n\t}\n\tinEdges := make(map[string]int)\n\tfor key := range dict {\n\t\tinEdges[key] = 0\n\t}\n\tfor i := 1; i < len(words); i++ {\n\t\tfirst := words[i-1]\n\t\tsecond := words[i]\n\t\tl := int(math.Min(float64(len(first)), float64(len(second))))\n\t\tfor j := 0; j < l; j++ {\n\t\t\tif first[j] != second[j] {\n\t\t\t\tdict[string(first[j])] = append(dict[string(first[j])], string(second[j]))\n\t\t\t\tinEdges[string(second[j])]++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tq := []string{}\n\tfor key := range inEdges {\n\t\tif inEdges[key] == 0 {\n\t\t\tq = append(q, key)\n\t\t}\n\t}\n\tans := \"\"\n\tfor len(q) > 0 {\n\t\tremoved := q[0]\n\t\tq = q[1:]\n\t\tans += removed\n\t\tcurrent := dict[removed]\n\t\tfor i := 0; i < len(current); i++ {\n\t\t\tinEdges[string(current[i])]--\n\t\t\tif inEdges[string(current[i])] == 0 {\n\t\t\t\tq = append(q, string(current[i]))\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Println(ans)\n}", "func (hat *HashedArrayTree) Append(values ...interface{}) error {\n\tnewSize := hat.size + len(values)\n\tif err := hat.resize(newSize); err != nil {\n\t\treturn err\n\t}\n\tfor i, j := hat.size, 0; i < newSize; i, j = i+1, j+1 {\n\t\tti, li := hat.topIndex(i), hat.leafIndex(i)\n\t\that.top[ti][li] = values[j]\n\t}\n\that.size = newSize\n\treturn nil\n}", "func buildPhrases(words []string, ppWords int) {\n dictLength := big.NewInt(int64(len(words)))\n password := \"\"\n for i := 0; i < ppWords; i++ {\n index, err := rand.Int(rand.Reader, dictLength)\n if err != nil {\n fmt.Println(\"Something strange happened\")\n return\n }\n word := []byte(words[index.Uint64()])\n password += ucFirst(toUtf8(word))\n }\n fmt.Printf(\": %-60s - Brute force giving a total of %.1f bit entropy.\\n\", password, math.Log2(float64(58))*float64(len(password)))\n}", "func appendContentText(content string) (int, Burst) {\n\tout := make(Burst, 0)\n\tdebugf(\"appendContentText: %s\", content)\n\n\tbitpos := 0\n\tword := uint32(0)\n\tleftbits := 0\n\tpos := 0\n\n\t// walk through characters in message\n\tfor i, r := range content {\n\t\t// make sure it's 7 bits\n\t\tchar := byte(r & 0x7f)\n\n\t\tdebugf(\" char %d: %d [%X]\\n\", i, char, char)\n\n\t\tchar = reverseBits(char)\n\n\t\t// if the bits won't fit:\n\t\tif bitpos+7 > 20 {\n\t\t\tspace := 20 - bitpos\n\t\t\t// leftbits least significant bits of $char are left over in the next word\n\t\t\tleftbits = 7 - space\n\t\t\tdebugf(\" bits of char won't fit since bitpos is %d, got %d bits free, leaving %d bits in next word\", bitpos, space, leftbits)\n\t\t}\n\n\t\tword |= (uint32(char) << uint(31-7-bitpos))\n\n\t\tbitpos += 7\n\n\t\tif bitpos >= 20 {\n\t\t\tdebugf(\" appending word: %X\\n\", word)\n\t\t\tout = append(out, appendMessageCodeword(word))\n\t\t\tpos++\n\t\t\tword = 0\n\t\t\tbitpos = 0\n\t\t}\n\n\t\tif leftbits > 0 {\n\t\t\tword |= (uint32(char) << uint(31-leftbits))\n\t\t\tbitpos = leftbits\n\t\t\tleftbits = 0\n\t\t}\n\t}\n\n\tif bitpos > 0 {\n\t\tdebugf(\" got %d bits in word at end of text, word: %X\", bitpos, word)\n\t\tstep := 0\n\t\tfor bitpos < 20 {\n\t\t\tif step == 2 {\n\t\t\t\tword |= (1 << uint(30-bitpos))\n\t\t\t}\n\t\t\tbitpos++\n\t\t\tstep++\n\t\t\tif step == 7 {\n\t\t\t\tstep = 0\n\t\t\t}\n\t\t}\n\t\tout = append(out, appendMessageCodeword(word))\n\t\tpos++\n\t}\n\n\treturn pos, out\n}", "func (batch *BatchEncoder) Append(key []byte, value []byte) {\n\tvar keyLenByte [8]byte\n\tbinary.BigEndian.PutUint64(keyLenByte[:], uint64(len(key)))\n\tvar valueLenByte [8]byte\n\tbinary.BigEndian.PutUint64(valueLenByte[:], uint64(len(value)))\n\n\tbatch.keyBuf.Write(keyLenByte[:])\n\tbatch.keyBuf.Write(key)\n\n\tbatch.valueBuf.Write(valueLenByte[:])\n\tbatch.valueBuf.Write(value)\n}", "func waysToBuildString(s string, vocabulary []string) int {\n\tvar dp []int\n\tfor i := 0; i < len(s)+1; i++ {\n\t\tdp = append(dp, 0)\n\t}\n\tdp[0] = 1\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tsubString := s[i:nextIndex]\n\t\t\t\tif subString == w {\n\t\t\t\t\tdp[nextIndex] += dp[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func (n *Nodes) Append(a ...*Node)", "func UniqueAppend(orig []string, add ...string) []string {\n\treturn append(orig, NewUniqueElements(orig, add...)...)\n}", "func (s Sequence) Append(tok Token) Sequence {\n\tv := s.Clone()\n\tv.Tokens[len(s.Tokens)] = tok\n\treturn v\n}", "func concat(args ...[]string) []string {\n\tvar buf []string\n\tfor _, arg := range args {\n\t\tbuf = append(buf, arg...)\n\t}\n\n\treturn buf\n}", "func allCombinationsToBuildString(s string, vocabulary []string) [][]string {\n\tvar dp [][][]string\n\n\tfor i := 0; i < len(dp); i++ {\n\t\tfor _, w := range vocabulary {\n\t\t\tnextIndex := i + len(w)\n\t\t\tsubString := s[i:nextIndex]\n\t\t\tif nextIndex < len(dp) {\n\t\t\t\tif subString == w {\n\t\t\t\t\tfor _, comb := range dp[i] {\n\t\t\t\t\t\tupdatedComb := append(comb, w)\n\t\t\t\t\t\tdp[nextIndex] = append(dp[nextIndex], updatedComb)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[len(s)+1]\n}", "func paddedAppend(size uint, dst, src []byte) []byte {\n\tfor i := 0; i < int(size)-len(src); i++ {\n\t\tdst = append(dst, 0)\n\t}\n\treturn append(dst, src...)\n}", "func AppendB2R(dst []rune, b []byte) []rune {\n\treturn AppendBytesToRunes(dst, b)\n}", "func appendOne(arr1 []byte, oneByte byte) []byte {\n\tresult := make([]byte, len(arr1) + 1);\n\tfor i:= 0; i < len(arr1); i++ {\n\t\tresult[i] = arr1[i];\n\t};\n\tresult[len(result) - 1] = oneByte;\n\treturn result;\n}", "func Append(m []interface{}, args ...interface{}) []interface{} {\n\tfor _, v := range args {\n\t\tm = append(m, v)\n\t}\n\treturn m\n}", "func (s *String) Append(value []byte) (int, error) {\n\ts.Meta.Value = append(s.Meta.Value, value...)\n\tif err := s.txn.t.Set(MetaKey(s.txn.db, s.key), s.encode()); err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(s.Meta.Value), nil\n}", "func appendRepeatedBytes(dst []byte, repeatedBytes []byte, number int) []byte {\n\tfor number > 0 {\n\t\tn := number\n\t\tif n > len(repeatedBytes) {\n\t\t\tn = len(repeatedBytes)\n\t\t}\n\t\tdst = append(dst, repeatedBytes[:n]...)\n\t\tnumber -= n\n\t}\n\treturn dst\n}", "func BCat(b1, b2 []byte) []byte {\n\treturn append(b1, b2...)\n}", "func AppendEncode(enc []byte, inNode ipld.Node) ([]byte, error) {\n\treturn dageth_trie.AppendEncode(enc, inNode)\n}", "func (e *T) append(b byte) {\n\tif e.widx >= len(e.buf) {\n\t\te.overflow = true\n\t\te.available = true\n\t\treturn\n\t}\n\te.buf[e.widx] = b\n\te.widx++\n}", "func Append(text string) {\n\tctext := C.CString(text)\n\tdefer C.free(unsafe.Pointer(ctext))\n\tC.Z3_append_log(ctext)\n}", "func RevAppend(seq, tail Seq) Seq {\n\tif seq == nil {\n\t\treturn tail\n\t}\n\treturn RevAppend(seq.Rest(), cons(seq.First(), tail))\n}", "func combine(str1, str2 string) string {\n\tvar res string\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\t//mark the number of same chars\n\tvar sameNum int = 0\n\tfor len1 > 0 && sameNum < len2 {\n\t\tif str1[len1-1] == str2[sameNum] {\n\t\t\tlen1--\n\t\t\tsameNum++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\t//combine str1 and str2\n\tres = str1[0:len1] + str2[sameNum:len2]\n\treturn res\n\n}", "func (p *Packed2DGenericTypeBuilder) Append(x GenericType) {\n\tif p.autoGrow && p.tail >= len(p.buf) {\n\t\tp.Grow(1)\n\t}\n\tp.buf[p.tail] = x\n\tp.tail++\n}", "func (s String) Add(in ...string) {\n\tfor _, i := range in {\n\t\ts[i] = struct{}{}\n\t}\n}", "func newIndexedConcat() concat {\n\tnl := []byte{byte('\\n')}\n\treturn concat{\n\t\tjoin: func(element store.Element) ([]byte, error) {\n\t\t\tb, err := Concat(len(element.Value)+len(nl), element.Value, nl)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not serialize value %w\", err)\n\t\t\t}\n\t\t\treturn b, nil\n\t\t},\n\t\tsplit: func(key store.Key, data []byte) (store.Element, error) {\n\t\t\tn := len(data) - len(nl)\n\t\t\treturn store.NewElement(key, data[0:n]), nil\n\t\t},\n\t}\n}", "func (jbobject *JavaNioCharBuffer) Append2(a JavaLangCharSequenceInterface, b int, c int) *JavaNioCharBuffer {\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\tjret, err := jbobject.CallMethod(javabind.GetEnv(), \"append\", \"java/nio/CharBuffer\", conv_a.Value().Cast(\"java/lang/CharSequence\"), b, c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\tretconv := javabind.NewJavaToGoCallable()\n\tdst := &javabind.Callable{}\n\tretconv.Dest(dst)\n\tif err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {\n\t\tpanic(err)\n\t}\n\tretconv.CleanUp()\n\tunique_x := &JavaNioCharBuffer{}\n\tunique_x.Callable = dst\n\treturn unique_x\n}" ]
[ "0.5854114", "0.5709732", "0.5358691", "0.53485084", "0.5276471", "0.50733846", "0.5061012", "0.49326667", "0.48938566", "0.48491368", "0.48405713", "0.4838271", "0.48338476", "0.4833691", "0.48082826", "0.4801425", "0.47989488", "0.47850963", "0.47785482", "0.47461033", "0.4745807", "0.4739743", "0.47312087", "0.46961665", "0.46764386", "0.46589607", "0.4635204", "0.46197635", "0.46196514", "0.46180606", "0.46046713", "0.45940456", "0.45773792", "0.4568429", "0.45678285", "0.4564373", "0.45578107", "0.4543602", "0.4533565", "0.45321923", "0.45280904", "0.45241255", "0.45147958", "0.45104414", "0.45065793", "0.4504366", "0.44987577", "0.44886464", "0.44884917", "0.44820252", "0.44820252", "0.4481796", "0.4475984", "0.44741893", "0.44593942", "0.44572195", "0.4444688", "0.44424665", "0.44371483", "0.44322935", "0.44306403", "0.44106373", "0.44065222", "0.43959945", "0.43952066", "0.43949106", "0.4393399", "0.43882856", "0.43882856", "0.43863016", "0.43853217", "0.43789756", "0.43751258", "0.43733662", "0.43706992", "0.43656236", "0.4362065", "0.43576214", "0.43550447", "0.435143", "0.43316734", "0.43312567", "0.43286997", "0.4318695", "0.43075913", "0.43028542", "0.42911083", "0.42846805", "0.4282234", "0.4279279", "0.42783868", "0.42668197", "0.42635468", "0.42608494", "0.42578605", "0.42561713", "0.42501757", "0.42466596", "0.42401236", "0.42316166" ]
0.6780024
0
Get accounts by the provided names
func (api *API) GetAccounts(ctx context.Context, names ...string) ([]*Account, error) { var resp []*Account err := api.call(ctx, "get_accounts", []interface{}{names}, &resp) return resp, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (accounts *Accounts) ByName(name string) *Account {\n\tfor _, acc := range accounts.Map {\n\t\tif acc.Name == name {\n\t\t\treturn acc\n\t\t}\n\t}\n\treturn nil\n}", "func (c *GethClient) Accounts(ctx context.Context) ([]string, error) {\n\tvar result []string\n\terr := c.rpcCli.CallContext(ctx, &result, \"personal_listAccounts\")\n\treturn result, err\n}", "func (api *API) LookupAccounts(ctx context.Context, lowerBoundName string, limit uint16) ([]string, error) {\n\tvar resp []string\n\terr := api.call(ctx, \"lookup_accounts\", []interface{}{lowerBoundName, limit}, &resp)\n\treturn resp, err\n}", "func (tk *TwitchKraken) GetUsersByNames(names []string) (resp *Users, jsoerr *network.JSONError, err error) {\n\tresp = new(Users)\n\tjac := new(network.JSONAPIClient)\n\thMap := make(map[string]string)\n\thMap[\"Accept\"] = APIVersionHeader\n\thMap[\"Client-ID\"] = tk.ClientID\n\n\tlogins := \"\"\n\tfor _, val := range names {\n\t\tlogins = logins + val + \",\"\n\t}\n\tlogins = strings.TrimRight(logins, \",\")\n\tjsoerr, err = jac.Request(BaseURL+\"/users?login=\"+logins, hMap, &resp)\n\treturn\n}", "func getAccount(addrs []string) ([]*account, []string, error) {\n\tstartWorker()\n\n\ttotalTask := len(addrs)\n\tresult := make([]*account, 0, len(addrs))\n\tbadAddr := make([]string, 0, len(addrs))\n\tlock := new(sync.Mutex)\n\twg := new(sync.WaitGroup)\n\n\tif len(addrs) > getAccountWorkerLimit {\n\t\tgo getAcoountF(addrs[0:len(addrs)-getAccountWorkerLimit], &result, &badAddr, lock, wg)\n\t\taddrs = addrs[len(addrs)-getAccountWorkerLimit:]\n\t}\n\n\tclient := grpcclient.GetRandomSolidity()\n\t// client1 := grpcclient.GetRandomWallet()\n\n\terrCnt := 0\n\n\trestAddr := make([]string, 0, len(addrs))\n\taccountList := make([]*account, 0, len(addrs))\n\tbad := make([]string, 0, len(addrs))\n\n\tfor _, addr := range addrs {\n\t\tif !utils.VerifyTronAddrByte([]byte(addr)) {\n\t\t\tbad = append(bad, addr)\n\t\t\tcontinue\n\t\t}\n\n\t\tacc, err := client.GetAccountRawAddr(([]byte(addr)))\n\t\tif nil != err || nil == acc || len(acc.Address) == 0 {\n\t\t\terrCnt++\n\t\t\trestAddr = append(restAddr, addr)\n\t\t\tif errCnt >= maxErrCnt {\n\t\t\t\tclient = grpcclient.GetRandomSolidity()\n\t\t\t\terrCnt = 0\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// accNet, err := client1.GetAccountNetRawAddr([]byte(addr))\n\t\t// if nil != err || nil == accNet {\n\t\t// \terrCnt++\n\t\t// \trestAddr = append(restAddr, addr)\n\t\t// \tif errCnt > maxErrCnt {\n\t\t// \t\tclient1 = grpcclient.GetRandomWallet()\n\t\t// \t\terrCnt = 0\n\t\t// \t}\n\t\t// \tcontinue\n\t\t// }\n\n\t\tacct := new(account)\n\t\tacct.SetRaw(acc)\n\t\t// acct.SetNetRaw(accNet)\n\t\taccountList = append(accountList, acct)\n\t}\n\n\tif len(restAddr) > 0 {\n\t\tgo getAcoountF(restAddr, &result, &badAddr, lock, wg)\n\t}\n\n\twaitCnt := 3\n\tlock.Lock()\n\tresult = append(result, accountList...)\n\tbadAddr = append(badAddr, bad...)\n\tlock.Unlock()\n\tfmt.Printf(\"***** main routine, working task:%v, current account result count:%v, badAddr:%v, waitCnt:%v\\n\", workingTaskCnt(), len(result), len(badAddr), waitCnt)\n\n\tfor {\n\t\tworkCnt := workingTaskCnt()\n\t\tlock.Lock()\n\t\tfmt.Printf(\"***** main routine, working task:%v, current account result count:%v (total:%v), badAddr:%v, waitCnt:%v\\n\", workCnt, len(result), totalTask, len(badAddr), waitCnt)\n\t\tlock.Unlock()\n\n\t\tif workCnt == 1 {\n\t\t\twaitCnt--\n\t\t}\n\t\tif waitCnt <= 0 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\t}\n\n\t// storeAccount(accountList)\n\n\tstopWorker()\n\n\tprocess := int64(0)\n\tgetAccountNet(result, &process, lock)\n\n\treturn result, badAddr, nil\n}", "func getAccounts() ([]string, error) {\n\tout, err := exec.Command(\"ykman\", \"oath\", \"accounts\", \"list\").Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//fmt.Printf(\"Cmd out:\\n%s\\n\", out)\n\treturn strings.Split(strings.ReplaceAll(string(out), \"\\r\\n\", \"\\n\"), \"\\n\"), nil\n}", "func (t *SimpleChaincode) query_account_names (stub shim.ChaincodeStubInterface, args []string) pb.Response {\n if len(args) != 0 {\n return shim.Error(fmt.Sprintf(\"Incorrect number of arguments. Expecting 0 arguments, got %v\", args))\n }\n\n // only Admin is allowed to query_account_names\n if !transactor_is_admin(stub) {\n return shim.Error(\"Only admin user is authorized to query_account_names\")\n }\n\n account_names,err := get_account_names_(stub)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"Could not query_account_names due to error %v\", err.Error()))\n }\n\n var bytes []byte\n if len(account_names) == 0 {\n bytes = []byte(\"[]\")\n } else {\n // Serialize account names as JSON\n bytes,err = json.Marshal(account_names)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"Serializing account names failed in query_account_names because json.Marshal failed with error %v\", err))\n }\n }\n fmt.Printf(\"query_account_names response: %s\\n\", string(bytes))\n return shim.Success(bytes)\n}", "func (c *Client) GetAllByName(name string) ([]Credential, error) {\n\treturn c.getByName(name, false, -1)\n}", "func (owner *WalletOwnerAPI) Accounts() (*[]libwallet.AccountPathMapping, error) {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t}{\n\t\tToken: owner.token,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvl, err := owner.client.EncryptedRequest(\"accounts\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif envl == nil {\n\t\treturn nil, errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during Accounts\")\n\t\treturn nil, errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Err != nil {\n\t\treturn nil, errors.New(string(result.Err))\n\t}\n\tvar accounts []libwallet.AccountPathMapping\n\tif err = json.Unmarshal(result.Ok, &accounts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accounts, nil\n}", "func Accounts(client *ticketmatic.Client) ([]*ticketmatic.AccountInfo, error) {\n\tr := client.NewRequest(\"GET\", \"/_/tools/accounts\", \"json\")\n\n\tvar obj []*ticketmatic.AccountInfo\n\terr := r.Run(&obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}", "func GetAccountsByAddress(address common.Address) (account TestAccount, err error) {\n\taccounts, err := GetAccounts()\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, a := range accounts {\n\t\tif a.Address == address {\n\t\t\taccount = a\n\t\t\treturn\n\t\t}\n\t}\n\terr = errors.New(\"no account in keystore\")\n\treturn\n}", "func getAccountByName(db *sqlite.Driver, name string) (*Account, error) {\n\tvar err error\n\tvar newAccount Account\n\n\tvar stmt = fmt.Sprintf(\"select %s from %s where name = ?\", allColumns, tableName)\n\tif err = db.QueryRow(stmt, name).Scan(\n\t\t&newAccount.ID,\n\t\t&newAccount.Name,\n\t\t&newAccount.Credential,\n\t\t&newAccount.PermLevel); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, FindAccountError(name)\n\t\t}\n\t\treturn nil, SQLExecutionError(err)\n\t}\n\n\treturn &newAccount, nil\n}", "func GetUsersByName(name string)(users Users,err error){\n\trows,err := db.Query(\"select user_id,email,password,date from users where user_name = ?\",name)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor rows.Next() {\n\t\tu := &User{}\n\t\trows.Scan(&u.Id,&u.Email,&u.password,&u.Date)\n\t\tu.Name = name\n\t\tusers = append(users,u)\n\t}\n\t//for _,v := range users{\n\t//\tfmt.Println(v)\n\t//}\n\treturn\n}", "func Find(in *accountstore.SearchRequest) ([]Account, error) {\n\tvar out []Account\n\treq := db.New()\n\n\tif in.InstagramUsername > \"\" {\n\t\treq = req.Where(\"instagram_username = ?\", strings.ToLower(in.InstagramUsername))\n\t}\n\n\tif in.InstagramId > 0 {\n\t\treq = req.Where(\"instagram_id = ?\", in.InstagramId)\n\t}\n\n\tif in.OwnerId > 0 {\n\t\treq = req.Where(\"owner_id = ?\", in.OwnerId)\n\t}\n\n\tif !in.IncludeInvalids {\n\t\treq = req.Where(\"valid != FALSE\")\n\t}\n\n\tif len(in.Roles) > 0 {\n\t\treq = req.Where(\"role in (?)\", in.Roles)\n\t}\n\n\terr := req.Find(&out).Error\n\treturn out, err\n}", "func FindAccounts(tx *storage.Connection, userID uuid.UUID, pageParams *Pagination, sortParams *SortParams) ([]*Account, error) {\n\taccounts := []*Account{}\n\tvar err error\n\n\tpop.Debug = true\n\tq := tx.Q()\n\tif userID.String() != \"00000000-0000-0000-0000-000000000000\" {\n\t\t// UserID is not nil, so we have to query for the relations from\n\t\t// account_user\n\t\tq.RawQuery(`\n\t\tSELECT\n\t\t\taccounts.id as id,\n\t\t\taccounts.name as name,\n\t\t\taccounts.billing_name as billing_name,\n\t\t\taccounts.billing_email as billing_email,\n\t\t\taccounts.billing_details as billing_details,\n\t\t\taccounts.billing_period as billing_period,\n\t\t\taccounts.payment_method_id as payment_method_id,\n\t\t\taccounts.raw_owner_ids as raw_owner_ids,\n\t\t\taccounts.raw_account_meta_data as raw_account_meta_data,\n\t\t\taccounts.created_at as created_at,\n\t\t\taccounts.updated_at as updated_at\n\t\tFROM\n\t\t\taccounts_users as accounts_users\n\t\t\tJOIN accounts ON accounts.id = accounts_users.account_id\n\t\tWHERE\n\t\t\taccounts_users.user_id = ?`, userID)\n\n\t\terr = q.Eager(\"Roles\").All(&accounts)\n\t\treturn accounts, err\n\t}\n\n\tif sortParams != nil && len(sortParams.Fields) > 0 {\n\t\tfor _, field := range sortParams.Fields {\n\t\t\tq = q.Order(field.Name + \" \" + string(field.Dir))\n\t\t}\n\t}\n\n\tif pageParams != nil {\n\t\terr = q.Paginate(int(pageParams.Page), int(pageParams.PerPage)).Eager(\"Roles\").All(&accounts)\n\t\tpageParams.Count = uint64(q.Paginator.TotalEntriesSize)\n\t} else {\n\t\terr = q.Eager(\"Roles\").All(&accounts)\n\t}\n\treturn accounts, err\n}", "func encryptNameForAccounts(name string, accounts ...*api.Account) ([]api.EncryptedNameRequest, error) {\n\tencryptedNames := make([]api.EncryptedNameRequest, len(accounts))\n\tfor i, account := range accounts {\n\t\tvar err error\n\t\tencryptedNames[i], err = encryptNameForAccount(name, account)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn encryptedNames, nil\n}", "func (ks *KeyStore) Find(a common.Address) ([]accounts.Account, error) {\n\taccs, err := ks.Accounts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfound := []accounts.Account{}\n\tfor _, acc := range accs {\n\t\tif acc.Address == a {\n\t\t\tfound = append(found, *acc)\n\t\t}\n\t}\n\treturn found, nil\n}", "func accountsGet(c *gin.Context) {\n\tres := c.Query(\"result\")\n\n\tidStr := c.Query(\"id\")\n\n\tvar id int\n\tvar err error\n\tid, err = strconv.Atoi(idStr)\n\tif err != nil {\n\t\tid = noId\n\t}\n\n\t// if there is an id in the request (getting only one balance)\n\tif id != noId {\n\t\tbalance, err := manager.Get(id)\n\t\tif err != nil {\n\t\t\tlogger.Zap().Error(\"failed to get balance\", zap.Error(err))\n\t\t\t// TODO: return more explicit error code\n\t\t\tc.String(http.StatusInternalServerError, \"failed to get balance\")\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%d\", balance)\n\t\treturn\n\t}\n\n\t// getting all balances\n\tswitch res {\n\t// to return sum of all balances\n\tcase \"aggregate\":\n\t\tbalance, err := manager.GetAll()\n\t\tif err != nil {\n\t\t\tlogger.Zap().Error(\"failed to get all balances\", zap.Error(err))\n\t\t\t// TODO: return more explicit error code\n\t\t\tc.String(http.StatusInternalServerError, \"failed to get all balances\")\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%d\", balance)\n\t// to return the list all balances\n\tcase \"list\":\n\t\t// TODO: declare business api to support returning a list all the accounts (ids and values)\n\t\t// Its difference in concurrent mode would be the way we protect the global slice in the memory (which all go routines will add an account to)\n\t\t// We need to use locking (mutex) around the piece of code that inserts into the slice in that case\n\t\tc.String(http.StatusNotImplemented, \"not implemented\")\n\tdefault:\n\t\tc.String(http.StatusUnprocessableEntity, \"please specify the result mod (aggregate,...)\")\n\t}\n}", "func listAccounts(c echo.Context) error {\n\tvar errResp ErrorResponseData\n\tvar resp AccountListResponseData\n\n\tfromDateTime, err := strconv.Atoi(c.Param(\"dromDateTime\"))\n\n\tif (err != nil) || (fromDateTime <= 0) {\n\t\terrResp.Data.Code = \"invalid_parameter_error\"\n\t\terrResp.Data.Description = \"Invalid value in query parameter fromDateTime\"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusBadRequest)\n\t\treturn c.JSON(http.StatusBadRequest, errResp)\n\t}\n\ttoDateTime, err := strconv.Atoi(c.Param(\"toDateTime\"))\n\n\tif (err != nil) || (toDateTime <= 0) || toDateTime < fromDateTime {\n\t\terrResp.Data.Code = \"invalid_parameter_error\"\n\t\terrResp.Data.Description = \"Invalid value \"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusBadRequest)\n\t\treturn c.JSON(http.StatusBadRequest, errResp)\n\t}\n\n\ttotalItems, accounts, err := storage.GetAccountList(fromDateTime, toDateTime)\n\n\tif err != nil {\n\t\terrResp.Data.Code = \"error\"\n\t\terrResp.Data.Description = \"Unable to fetch list \"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusInternalServerError)\n\t\treturn c.JSON(http.StatusInternalServerError, errResp)\n\t}\n\n\tfor _, account := range accounts {\n\t\tvar respAccount UserResponseData\n\t\trespAccount.mapFromModel(account)\n\t\tresp.Data = append(resp.Data, respAccount.Data)\n\t}\n\n\tpageSize := 10\n\tresp.Meta.TotalPages = (totalItems / pageSize) + 1\n\n\treturn c.JSON(http.StatusOK, resp)\n}", "func returnUsersAccounts(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar users []User\n\tvar orders []Orders\n\t//fmt.Println(\"Request URI: \", path.Base(r.RequestURI))\n\tusername := path.Base(r.RequestURI)\n\n\t// query for userid\n\tresults, err := db.Query(\"Select * from users where username = ?\", username)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tfor results.Next() {\n\t\tvar user User\n\t\terr := results.Scan(&user.ID, &user.Username)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\n\t\tusers = append(users, user)\n\t\tfmt.Println(\"Userid: \", users[0].ID)\n\t}\n\n\t// query the orders table with userid and return all rows\n\n\t//select orders.id, users.username, stocks.symbol, shares from orders inner join users on orders.user_id = users.id inner join stocks on orders.stock_id = stocks.id\n\tresults, err = db.Query(\"select orders.id, users.username, stocks.symbol, shares from orders inner join users on orders.user_id = users.id inner join stocks on orders.stock_id = stocks.id where orders.user_id = ?\", users[0].ID)\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tfor results.Next() {\n\t\tvar order Orders\n\t\terr = results.Scan(&order.ID, &order.Username, &order.Symbol, &order.Shares)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\torders = append(orders, order)\n\t}\n\tjson.NewEncoder(w).Encode(orders)\n}", "func (client *ClientImpl) GetAccounts(ctx context.Context, args GetAccountsArgs) (*[]Account, error) {\n\tqueryParams := url.Values{}\n\tif args.OwnerId != nil {\n\t\tqueryParams.Add(\"ownerId\", (*args.OwnerId).String())\n\t}\n\tif args.MemberId != nil {\n\t\tqueryParams.Add(\"memberId\", (*args.MemberId).String())\n\t}\n\tif args.Properties != nil {\n\t\tqueryParams.Add(\"properties\", *args.Properties)\n\t}\n\tlocationId, _ := uuid.Parse(\"229a6a53-b428-4ffb-a835-e8f36b5b4b1e\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.1\", nil, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []Account\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\trepository := repositories.NewAccountRepository(db)\n\taccounts, erro := repository.FindAll()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, accounts)\n}", "func UsersByName(c *gin.Context) {\n\tname := c.Param(\"name\")\n\tusers := user.GetByName(name)\n\tc.JSON(200, gin.H{\n\t\t\"data\": users,\n\t})\n}", "func (e *Ethereum) Accounts() ([]string, error) {\n\tvar accounts []string\n\terr := e.rpcClient.CallContext(e.ctx, &accounts, \"eth_accounts\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"fail to call rpc.CallContext(eth_accounts)\")\n\t}\n\n\treturn accounts, nil\n}", "func (_FCToken *FCTokenSession) Accounts(arg0 *big.Int) (common.Address, error) {\n\treturn _FCToken.Contract.Accounts(&_FCToken.CallOpts, arg0)\n}", "func get_account_ (stub shim.ChaincodeStubInterface, account_name string) (*Account, error) {\n var account Account\n row_was_found,err := util.GetTableRow(stub, ACCOUNT_TABLE, []string{account_name}, &account, util.FAIL_IF_MISSING)\n if err != nil {\n return nil,fmt.Errorf(\"Could not retrieve account named \\\"%s\\\"; error was %v\", account_name, err.Error())\n }\n if !row_was_found {\n return nil,fmt.Errorf(\"Account named \\\"%s\\\" does not exist\", account_name)\n }\n return &account,nil\n}", "func (authcl *Client) SearchAccount(query string) ([]gin.Account, error) {\n\tvar accs []gin.Account\n\n\tparams := url.Values{}\n\tparams.Add(\"q\", query)\n\taddress := fmt.Sprintf(\"/api/accounts?%s\", params.Encode())\n\tres, err := authcl.Get(address)\n\tif err != nil {\n\t\treturn accs, err\n\t} else if res.StatusCode != http.StatusOK {\n\t\treturn accs, fmt.Errorf(\"[Account search] Failed. Server returned: %s\", res.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn accs, err\n\t}\n\n\terr = json.Unmarshal(body, &accs)\n\treturn accs, err\n}", "func (_FCToken *FCTokenCallerSession) Accounts(arg0 *big.Int) (common.Address, error) {\n\treturn _FCToken.Contract.Accounts(&_FCToken.CallOpts, arg0)\n}", "func ListAccounts(w http.ResponseWriter, r *http.Request) {\n\tisAdmin := false\n\tif oauth, ok := OAuthToken(r); ok {\n\t\tisAdmin = oauth.Match.Contains(\"account-admin\")\n\t}\n\n\tvar accounts []data.Account\n\tsearch := r.URL.Query().Get(\"q\")\n\tif search != \"\" {\n\t\taccounts = data.SearchAccounts(search)\n\t} else {\n\t\taccounts = data.ListAccounts()\n\t}\n\n\tmarshal := make([]data.AccountMarshaler, 0, len(accounts))\n\tfor i := 0; i < len(accounts); i++ {\n\t\tacc := &accounts[i]\n\t\tmarshal = append(marshal, data.AccountMarshaler{\n\t\t\tWithMail: isAdmin || acc.IsEmailPublic,\n\t\t\tWithAffiliation: isAdmin || acc.IsAffiliationPublic,\n\t\t\tAccount: acc,\n\t\t})\n\t}\n\n\tw.Header().Add(\"Cache-Control\", \"no-cache\")\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(marshal)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (r *RepoCache) FindOwners(repoName string) []string {\n if owners, ok := r.NameMap[repoName]; ok {\n return owners\n }\n return []string{}\n}", "func (a *AccountClient) List(paging PagingParams) (*Resources, error) {\n\n\tr := a.client.R().SetResult(&Resources{})\n\n\tif paging.number != \"\" {\n\t\tr.SetQueryParam(\"page[number]\", paging.number)\n\t}\n\n\tif paging.size != \"\" {\n\t\tr.SetQueryParam(\"page[size]\", paging.size)\n\t}\n\tresp, err := r.Get(\"/v1/organisation/accounts\")\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"list accounts failed: %s\", err)\n\t}\n\n\tif resp.Error() != nil {\n\t\treturn nil, getAPIError(resp)\n\t}\n\n\treturn resp.Result().(*Resources), nil\n}", "func OneAccountByName(name string) (Account, error) {\n\tuser := Account{}\n\n\tsqlStatement := \"SELECT * FROM account WHERE account.username = $1\"\n\n\trow := config.DB.QueryRow(sqlStatement, name)\n\n\tswitch err := row.Scan(&user.ID, &user.Username, &user.Password); err {\n\tcase sql.ErrNoRows:\n\t\treturn user, fmt.Errorf(\"No rows were found\")\n\tcase nil:\n\t\treturn user, nil\n\tdefault:\n\t\tpanic(err)\n\t}\n}", "func (_FCToken *FCTokenCaller) Accounts(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"accounts\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func find(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, query *sqlbuilder.SelectBuilder, args []interface{}, includedArchived bool) (UserAccounts, error) {\n\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.user_account.Find\")\n\tdefer span.Finish()\n\n\tquery.Select(userAccountMapColumns)\n\tquery.From(userAccountTableName)\n\n\tif !includedArchived {\n\t\tquery.Where(query.IsNull(\"archived_at\"))\n\t}\n\n\t// Check to see if a sub query needs to be applied for the claims\n\terr := applyClaimsSelect(ctx, claims, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqueryStr, queryArgs := query.Build()\n\tqueryStr = dbConn.Rebind(queryStr)\n\targs = append(args, queryArgs...)\n\n\t// fetch all places from the db\n\trows, err := dbConn.QueryContext(ctx, queryStr, args...)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\terr = errors.WithMessage(err, \"find user accounts failed\")\n\t\treturn nil, err\n\t}\n\n\t// iterate over each row\n\tresp := []*UserAccount{}\n\tfor rows.Next() {\n\t\tua, err := mapRowsToUserAccount(rows)\n\t\tif err != nil {\n\t\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = append(resp, ua)\n\t}\n\n\treturn resp, nil\n}", "func (r *APIClientRepository) Accounts() (gin.Accounts, error) {\n\tclients := []domain.APIClient{}\n\tif err := r.DB.Select(&clients, \"select * from api_clients\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\taccounts := gin.Accounts{}\n\tfor _, client := range clients {\n\t\taccounts[client.Key] = client.Secret\n\t}\n\n\treturn accounts, nil\n}", "func (c *Client) getReaders(op errors.Op, name upspin.PathName, accessEntry *upspin.DirEntry) ([]upspin.UserName, error) {\n\tif accessEntry == nil {\n\t\t// No Access file present, therefore we must be the owner.\n\t\treturn nil, nil\n\t}\n\taccessData, err := c.Get(accessEntry.Name)\n\tif errors.Is(errors.NotExist, err) || errors.Is(errors.Permission, err) || errors.Is(errors.Private, err) {\n\t\t// If we failed to get the Access file for access-control\n\t\t// reasons, then we must not have read access and thus\n\t\t// cannot know the list of readers.\n\t\t// Instead, just return the owner as the only reader.\n\t\tparsed, err := path.Parse(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\towner := parsed.User()\n\t\tif owner == c.config.UserName() {\n\t\t\t// We are the owner, but the caller always\n\t\t\t// adds the us, so return an empty list.\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn []upspin.UserName{owner}, nil\n\t} else if err != nil {\n\t\t// We failed to fetch the Access file for some unexpected reason,\n\t\t// so bubble the error up.\n\t\treturn nil, err\n\t}\n\tacc, err := access.Parse(accessEntry.Name, accessData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treaders, err := acc.Users(access.Read, c.Get)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn readers, nil\n}", "func (d *dashboardsClient) GetByName(name string) ([]interface{}, error) {\n return []interface{}{}, nil\n}", "func (api *PublicEthereumAPI) Accounts() ([]common.Address, error) {\n\tapi.logger.Debug(\"eth_accounts\")\n\tapi.keyringLock.Lock()\n\tdefer api.keyringLock.Unlock()\n\n\taddresses := make([]common.Address, 0) // return [] instead of nil if empty\n\n\tinfos, err := api.clientCtx.Keybase.List()\n\tif err != nil {\n\t\treturn addresses, err\n\t}\n\n\tfor _, info := range infos {\n\t\taddressBytes := info.GetPubKey().Address().Bytes()\n\t\taddresses = append(addresses, common.BytesToAddress(addressBytes))\n\t}\n\n\treturn addresses, nil\n}", "func (s *Repository) GetAll(ctx context.Context) ([]Account, error) {\n\tconst limit = 10\n\n\trows, err := s.pool.Query(\n\t\tctx,\n\t\t`select * from \"account\"\n\t\t\t order by \"createdAt\" desc\n\t\t\t limit $1`, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\treturn scanAccounts(limit, rows)\n}", "func withArgs1(name string) (user, error) {\n\tfor _, user := range users {\n\t\tif user.name == name {\n\t\t\treturn user, nil\n\t\t}\n\t}\n\n\treturn user{}, errors.New(\"user is not found\")\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexepcted value found, height needs to be string of int!\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Return accounts from staking client\n\taccounts, err := so.Addresses(context.Background(), height)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Accounts!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/accounts failed to retrieve Accounts : \",\n\t\t\terr)\n\t\treturn\n\t}\n\n\t// Respond with array of all accounts\n\tlgr.Info.Println(\"Request at /api/staking/accounts responding with \" +\n\t\t\"Accounts!\")\n\tjson.NewEncoder(w).Encode(responses.AllAccountsResponse{AllAccounts: accounts})\n}", "func (pca Client) Accounts(ctx context.Context) ([]Account, error) {\n\treturn pca.base.AllAccounts(ctx)\n}", "func (s *Identity) AccountsGET(w http.ResponseWriter, r *http.Request) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\twriteResponse(s.addresses, w, r)\n}", "func (d *Dynamicd) GetMyAccounts() (*[]Account, error) {\n\tvar accountsGeneric map[string]interface{}\n\tvar accounts = []Account{}\n\treq, _ := NewRequest(\"dynamic-cli mybdapaccounts\")\n\trawResp := []byte(<-d.ExecCmdRequest(req))\n\terrUnmarshal := json.Unmarshal(rawResp, &accountsGeneric)\n\tif errUnmarshal != nil {\n\t\treturn &accounts, errUnmarshal\n\t}\n\tfor _, v := range accountsGeneric {\n\t\tb, err := json.Marshal(v)\n\t\tif err == nil {\n\t\t\tvar account Account\n\t\t\terrUnmarshal = json.Unmarshal(b, &account)\n\t\t\tif errUnmarshal != nil {\n\t\t\t\tutil.Error.Println(\"Inner error\", errUnmarshal)\n\t\t\t\treturn nil, errUnmarshal\n\t\t\t}\n\t\t\taccounts = append(accounts, account)\n\t\t}\n\t}\n\treturn &accounts, nil\n}", "func (s accountService) Get(name string) (*api.Account, error) {\n\taccountName, err := api.NewAccountName(name)\n\tif err != nil {\n\t\treturn nil, errio.Error(err)\n\t}\n\n\treturn s.client.httpClient.GetAccount(accountName)\n}", "func GetUsernames(db *sql.DB, identifiers []*sharedModels.GetUsernamesRequest) ([]*sharedModels.GetUsernamesResponse, error) {\n\n\tif len(identifiers) < 1 {\n\t\treturn make([]*sharedModels.GetUsernamesResponse, 0), nil\n\t}\n\n\tquery := inQueryBuilder(identifiers)\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpersons := make([]*sharedModels.GetUsernamesResponse, 0)\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar username string\n\t\terr = rows.Scan(&id, &username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpersons = append(persons, &sharedModels.GetUsernamesResponse{ID: id, Username: username})\n\t}\n\treturn persons, nil\n}", "func (c *Client) Accounts() (*AddressesResponse, error) {\n\trequest := c.newRequest(EthAccounts)\n\n\tresponse := &AddressesResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (sc Funcs) Accounts(ctx wasmlib.ScViewClientContext) *AccountsCall {\n\tf := &AccountsCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccounts)}\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func GetAccountByStatus(w http.ResponseWriter, r *http.Request) {\n\t// Fetch the accounts.\n\taccountStatus := r.FormValue(\"accountStatus\")\n\tstatus, err := db.ParseAccountStatus(accountStatus)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tapi.WriteAPIErrorResponse(w, errors.NewValidation(err.Error(), nil))\n\t\treturn\n\t}\n\n\taccounts, err := Dao.FindAccountsByStatus(status)\n\tif err != nil {\n\t\terrorMessage := fmt.Sprintf(\"Failed to query database: %s\", err)\n\t\tlog.Print(errorMessage)\n\t\tapi.WriteAPIErrorResponse(w, errors.NewInternalServer(errorMessage, nil))\n\t\treturn\n\t}\n\n\tif len(accounts) == 0 {\n\t\tapi.WriteAPIErrorResponse(w, errors.NewNotFound(\"account\", accountStatus))\n\t\treturn\n\t}\n\n\t// Serialize them for the JSON response.\n\taccountResponses := []*response.AccountResponse{}\n\n\tfor _, a := range accounts {\n\t\tacctRes := response.AccountResponse(*a)\n\t\taccountResponses = append(accountResponses, &acctRes)\n\t}\n\n\t_ = json.NewEncoder(w).Encode(accountResponses)\n\n}", "func (service AccountsService) List(params Params) (*Response, []Account, error) {\n\treq, err := service.client.newRequest(\"GET\", \"accounts\", params, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar a struct {\n\t\tXMLName xml.Name `xml:\"accounts\"`\n\t\tAccounts []Account `xml:\"account\"`\n\t}\n\tres, err := service.client.do(req, &a)\n\n\tfor i := range a.Accounts {\n\t\ta.Accounts[i].BillingInfo = nil\n\t}\n\n\treturn res, a.Accounts, err\n}", "func openAccounts() *accountData {\n\tad := newAccountData()\n\n\t// If the network (account) directory is missing, but the temporary\n\t// directory exists, move it. This is unlikely to happen, but possible,\n\t// if writing out every account file at once to a tmp directory (as is\n\t// done for changing a wallet passphrase) and btcwallet closes after\n\t// removing the network directory but before renaming the temporary\n\t// directory.\n\tnetDir := networkDir(cfg.Net())\n\ttmpNetDir := tmpNetworkDir(cfg.Net())\n\tif !fileExists(netDir) && fileExists(tmpNetDir) {\n\t\tif err := Rename(tmpNetDir, netDir); err != nil {\n\t\t\tlog.Errorf(\"Cannot move temporary network dir: %v\", err)\n\t\t\treturn ad\n\t\t}\n\t}\n\n\t// The default account must exist, or btcwallet acts as if no\n\t// wallets/accounts have been created yet.\n\ta, err := openSavedAccount(\"\", cfg)\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tcase *walletOpenError:\n\t\t\tlog.Errorf(\"Default account wallet file unreadable: %v\", err)\n\t\t\treturn ad\n\n\t\tdefault:\n\t\t\tlog.Warnf(\"Non-critical problem opening an account file: %v\", err)\n\t\t}\n\t}\n\n\tad.addAccount(a)\n\n\t// Read all filenames in the account directory, and look for any\n\t// filenames matching '*-wallet.bin'. These are wallets for\n\t// additional saved accounts.\n\taccountDir, err := os.Open(netDir)\n\tif err != nil {\n\t\t// Can't continue.\n\t\tlog.Errorf(\"Unable to open account directory: %v\", err)\n\t\treturn ad\n\t}\n\tdefer accountDir.Close()\n\tfileNames, err := accountDir.Readdirnames(0)\n\tif err != nil {\n\t\t// fileNames might be partially set, so log an error and\n\t\t// at least try to open some accounts.\n\t\tlog.Errorf(\"Unable to read all account files: %v\", err)\n\t}\n\tvar accountNames []string\n\tfor _, file := range fileNames {\n\t\tif strings.HasSuffix(file, \"-wallet.bin\") {\n\t\t\tname := strings.TrimSuffix(file, \"-wallet.bin\")\n\t\t\taccountNames = append(accountNames, name)\n\t\t}\n\t}\n\n\t// Open all additional accounts.\n\tfor _, acctName := range accountNames {\n\t\t// Log txstore/utxostore errors as these will be recovered\n\t\t// from with a rescan, but wallet errors must be returned\n\t\t// to the caller.\n\t\ta, err := openSavedAccount(acctName, cfg)\n\t\tif err != nil {\n\t\t\tswitch err.(type) {\n\t\t\tcase *walletOpenError:\n\t\t\t\tlog.Errorf(\"Error opening account's wallet: %v\", err)\n\n\t\t\tdefault:\n\t\t\t\tlog.Warnf(\"Non-critical error opening an account file: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tad.addAccount(a)\n\t\t}\n\t}\n\treturn ad\n}", "func (am *AccountManager) Account(name string) (*Account, error) {\n\trespChan := make(chan *Account)\n\tam.cmdChan <- &accessAccountRequest{\n\t\tname: name,\n\t\tresp: respChan,\n\t}\n\tresp := <-respChan\n\tif resp == nil {\n\t\treturn nil, ErrNotFound\n\t}\n\treturn resp, nil\n}", "func makeUsers(n int) []*acm.PrivAccount {\n\taccounts := []*acm.PrivAccount{}\n\tfor i := 0; i < n; i++ {\n\t\tsecret := \"mysecret\" + strconv.Itoa(i)\n\t\tuser := acm.GenPrivAccountFromSecret(secret)\n\t\taccounts = append(accounts, user)\n\t}\n\treturn accounts\n}", "func (c *AccountController) List(ctx *app.ListAccountContext) error {\n\tusers, err := repositories.GetAllUsers(1, 100)\n\tif err != nil {\n\t\treturn ctx.InternalServerError()\n\t}\n\tresp := app.FtAccountCollection{}\n\tfor _, u := range users {\n\t\tresp = append(resp, &app.FtAccount{\n\t\t\tID: u.ID,\n\t\t\tFirstName: u.FirstName,\n\t\t\tLastName: u.LastName,\n\t\t\tEmail: u.Email,\n\t\t})\n\t}\n\treturn ctx.OK(resp)\n}", "func AccountsWithRange(lower, count int) (*[]AccountModel, error) {\n\tvar result = &[]AccountModel{}\n\tvar err error\n\tvar rawResult orm.RawSeter\n\n\to := GetOrmObject()\n\tsqlQuery := fmt.Sprintf(\"SELECT * FROM %s LIMIT %d OFFSET %d\", AccountTable, count, lower)\n\trawResult = o.Raw(sqlQuery)\n\n\t_, err = rawResult.QueryRows(result)\n\tif err != nil {\n\n\t\tbeego.Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func listAccountsRecord(db *sqlite.Driver, filter AccountsFilter) ([]Account, error) {\n\tvar err error\n\tvar rows *sql.Rows\n\n\t// if true, prepend \"where\" statement on the query string\n\tvar whereFlag = false\n\tvar conditionBlocks = []string{}\n\tvar valueBlocks = []interface{}{}\n\n\tif filter.nameLike != nil {\n\t\twhereFlag = true\n\t\tconditionBlocks = append(conditionBlocks, \"name like ?\")\n\t\tvalueBlocks = append(valueBlocks, *(filter.nameLike))\n\t}\n\t// limit\n\tif filter.limit != nil {\n\t\tif *(filter.limit) < 0 {\n\t\t\treturn nil, ValidationError(\"limit < 0\")\n\t\t}\n\n\t\tconditionBlocks = append(conditionBlocks, \"limit ?\")\n\t\tvalueBlocks = append(valueBlocks, *(filter.limit))\n\t}\n\t// offset\n\tif filter.limit != nil && filter.offset != nil {\n\t\tif *(filter.offset) < 0 {\n\t\t\treturn nil, ValidationError(\"offset < 0\")\n\t\t}\n\n\t\tconditionBlocks = append(conditionBlocks, \"offset ?\")\n\t\tvalueBlocks = append(valueBlocks, *(filter.offset))\n\t}\n\t// add \"where\" statement if necessary\n\tif whereFlag {\n\t\tconditionBlocks = append([]string{\"where\"}, conditionBlocks...)\n\t}\n\tvar accounts []Account\n\n\t// query statement\n\tvar stmt = fmt.Sprintf(\"select %s from %s %s\", listColumns, tableName, strings.Join(conditionBlocks, \" \"))\n\tif rows, err = db.Query(stmt, valueBlocks...); err != nil {\n\t\treturn nil, SQLExecutionError(err)\n\t}\n\n\tfor rows.Next() {\n\t\tvar newAccount Account\n\t\tif err = rows.Scan(&newAccount.ID, &newAccount.Name, &newAccount.PermLevel); err != nil {\n\t\t\treturn nil, SQLExecutionError(err)\n\t\t}\n\n\t\taccounts = append(accounts, newAccount)\n\t}\n\n\treturn accounts, nil\n}", "func (k *Keypair) GetAccount(name string, fields map[string]string) *Account {\n\ta := &Account{\n\t\tfields: fields,\n\t\tname: name,\n\t\ttimestamp: uint32(time.Now().Unix()),\n\t}\n\n\tcopy(a.pub[:], k.pub[:])\n\thash := a.GetHash()\n\ta.sign = *(k.Sign(hash[:]))\n\treturn a\n}", "func (s *AccountsService) QueryAccounts(opt *QueryAccountOptions) (*[]AccountInfo, *Response, error) {\n\tu := \"accounts/\"\n\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new([]AccountInfo)\n\tresp, err := s.client.Do(req, v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func (e *Entry) GetByAccount(account string) error {\n\tfor _, entry := range []Entry(contacts) {\n\t\tif entry.ID == account {\n\t\t\t*e = entry\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"not found\")\n}", "func (repo mockRepository) GetByCreds(email, password string) (*User, error) {\n\tfor _, u := range repo {\n\t\tif u.Email == email && u.Password == password {\n\t\t\treturn &u, nil\n\t\t}\n\t}\n\n\treturn nil, ErrNoSuchUser\n}", "func (controller *AccountController) GetAccounts(ctx *gin.Context) {\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\taccs, err := controller.service.GetAccounts(info.Name)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Account Error GetAll\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"Could not get accounts because: \" + err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\tresponse, _ := restapi.NewOkResponse(accs).Marshal()\n\tfmt.Fprint(ctx.Writer, string(response))\n\tctx.Next()\n\n}", "func (a *ChatLogsArchive) GetAccountNames() ([]string, error) {\n\tif a.r == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar accountNamesMap = make(map[string]interface{})\n\tfor _, f := range a.r.File {\n\t\t// Take only .txt files.\n\t\tif filepath.Ext(f.Name) != \".txt\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tpath := filepath.Dir(f.Name)\n\n\t\t// Take files from 1st level directories only.\n\t\tif path != \"\" && !strings.ContainsAny(path, \"/\\\\\") {\n\t\t\taccountNamesMap[path] = nil\n\t\t}\n\t}\n\n\tvar accountNames []string\n\tfor accountName := range accountNamesMap {\n\t\taccountNames = append(accountNames, accountName)\n\t}\n\n\treturn accountNames, nil\n}", "func parseAccounts(resp *http.Response) ([]Account, error) {\n\tdoc, err := goquery.NewDocumentFromResponse(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taccounts := []Account{}\n\tvar accErr interface{}\n\n\tdoc.Find(\".setup-accounts .section.group\").Not(\".setup-heading\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\tacc, err := parseAccount(s)\n\t\tif err != nil {\n\t\t\taccErr = err\n\t\t\treturn false\n\t\t}\n\t\taccounts = append(accounts, *acc)\n\t\treturn true\n\t})\n\n\tif accErr != nil {\n\t\treturn nil, accErr.(error)\n\t}\n\treturn accounts, nil\n}", "func (s S) Accounts() []v1.ServiceAccount {\n\treturn s.accounts\n}", "func (service *AccountService) List(budgetId string) (accounts []model.Account, err error) {\n\n\tvar result model.AccountsResponse\n\terr = service.Client.get(\"/budgets/\"+budgetId+\"/accounts\", &result)\n\tif err != nil {\n\t\treturn\n\t}\n\n\taccounts = model.FilterActive(&result.Data.Accounts)\n\treturn\n}", "func (a *Api) GetAccounts(ctx echo.Context) error {\n\t// var result []Account\n\tvar accounts []Account\n\n\tdbResult := a.DB.Find(&accounts)\n\tif dbResult.Error != nil {\n\t\treturn sendApiError(ctx, http.StatusInternalServerError, \"DB error\")\n\t}\n\n\treturn ctx.JSONPretty(http.StatusOK, accounts, \" \")\n}", "func (t *TezTracker) AccountList(before string, limits Limiter, favorites []string) (accs []models.AccountListView, count int64, err error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.AccountFilter{\n\t\tType: models.AccountTypeAccount,\n\t\tOrderBy: models.AccountOrderFieldCreatedAt,\n\t\tAfter: before,\n\t\tFavorites: favorites,\n\t}\n\tcount, accs, err = r.List(limits.Limit(), limits.Offset(), filter)\n\treturn accs, count, err\n}", "func AccessListByNames(names string) AccessList {\n\t// check to see if there is only \"one\" entry\n\tif !strings.Contains(names, \",\") {\n\t\treturn []Access{AccessByName(names)}\n\t}\n\tnamelist := strings.Split(names, \",\")\n\tresult := make(AccessList, len(namelist))\n\tfor i, name := range namelist {\n\t\tresult[i] = AccessByName(name)\n\t}\n\treturn result\n}", "func (w *Wallet) ScanForAccounts() (err error) {\n\taccounts := make([]string, 10)\n\tfor i := range accounts {\n\t\ta, err := w.NewAccount(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taccounts[i] = a.Address()\n\t}\n\tbalances, err := w.RPC.AccountsBalances(accounts)\n\tif err != nil {\n\t\treturn\n\t}\n\tfrontiers, err := w.RPC.AccountsFrontiers(accounts)\n\tif err != nil {\n\t\treturn\n\t}\n\ti := len(accounts) - 1\n\tfor ; i >= 0; i-- {\n\t\tif balances[accounts[i]].Pending.Sign() > 0 {\n\t\t\tbreak\n\t\t}\n\t\tif frontiers[accounts[i]] != nil {\n\t\t\tbreak\n\t\t}\n\t\tw.nextIndex = w.accounts[accounts[i]].index\n\t\tdelete(w.accounts, accounts[i])\n\t}\n\tif i < 5 {\n\t\treturn\n\t}\n\treturn w.ScanForAccounts()\n}", "func (p *bitsharesAPI) GetAccounts(accounts ...objects.GrapheneObject) ([]objects.Account, error) {\n\tvar result []objects.Account\n\terr := p.call(p.databaseAPIID, \"get_accounts\", &result, accounts)\n\treturn result, err\n}", "func (s *Service) GetAccounts(budgetID string, f *api.Filter) (*SearchResultSnapshot, error) {\n\tresModel := struct {\n\t\tData struct {\n\t\t\tAccounts []*Account `json:\"accounts\"`\n\t\t\tServerKnowledge uint64 `json:\"server_knowledge\"`\n\t\t} `json:\"data\"`\n\t}{}\n\n\turl := fmt.Sprintf(\"/budgets/%s/accounts\", budgetID)\n\tif f != nil {\n\t\turl = fmt.Sprintf(\"%s?%s\", url, f.ToQuery())\n\t}\n\tif err := s.c.GET(url, &resModel); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SearchResultSnapshot{\n\t\tAccounts: resModel.Data.Accounts,\n\t\tServerKnowledge: resModel.Data.ServerKnowledge,\n\t}, nil\n}", "func (q *Q) GetAccountDataByKeys(keys []xdr.LedgerKeyData) ([]Data, error) {\n\tvar data []Data\n\tlkeys := make([]string, 0, len(keys))\n\tfor _, key := range keys {\n\t\tlkey, err := ledgerKeyDataToString(key)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Error running ledgerKeyTrustLineToString\")\n\t\t}\n\t\tlkeys = append(lkeys, lkey)\n\t}\n\tsql := selectAccountData.Where(map[string]interface{}{\"accounts_data.ledger_key\": lkeys})\n\terr := q.Select(&data, sql)\n\treturn data, err\n}", "func (client JobClient) ListByAccountSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, azure.DoRetryWithRegistration(client.Client))\n }", "func GetAccountsIndex(db gorm.DB, search_vars fp.SearchVars) ([]AccountView, error) {\n\n\tvar rows []AccountView\n\tfmt.Println(\"getttttts=\", search_vars)\n\n\twhere := search_vars.GetSQL(\"company\", \"acc_active\")\n\tfmt.Println(\"where=\", where)\n\tdb.Table(ACCOUNT_VIEW).Select(ACCOUNT_VIEW_COLS).Where(where).Scan(&rows)\n\n\treturn rows, nil\n\n}", "func GetAccounts(db gorm.DB) ([]AccountView, error) {\n\n\tvar rows []AccountView\n\tdb.Table(ACCOUNT_VIEW).Select(ACCOUNT_VIEW_COLS).Scan(&rows)\n\treturn rows, nil\n\n}", "func GetUsers(req *http.Request, render render.Render, account services.Account) {\n qs := req.URL.Query()\n userIDs := qs[\"userId\"]\n var users []models.User\n for _, userID := range userIDs {\n if user, err := account.GetUser(userID); err != nil {\n render.JSON(err.HttpCode, err)\n return\n } else {\n users = append(users, *user)\n }\n }\n render.JSON(http.StatusOK, users)\n}", "func SearchUsers(name string) ([]User, error) {\n\tname = strings.ToLower(name)\n\tusers, err := ListAllUsers()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfiltered := []User{}\n\tfor _, user := range users {\n\t\tif strings.Contains(user.LoginName, name) || strings.Contains(user.FullName, name) {\n\t\t\tfiltered = append(filtered, user)\n\t\t}\n\t}\n\treturn filtered, nil\n}", "func (repository *Repository) FindByEmailAndProvider(email string, provider string, unscoped bool) (*[]entity.Account, error) {\n\toutput := []entity.Account{}\n\tcondition := entity.Account{Email: email, Provider: provider}\n\tif unscoped == true {\n\t\terr := repository.connection.Unscoped().Where(condition).Find(output).Error\n\t\treturn &output, err\n\t}\n\terr := repository.connection.Where(condition).Find(&output).Error\n\treturn &output, err\n}", "func (ks *KeyStore) Accounts() ([]*accounts.Account, error) {\n\t// List all the files from the keystore folder\n\tfiles, err := ioutil.ReadDir(ks.keydir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccounts := []*accounts.Account{}\n\tfor _, fi := range files {\n\t\tpath := ks.storage.JoinPath(fi.Name())\n\t\t// Skip any non-key files from the folder\n\t\tif nonKeyFile(fi) {\n\t\t\tks.ui.Logf(\"Ignoring file on account scan: %s\\n\", path)\n\t\t\tcontinue\n\t\t}\n\t\tacc, err := readAccount(path)\n\t\tif err != nil {\n\t\t\tks.ui.Errorf(\"Error while reading keystore account from path: %s, %v\\n\", path, err)\n\t\t\tcontinue\n\t\t}\n\t\taccounts = append(accounts, acc)\n\t}\n\treturn accounts, nil\n}", "func (t *TezTracker) AccountList(before string, limits Limiter) (accs []models.AccountListView, count int64, err error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.AccountFilter{\n\t\tType: models.AccountTypeAccount,\n\t\tOrderBy: models.AccountOrderFieldCreatedAt,\n\t\tAfter: before,\n\t}\n\tcount, accs, err = r.List(limits.Limit(), limits.Offset(), filter)\n\treturn accs, count, err\n}", "func (a Accounts) Get(asset string) *Account {\n\tfor i := range a.Datas {\n\t\tif a.Datas[i].Balance.Currency == asset {\n\t\t\treturn &a.Datas[i]\n\t\t}\n\t}\n\treturn nil\n}", "func GetAllAccounts(w http.ResponseWriter, r *http.Request) {\n\t// Fetch the accounts.\n\n\tgetAccountsInput, err := parseGetAccountsInput(r)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteRequestValidationError(w, fmt.Sprintf(\"Error parsing query params\"))\n\t\treturn\n\t}\n\n\tresult, err := Dao.GetAccounts(getAccountsInput)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t\treturn\n\t}\n\n\t// Serialize them for the JSON response.\n\taccountResponses := []*response.AccountResponse{}\n\n\tfor _, a := range result.Results {\n\t\tacctRes := response.AccountResponse(*a)\n\t\taccountResponses = append(accountResponses, &acctRes)\n\t}\n\n\t// If the DB result has next keys, then the URL to retrieve the next page is put into the Link header.\n\tif len(result.NextKeys) > 0 {\n\t\tnextURL := response.BuildNextURL(r, result.NextKeys, baseRequest)\n\t\tw.Header().Add(\"Link\", fmt.Sprintf(\"<%s>; rel=\\\"next\\\"\", nextURL.String()))\n\t}\n\n\terr = json.NewEncoder(w).Encode(accountResponses)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t}\n}", "func (repository Accounts) GetAll() ([]models.Account, error) {\n\trows, err := repository.db.Query(\n\t\t\"select id, name, cpf, balance, created_at from accounts\",\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tvar accounts []models.Account\n\n\tfor rows.Next() {\n\t\tvar account models.Account\n\n\t\tif err = rows.Scan(\n\t\t\t&account.ID,\n\t\t\t&account.Name,\n\t\t\t&account.Cpf,\n\t\t\t&account.Balance,\n\t\t\t&account.CreatedAt,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\taccounts = append(accounts, account)\n\t}\n\n\treturn accounts, nil\n}", "func (r *UserRepository) GetAllByName(name string) []models.User {\n\tvar users []models.User\n\tr.C.Where(\"name = ?\", name).Find(&users)\n\treturn users\n}", "func (tk *TwitchKraken) GetUserByName(name string) (resp *Users, jsoerr *network.JSONError, err error) {\n\tresp = new(Users)\n\tjac := new(network.JSONAPIClient)\n\thMap := make(map[string]string)\n\thMap[\"Accept\"] = APIVersionHeader\n\thMap[\"Client-ID\"] = tk.ClientID\n\tjsoerr, err = jac.Request(BaseURL+\"/users?login=\"+name, hMap, &resp)\n\treturn\n}", "func (s *Single) Accounts() (accounts *Accounts) {\n\taccounts = &Accounts{}\n\terr := DB.BelongsToThrough(s, \"users\").All(accounts)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn\n}", "func (r *NucypherAccountRepository) GetAccounts(createdBy string) ([]*model.NucypherAccount, error) {\n\tvar accounts []*model.NucypherAccount\n\n\tif err := r.store.db.Select(&accounts,\n\t\t\"SELECT account_id, name, organization_id, address, signing_key, encrypting_key, balance, tokens, is_active, is_private, created_by, created_at FROM nucypher_accounts WHERE created_by=$1\",\n\t\tcreatedBy,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn accounts, nil\n}", "func (a *Client) GetAccounts(params *GetAccountsParams) (*GetAccountsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetAccountsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getAccounts\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/AccountService/Accounts\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetAccountsReader{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.(*GetAccountsOK), nil\n\n}", "func GetAccount(name string) (ethcmn.Address, error) {\n\tdir := getDir(accountDir)\n\tdb, err := leveldb.OpenFile(dir, nil)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\tdefer db.Close()\n\n\taddr, err := db.Get([]byte(name), nil)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\treturn ethcmn.BytesToAddress(addr), nil\n}", "func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, cb func(account exported.Account) (stop bool)) {\n\tstore := ctx.KVStore(ak.key)\n\titerator := sdk.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix)\n\n\tdefer iterator.Close()\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\taccount := ak.decodeAccount(iterator.Value())\n\n\t\tif cb(account) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (a *auth) getAccount(r *http.Request) (string, error) {\n\t// Create a map of prefixes to match\n\tmatchers := map[string]accountFetcher{\n\t\t\"/v1/accounts\": getAccountFromVars,\n\t\t\"/v1/devices\": a.getAccountFromDevice,\n\t}\n\t// Try to find appropriate fetcher for the route\n\tfor prefix, fetcher := range matchers {\n\t\tif strings.HasPrefix(r.URL.Path, prefix) {\n\t\t\treturn fetcher(r)\n\t\t}\n\t}\n\treturn \"\", errors.New(\"No match found\")\n}", "func Get(names []string) ([]Response, error) {\n\tnameResponses, err := defaultClient.Get(Query{Names: names})\n\treturn nameResponses, err\n}", "func (am *AccountManager) ListAccounts(minconf int) map[string]float64 {\n\t// Create and fill a map of account names and their balances.\n\tpairs := make(map[string]float64)\n\tfor _, a := range am.AllAccounts() {\n\t\tpairs[a.name] = a.CalculateBalance(minconf)\n\t}\n\treturn pairs\n}", "func (dbHandler *Handler) GetUserEntriesByName(name string) ([]api.Entry, error) {\n\tvar entries []api.Entry\n\n\tuser, err := dbHandler.GetUserByName(name)\n\tif err != nil {\n\t\treturn entries, errors.Wrap(err, \"cannot get user\")\n\t}\n\n\tdb := dbHandler.DB.Where(&api.Entry{UserID: user.ID}).Find(&entries)\n\tif db.Error != nil {\n\t\treturn entries, errors.Wrap(db.Error, \"cannot get entry\")\n\t}\n\n\treturn entries, nil\n}", "func (backend *Backend) Accounts() []accounts.Interface {\n\tdefer backend.accountsAndKeystoreLock.RLock()()\n\treturn backend.accounts\n}", "func (s *Service) FindAccountByName(name string) (*Account, error) {\n\t// Fetch the client from the database\n\taccount := new(Account)\n\tnotFound := s.db.Where(\"name = ?\", name).Preload(\"OauthClient\").\n\t\tFirst(account).RecordNotFound()\n\n\t// Not found\n\tif notFound {\n\t\treturn nil, ErrAccountNotFound\n\t}\n\n\treturn account, nil\n}", "func (_Storage *StorageCaller) Accounts(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"accounts\")\n\treturn *ret0, err\n}", "func (m *MegaCorp) getAllAccounts() (accts []*Account) {\n\trg := Me.NewRangeGetter(Ledger, \"account\", \"\", false)\n\tfor rg.HasNext() {\n\t\tvar act Account\n\t\ttx := rg.Next()\n\t\tutil.FromJSON([]byte(tx.Value), &act)\n\t\taccts = append(accts, &act)\n\t}\n\treturn\n}", "func getUsers(githubAccessToken string, githubOrganization string, githubTeams string) []githubUser {\n\n\tvar users = make([]githubUser, 0)\n\n\tctx := context.Background()\n\tgithubClient := getGithubClient(ctx, githubAccessToken)\n\tteamsIds := getTeamsIds(ctx, githubClient, githubOrganization, githubTeams)\n\tfor _, teamId := range teamsIds {\n\t\tusers = append(users, getTeamUsers(ctx, githubClient, teamId, users)...)\n\t}\n\treturn users\n}", "func (db *DB) GetClientsByUsername(username string, clients *[]Client) []error {\n\terrs := db.Joins(\"JOIN `users` ON `clients`.user_id = `users`.id AND `users`.username = ?\", username).Find(&clients).GetErrors()\n\treturn errs\n}" ]
[ "0.637644", "0.63298076", "0.6257646", "0.6228807", "0.6209985", "0.61972433", "0.6075114", "0.606668", "0.59395134", "0.5928551", "0.589412", "0.5893891", "0.5889837", "0.58318645", "0.58226526", "0.5752496", "0.57408327", "0.5739339", "0.5705747", "0.5685761", "0.5654846", "0.5642374", "0.56395304", "0.56369865", "0.5619492", "0.56149226", "0.56143457", "0.5603357", "0.5554893", "0.5552447", "0.5531637", "0.55261904", "0.55107105", "0.54753864", "0.5472408", "0.5449267", "0.54326016", "0.54316974", "0.53849506", "0.538108", "0.5378935", "0.5346409", "0.53419805", "0.5338547", "0.5316848", "0.53118604", "0.5309999", "0.5290211", "0.5289169", "0.5288066", "0.52852476", "0.52806085", "0.5277296", "0.5270739", "0.5267403", "0.52607846", "0.5254869", "0.52528834", "0.5248427", "0.5246911", "0.52357924", "0.5231395", "0.52282095", "0.5224465", "0.52237743", "0.5220421", "0.5206662", "0.51930475", "0.518681", "0.51800543", "0.5179388", "0.5176607", "0.51749015", "0.517376", "0.5165809", "0.51629376", "0.51506996", "0.5144801", "0.5138687", "0.51339823", "0.51228684", "0.5108298", "0.5107631", "0.5107314", "0.50980186", "0.5096475", "0.5087752", "0.5085011", "0.5075334", "0.50689965", "0.50643027", "0.504364", "0.5042355", "0.50408834", "0.50404745", "0.5033838", "0.5031364", "0.5030848", "0.50177515", "0.5017424" ]
0.58654314
13
GetAccountsCount returns account count
func (api *API) GetAccountsCount(ctx context.Context) (int, error) { var resp int err := api.call(ctx, "get_account_count", caller.EmptyParams, &resp) return resp, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_FCToken *FCTokenCaller) GetAccountCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"getAccountCount\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_FCToken *FCTokenSession) GetAccountCount() (*big.Int, error) {\n\treturn _FCToken.Contract.GetAccountCount(&_FCToken.CallOpts)\n}", "func (_FCToken *FCTokenCallerSession) GetAccountCount() (*big.Int, error) {\n\treturn _FCToken.Contract.GetAccountCount(&_FCToken.CallOpts)\n}", "func countTotalAccounts(db *sqlite.Driver) (int, error) {\n\tvar err error\n\tvar stmt = fmt.Sprintf(\"select count(*) from %s\", tableName)\n\n\tvar count int\n\tif err = db.QueryRow(stmt).Scan(&count); err != nil {\n\t\treturn 0, SQLExecutionError(err)\n\t}\n\treturn count, nil\n}", "func (db *Database) GetAccountCount(ip string) (int, error) {\n\trow := db.db.QueryRow(`\n\t\tSELECT COUNT(*) FROM melodious.accounts WHERE ip=$1;\n\t`, ip)\n\tvar count int\n\terr := row.Scan(&count)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn count, nil\n}", "func (p *bitsharesAPI) GetAccountCount() (uint64, error) {\n\tvar count objects.UInt64\n\terr := p.call(p.databaseAPIID, \"get_account_count\", &count)\n\treturn uint64(count), err\n}", "func (list *AccountList) Count() (*int64, error) {\n\treturn list.CountWithContext(context.Background())\n}", "func (_Storage *StorageSession) Accounts() (*big.Int, error) {\n\treturn _Storage.Contract.Accounts(&_Storage.CallOpts)\n}", "func GetnumAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetnumberAccountsAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\t// data := map[string]int{\n\t// \t\"NumberOfAccounts\": len(accountdb.GetAllAccounts()),\n\t// }\n\t// var responsedata globalPkg.StructData\n\t// for key, value := range data {\n\t// \tresponsedata.Name = key\n\t// \tresponsedata.Length = value\n\t// }\n\t// jsonObj, _ := json.Marshal(responsedata)\n\n\tglobalPkg.SendResponseMessage(w, strconv.Itoa(len(accountdb.GetAllAccounts())))\n\tlogobj.OutputData = \"success to get number of accounts\"\n\tlogobj.Process = \"success\"\n\tglobalPkg.WriteLog(logobj, \"success to get number of accounts\", \"success\")\n\n}", "func (_Storage *StorageCallerSession) Accounts() (*big.Int, error) {\n\treturn _Storage.Contract.Accounts(&_Storage.CallOpts)\n}", "func (_ArbSys *ArbSysCallerSession) GetTransactionCount(account common.Address) (*big.Int, error) {\n\treturn _ArbSys.Contract.GetTransactionCount(&_ArbSys.CallOpts, account)\n}", "func (_Storage *StorageCaller) Accounts(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"accounts\")\n\treturn *ret0, err\n}", "func (_ArbSys *ArbSysSession) GetTransactionCount(account common.Address) (*big.Int, error) {\n\treturn _ArbSys.Contract.GetTransactionCount(&_ArbSys.CallOpts, account)\n}", "func (kph *keePassHTTP) Count(filter *Filter) (credentialsCount int, err error) {\n\tresult, err := kph.request(&body{\n\t\tRequestType: \"get-logins-count\",\n\t\tUrl: filter.Url,\n\t\tSubmitUrl: filter.SubmitUrl,\n\t\tRealm: filter.Realm,\n\t})\n\n\tif err == nil && result != nil {\n\t\tcredentialsCount = result.Count\n\t}\n\treturn\n}", "func (acc *Account) TxCount() (hexutil.Uint64, error) {\n\t// get the sender by address\n\tbal, err := repository.R().AccountNonce(&acc.Address)\n\tif err != nil {\n\t\treturn hexutil.Uint64(0), err\n\t}\n\n\treturn *bal, nil\n}", "func (env *ExecuteEnv) GetAnsCount() (int64, error) {\n\treturn int64(len(env.reports)), nil\n}", "func (env *BaseEnv) GetAnsCount() (int64, error) {\n\treturn 0, api.ErrWrongPeriodAction\n}", "func (accounts *Accounts) Len() int {\n\tif (accounts == nil) || (accounts.Map == nil) {\n\t\treturn 0\n\t}\n\treturn len(accounts.Map)\n}", "func GetCount() (int, error) {\n\tvar count int\n\tdb := common.GetDB()\n\tvar cts []Contact\n\terr := db.Find(&cts).Count(&count).Error\n\treturn count, err\n}", "func (zs *CompanyWebsiteService) Count(opts ...Option) (int, error) {\n\tct, err := zs.client.getCount(zs.end, opts...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"cannot count CompanyWebsites\")\n\t}\n\n\treturn ct, nil\n}", "func (a *Account) GetCounters(filter string) (AccountGetCountersResponse, error) {\n\tparams := map[string]string{\"filter\": filter }\n\tresp, err := a.vk.Request(\"account.getCounters\", params)\n\tif err != nil {\n\t\treturn AccountGetCountersResponse{}, err\n\t}\n\tvar counters AccountGetCountersResponse\n\terr = json.Unmarshal(resp, &counters)\n\tif err != nil {\n\t\treturn AccountGetCountersResponse{}, err\n\t}\n\treturn counters, nil\n}", "func (q authQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count auths rows\")\n\t}\n\n\treturn count, nil\n}", "func (r Notification_Occurrence_Event) GetImpactedAccountCount() (resp int, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Notification_Occurrence_Event\", \"getImpactedAccountCount\", nil, &r.Options, &resp)\n\treturn\n}", "func (us *UserService) Count(a AdminCriteria) (int, error) {\n\treturn us.Datasource.Count(a)\n}", "func (_ArbSys *ArbSysCaller) GetTransactionCount(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ArbSys.contract.Call(opts, &out, \"getTransactionCount\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_FCToken *FCTokenCallerSession) GetCounts(id uint8) (*big.Int, error) {\n\treturn _FCToken.Contract.GetCounts(&_FCToken.CallOpts, id)\n}", "func (s UserSet) CompaniesCount() int {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"CompaniesCount\", \"companies_count\")).(int)\n\treturn res\n}", "func (_FCToken *FCTokenCaller) GetCounts(opts *bind.CallOpts, id uint8) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"getCounts\", id)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (n *NodeServiceImpl) Count(namespace string) (map[string]int, error) {\n\tlist, err := n.List(namespace, &models.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn map[string]int{\n\t\tplugin.QuotaNode: len(list.Items),\n\t}, nil\n}", "func (_FCToken *FCTokenSession) Accounts(arg0 *big.Int) (common.Address, error) {\n\treturn _FCToken.Contract.Accounts(&_FCToken.CallOpts, arg0)\n}", "func (_FCToken *FCTokenSession) GetCounts(id uint8) (*big.Int, error) {\n\treturn _FCToken.Contract.GetCounts(&_FCToken.CallOpts, id)\n}", "func (t *TezTracker) AccountList(before string, limits Limiter) (accs []models.AccountListView, count int64, err error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.AccountFilter{\n\t\tType: models.AccountTypeAccount,\n\t\tOrderBy: models.AccountOrderFieldCreatedAt,\n\t\tAfter: before,\n\t}\n\tcount, accs, err = r.List(limits.Limit(), limits.Offset(), filter)\n\treturn accs, count, err\n}", "func (b *GetParticipantsQueryBuilder) Count(ctx context.Context) (int, error) {\n\titer := b.Iter()\n\tc, err := iter.Total(ctx)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"get total\")\n\t}\n\treturn c, nil\n}", "func (_Harberger *HarbergerCaller) AssetsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Harberger.contract.Call(opts, out, \"assetsCount\")\n\treturn *ret0, err\n}", "func (r UsersResolver) TotalCount() int32 {\n\treturn int32(r.users.TotalCount)\n}", "func (_FCToken *FCTokenCallerSession) Accounts(arg0 *big.Int) (common.Address, error) {\n\treturn _FCToken.Contract.Accounts(&_FCToken.CallOpts, arg0)\n}", "func (t *TezTracker) AccountList(before string, limits Limiter, favorites []string) (accs []models.AccountListView, count int64, err error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.AccountFilter{\n\t\tType: models.AccountTypeAccount,\n\t\tOrderBy: models.AccountOrderFieldCreatedAt,\n\t\tAfter: before,\n\t\tFavorites: favorites,\n\t}\n\tcount, accs, err = r.List(limits.Limit(), limits.Offset(), filter)\n\treturn accs, count, err\n}", "func (q tenantQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"dbmodel: failed to count tenants rows\")\n\t}\n\n\treturn count, nil\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\trepository := repositories.NewAccountRepository(db)\n\taccounts, erro := repository.FindAll()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, accounts)\n}", "func (_OracleMgr *OracleMgrCaller) GetDepositCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _OracleMgr.contract.Call(opts, out, \"getDepositCount\")\n\treturn *ret0, err\n}", "func (_Gatekeeper *GatekeeperCaller) GetRootsCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetRootsCount\")\n\treturn *ret0, err\n}", "func (c *GethClient) Accounts(ctx context.Context) ([]string, error) {\n\tvar result []string\n\terr := c.rpcCli.CallContext(ctx, &result, \"personal_listAccounts\")\n\treturn result, err\n}", "func (q authTokenQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count auth_tokens rows\")\n\t}\n\n\treturn count, nil\n}", "func (controller *AccountController) GetAccounts(ctx *gin.Context) {\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\taccs, err := controller.service.GetAccounts(info.Name)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Account Error GetAll\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"Could not get accounts because: \" + err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\tresponse, _ := restapi.NewOkResponse(accs).Marshal()\n\tfmt.Fprint(ctx.Writer, string(response))\n\tctx.Next()\n\n}", "func (_Harberger *HarbergerCallerSession) AssetsCount() (*big.Int, error) {\n\treturn _Harberger.Contract.AssetsCount(&_Harberger.CallOpts)\n}", "func (_OracleMgr *OracleMgrCallerSession) GetDepositCount() (*big.Int, error) {\n\treturn _OracleMgr.Contract.GetDepositCount(&_OracleMgr.CallOpts)\n}", "func (q oauthClientQuery) Count(exec boil.Executor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count oauth_clients rows\")\n\t}\n\n\treturn count, nil\n}", "func (_OracleMgr *OracleMgrSession) GetDepositCount() (*big.Int, error) {\n\treturn _OracleMgr.Contract.GetDepositCount(&_OracleMgr.CallOpts)\n}", "func (m *SearchBucket) GetCount()(*int32) {\n return m.count\n}", "func (list *BillingInfoList) Count() (*int64, error) {\n\treturn list.CountWithContext(context.Background())\n}", "func (a *Api) GetAccounts(ctx echo.Context) error {\n\t// var result []Account\n\tvar accounts []Account\n\n\tdbResult := a.DB.Find(&accounts)\n\tif dbResult.Error != nil {\n\t\treturn sendApiError(ctx, http.StatusInternalServerError, \"DB error\")\n\t}\n\n\treturn ctx.JSONPretty(http.StatusOK, accounts, \" \")\n}", "func GetCount(c *gin.Context) {\n\tstore := c.MustGet(\"store\").(*Store)\n\n\tc.JSON(http.StatusOK, store.Count())\n}", "func GetnumberAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetnumberAccountsAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tdata := map[string]interface{}{\n\t\t\t\"Number_Of_Accounts\": len(accountdb.GetAllAccounts()),\n\t\t}\n\t\tjsonObj, _ := json.Marshal(data)\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tlogobj.OutputData = \"success to get number of accounts\"\n\t\tlogobj.Process = \"success\"\n\t\tglobalPkg.WriteLog(logobj, \"success to get number of accounts\", \"success\")\n\t} else {\n\t\tglobalPkg.SendError(w, \"you are not admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all Emails and username \", \"failed\")\n\n\t}\n}", "func (sc Funcs) Accounts(ctx wasmlib.ScViewClientContext) *AccountsCall {\n\tf := &AccountsCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccounts)}\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func (s kw_rest_admin) UserCount(emails []string, params ...interface{}) (users int, err error) {\n\tvar user []struct{}\n\tif emails != nil && emails[0] != NONE {\n\t\tfor _, u := range emails {\n\t\t\terr = s.DataCall(APIRequest{\n\t\t\t\tMethod: \"GET\",\n\t\t\t\tPath: \"/rest/admin/users\",\n\t\t\t\tParams: SetParams(Query{\"email\": u}, params),\n\t\t\t\tOutput: &user}, -1, 1000)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tusers = len(user) + users\n\t\t}\n\t\treturn\n\t}\n\terr = s.DataCall(APIRequest{\n\t\tMethod: \"GET\",\n\t\tPath: \"/rest/admin/users\",\n\t\tParams: SetParams(params),\n\t\tOutput: &user}, -1, 1000)\n\treturn len(user), err\n}", "func azCount(subnets map[string]string) int {\n\tvar result int\n\tfor k := range subnets {\n\t\tif k != subnetAllAZName {\n\t\t\tresult++\n\t\t}\n\t}\n\treturn result\n}", "func (r *projectTypeConnectionResolver) TotalCount(ctx context.Context) *int32 {\n\treturn &r.totalCount\n}", "func (nsq *NamespaceSecretQuery) Count(ctx context.Context) (int, error) {\n\tif err := nsq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn nsq.sqlCount(ctx)\n}", "func (q authUserQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count auth_user rows\")\n\t}\n\n\treturn count, nil\n}", "func (db *PSQL) CountOrganizations() (int, error) {\n\treturn 0, nil\n}", "func (m *ManagementTemplateStepTenantSummary) GetCompliantTenantsCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"compliantTenantsCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (_Harberger *HarbergerSession) AssetsCount() (*big.Int, error) {\n\treturn _Harberger.Contract.AssetsCount(&_Harberger.CallOpts)\n}", "func Accounts(client *ticketmatic.Client) ([]*ticketmatic.AccountInfo, error) {\n\tr := client.NewRequest(\"GET\", \"/_/tools/accounts\", \"json\")\n\n\tvar obj []*ticketmatic.AccountInfo\n\terr := r.Run(&obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}", "func (_Gatekeeper *GatekeeperCallerSession) GetRootsCount() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetRootsCount(&_Gatekeeper.CallOpts)\n}", "func (dl *DelegatorList) TotalCount() hexutil.Big {\n\tval := (*hexutil.Big)(big.NewInt(int64(len(dl.list))))\n\treturn *val\n}", "func (a API) GetConnectionCount(cmd *None) (e error) {\n\tRPCHandlers[\"getconnectioncount\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (a *SchedulesApiService) OrganizationsOrganizationIdAccountsAccountIdSchedulesCountGet(ctx context.Context, accountId string, organizationId string) (Count, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tsuccessPayload Count\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/organizations/{organization_id}/accounts/{account_id}/schedules/count\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"account_id\"+\"}\", fmt.Sprintf(\"%v\", accountId), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"organization_id\"+\"}\", fmt.Sprintf(\"%v\", organizationId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t}\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func (t *txLookUp) Count() int {\n\tt.mu.RLock()\n\tdefer t.mu.RUnlock()\n\n\treturn t.count()\n}", "func GetTotalNumberOfUsers(e Executor) (uint64, error) {\n\treq, _ := http.NewRequest(\"GET\", RexBaseURL+apiUsers, nil)\n\n\tresp, err := e.Execute(req)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer func() {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\t}()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn gjson.Get(string(body), \"page.totalElements\").Uint(), nil\n}", "func (_Gatekeeper *GatekeeperSession) GetRootsCount() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetRootsCount(&_Gatekeeper.CallOpts)\n}", "func (s *Storage) CountUsers() int {\n\tvar result int\n\terr := s.db.QueryRow(`SELECT count(*) FROM users`).Scan(&result)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn result\n}", "func (ps *PersonService) Count(opts ...FuncOption) (int, error) {\n\tct, err := ps.client.getEndpointCount(PersonEndpoint, opts...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn ct, nil\n}", "func (t *txLookup) Count() int {\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\n\treturn len(t.all)\n}", "func (h HMSketch) TotalCount() float64 {\n\treturn h.global().Total()\n}", "func (fs *FollowService) Count(opts ...Option) (int, error) {\n\tct, err := fs.client.getCount(fs.end, opts...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"cannot count Follows\")\n\t}\n\n\treturn ct, nil\n}", "func (d *Database) CountUsers() int {\n\treturn len(d.ListUsers())\n}", "func (_UserCrud *UserCrudCaller) GetUserCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _UserCrud.contract.Call(opts, out, \"getUserCount\")\n\treturn *ret0, err\n}", "func (o GetRulesRuleComplianceOutput) Count() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetRulesRuleCompliance) int { return v.Count }).(pulumi.IntOutput)\n}", "func (s *UserStore) Count(q *UserQuery) (int64, error) {\n\treturn s.Store.Count(q)\n}", "func (store *EntryStore) Count() int64 {\n\tprop := store.db.GetProperty(\"rocksdb.estimate-num-keys\")\n\tc, _ := strconv.ParseInt(prop, 10, 64)\n\treturn c\n}", "func (ps *PlatformWebsiteService) Count(opts ...Option) (int, error) {\n\tct, err := ps.client.getCount(ps.end, opts...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"cannot count PlatformWebsites\")\n\t}\n\n\treturn ct, nil\n}", "func (ps *peerStore) Count(infoHash InfoHash) int {\n\tset := ps.Set(infoHash)\n\tif set == nil {\n\t\treturn 0\n\t}\n\n\treturn set.Size()\n}", "func (instance *DSInstance) Count(ctx context.Context, query *datastore.Query) (int, error) {\n\treturn instance.client.Count(ctx, query)\n}", "func (r *APIClientRepository) Accounts() (gin.Accounts, error) {\n\tclients := []domain.APIClient{}\n\tif err := r.DB.Select(&clients, \"select * from api_clients\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\taccounts := gin.Accounts{}\n\tfor _, client := range clients {\n\t\taccounts[client.Key] = client.Secret\n\t}\n\n\treturn accounts, nil\n}", "func (ar *ActiveRecord) GetCount(args ...interface{}) (count int, err error) {\n\tif err = ar.DB.QueryRow(ar.ExecString(), ar.Args...).Scan(&count); err != nil {\n\t\treturn 0, err\n\t}\n\treturn count, nil\n}", "func (rep *UserRepository) TotalCount() (count int64, err error) {\n\terr = databaseConnection.Model(&models.User{}).Count(&count).Error\n\tif err != nil {\n\t\tlog.Error(0, \"Error counting total sessions: %v\", err)\n\t\treturn\n\t}\n\treturn\n}", "func (m *TeamSummary) GetOwnersCount()(*int32) {\n return m.ownersCount\n}", "func (pca Client) Accounts(ctx context.Context) ([]Account, error) {\n\treturn pca.base.AllAccounts(ctx)\n}", "func (s *Stat) GetCount() int {\n\treturn s.n\n}", "func (atc *AtomicTransactionComposer) Count() int {\n\treturn len(atc.txContexts)\n}", "func (m *ManagementTemplateStepTenantSummary) GetAssignedTenantsCount()(*int32) {\n val, err := m.GetBackingStore().Get(\"assignedTenantsCount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (o GetKubernetesClusterAgentPoolProfileOutput) Count() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetKubernetesClusterAgentPoolProfile) int { return v.Count }).(pulumi.IntOutput)\n}", "func (p *Partition) OwnerCount() int {\n\towners := p.owners.Load()\n\tif owners == nil {\n\t\treturn 0\n\t}\n\treturn len(owners.([]discovery.Member))\n}", "func (cs *CoverService) Count(opts ...Option) (int, error) {\n\tct, err := cs.client.getCount(cs.end, opts...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"cannot count Covers\")\n\t}\n\n\treturn ct, nil\n}", "func (s *Service) Count(userId string) (uint, error) {\n\tcount, err := s.repository.CountByUserId(userId)\n\tif nil != err {\n\t\tlog.Printf(\"tan service failed to count TANs for user %s: %s\", userId, err.Error())\n\t\treturn 0, err\n\t}\n\treturn count, nil\n}", "func (s *Srt) GetCount() int {\n\treturn s.count\n}", "func (q utxoQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count utxo rows\")\n\t}\n\n\treturn count, nil\n}", "func (_UserCrud *UserCrudSession) GetUserCount() (*big.Int, error) {\n\treturn _UserCrud.Contract.GetUserCount(&_UserCrud.CallOpts)\n}", "func (m *TeamsAsyncOperation) GetAttemptsCount()(*int32) {\n return m.attemptsCount\n}", "func (v Account) GetCounters(params AccountGetCountersParams) (*AccountGetCountersResponse, error) {\n\tr, err := v.API.Request(\"account.getCounters\", params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp AccountGetCountersResponse\n\terr = json.Unmarshal(r, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}" ]
[ "0.7629392", "0.7616788", "0.7604881", "0.76005614", "0.75523543", "0.7378767", "0.73631734", "0.68072057", "0.67254966", "0.6607631", "0.6525248", "0.64642614", "0.64617866", "0.642899", "0.6358162", "0.63580036", "0.6307512", "0.6102952", "0.6097889", "0.6087178", "0.60265404", "0.60257107", "0.6021735", "0.60046715", "0.59992963", "0.59923613", "0.597823", "0.59700626", "0.5964685", "0.59450996", "0.5914124", "0.5905055", "0.59003925", "0.58958524", "0.5876828", "0.586448", "0.58563596", "0.5849862", "0.5833832", "0.5827498", "0.58164716", "0.5815601", "0.58028424", "0.5780428", "0.5770223", "0.57644427", "0.57630515", "0.57478833", "0.57407635", "0.5735905", "0.57292753", "0.57218546", "0.5715168", "0.5699339", "0.56978536", "0.5696678", "0.5695123", "0.56948596", "0.5694708", "0.5693791", "0.56913763", "0.5685688", "0.5676233", "0.5670496", "0.56704015", "0.5667901", "0.56638986", "0.56625134", "0.5662158", "0.5659861", "0.5658566", "0.56560755", "0.5654938", "0.5654559", "0.56542367", "0.5642611", "0.5637124", "0.5632546", "0.5628828", "0.5626108", "0.5625952", "0.56201214", "0.5619088", "0.5609226", "0.5608158", "0.5607586", "0.56022424", "0.55953556", "0.55869734", "0.5579442", "0.5574464", "0.5571967", "0.5569963", "0.55636764", "0.5560916", "0.5557668", "0.5554025", "0.55520475", "0.5549283", "0.55470026" ]
0.8077577
0
LookupAccounts get names and IDs for registered accounts. lowerBoundName Lower bound of the first name to return. limit Maximum number of results to return must not exceed 1000
func (api *API) LookupAccounts(ctx context.Context, lowerBoundName string, limit uint16) ([]string, error) { var resp []string err := api.call(ctx, "lookup_accounts", []interface{}{lowerBoundName, limit}, &resp) return resp, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *GethClient) Accounts(ctx context.Context) ([]string, error) {\n\tvar result []string\n\terr := c.rpcCli.CallContext(ctx, &result, \"personal_listAccounts\")\n\treturn result, err\n}", "func getAccount(addrs []string) ([]*account, []string, error) {\n\tstartWorker()\n\n\ttotalTask := len(addrs)\n\tresult := make([]*account, 0, len(addrs))\n\tbadAddr := make([]string, 0, len(addrs))\n\tlock := new(sync.Mutex)\n\twg := new(sync.WaitGroup)\n\n\tif len(addrs) > getAccountWorkerLimit {\n\t\tgo getAcoountF(addrs[0:len(addrs)-getAccountWorkerLimit], &result, &badAddr, lock, wg)\n\t\taddrs = addrs[len(addrs)-getAccountWorkerLimit:]\n\t}\n\n\tclient := grpcclient.GetRandomSolidity()\n\t// client1 := grpcclient.GetRandomWallet()\n\n\terrCnt := 0\n\n\trestAddr := make([]string, 0, len(addrs))\n\taccountList := make([]*account, 0, len(addrs))\n\tbad := make([]string, 0, len(addrs))\n\n\tfor _, addr := range addrs {\n\t\tif !utils.VerifyTronAddrByte([]byte(addr)) {\n\t\t\tbad = append(bad, addr)\n\t\t\tcontinue\n\t\t}\n\n\t\tacc, err := client.GetAccountRawAddr(([]byte(addr)))\n\t\tif nil != err || nil == acc || len(acc.Address) == 0 {\n\t\t\terrCnt++\n\t\t\trestAddr = append(restAddr, addr)\n\t\t\tif errCnt >= maxErrCnt {\n\t\t\t\tclient = grpcclient.GetRandomSolidity()\n\t\t\t\terrCnt = 0\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// accNet, err := client1.GetAccountNetRawAddr([]byte(addr))\n\t\t// if nil != err || nil == accNet {\n\t\t// \terrCnt++\n\t\t// \trestAddr = append(restAddr, addr)\n\t\t// \tif errCnt > maxErrCnt {\n\t\t// \t\tclient1 = grpcclient.GetRandomWallet()\n\t\t// \t\terrCnt = 0\n\t\t// \t}\n\t\t// \tcontinue\n\t\t// }\n\n\t\tacct := new(account)\n\t\tacct.SetRaw(acc)\n\t\t// acct.SetNetRaw(accNet)\n\t\taccountList = append(accountList, acct)\n\t}\n\n\tif len(restAddr) > 0 {\n\t\tgo getAcoountF(restAddr, &result, &badAddr, lock, wg)\n\t}\n\n\twaitCnt := 3\n\tlock.Lock()\n\tresult = append(result, accountList...)\n\tbadAddr = append(badAddr, bad...)\n\tlock.Unlock()\n\tfmt.Printf(\"***** main routine, working task:%v, current account result count:%v, badAddr:%v, waitCnt:%v\\n\", workingTaskCnt(), len(result), len(badAddr), waitCnt)\n\n\tfor {\n\t\tworkCnt := workingTaskCnt()\n\t\tlock.Lock()\n\t\tfmt.Printf(\"***** main routine, working task:%v, current account result count:%v (total:%v), badAddr:%v, waitCnt:%v\\n\", workCnt, len(result), totalTask, len(badAddr), waitCnt)\n\t\tlock.Unlock()\n\n\t\tif workCnt == 1 {\n\t\t\twaitCnt--\n\t\t}\n\t\tif waitCnt <= 0 {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\t}\n\n\t// storeAccount(accountList)\n\n\tstopWorker()\n\n\tprocess := int64(0)\n\tgetAccountNet(result, &process, lock)\n\n\treturn result, badAddr, nil\n}", "func FindAcc(w http.ResponseWriter, req *http.Request) {\n\t//io.WriteString(w, \"Alle Accounts Anzeigen!\"+\"\\n\")\n\tallAcc(w)\n}", "func (authcl *Client) SearchAccount(query string) ([]gin.Account, error) {\n\tvar accs []gin.Account\n\n\tparams := url.Values{}\n\tparams.Add(\"q\", query)\n\taddress := fmt.Sprintf(\"/api/accounts?%s\", params.Encode())\n\tres, err := authcl.Get(address)\n\tif err != nil {\n\t\treturn accs, err\n\t} else if res.StatusCode != http.StatusOK {\n\t\treturn accs, fmt.Errorf(\"[Account search] Failed. Server returned: %s\", res.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn accs, err\n\t}\n\n\terr = json.Unmarshal(body, &accs)\n\treturn accs, err\n}", "func AccountsWithRange(lower, count int) (*[]AccountModel, error) {\n\tvar result = &[]AccountModel{}\n\tvar err error\n\tvar rawResult orm.RawSeter\n\n\to := GetOrmObject()\n\tsqlQuery := fmt.Sprintf(\"SELECT * FROM %s LIMIT %d OFFSET %d\", AccountTable, count, lower)\n\trawResult = o.Raw(sqlQuery)\n\n\t_, err = rawResult.QueryRows(result)\n\tif err != nil {\n\n\t\tbeego.Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func (t *SimpleChaincode) query_account_names (stub shim.ChaincodeStubInterface, args []string) pb.Response {\n if len(args) != 0 {\n return shim.Error(fmt.Sprintf(\"Incorrect number of arguments. Expecting 0 arguments, got %v\", args))\n }\n\n // only Admin is allowed to query_account_names\n if !transactor_is_admin(stub) {\n return shim.Error(\"Only admin user is authorized to query_account_names\")\n }\n\n account_names,err := get_account_names_(stub)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"Could not query_account_names due to error %v\", err.Error()))\n }\n\n var bytes []byte\n if len(account_names) == 0 {\n bytes = []byte(\"[]\")\n } else {\n // Serialize account names as JSON\n bytes,err = json.Marshal(account_names)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"Serializing account names failed in query_account_names because json.Marshal failed with error %v\", err))\n }\n }\n fmt.Printf(\"query_account_names response: %s\\n\", string(bytes))\n return shim.Success(bytes)\n}", "func listAccountsRecord(db *sqlite.Driver, filter AccountsFilter) ([]Account, error) {\n\tvar err error\n\tvar rows *sql.Rows\n\n\t// if true, prepend \"where\" statement on the query string\n\tvar whereFlag = false\n\tvar conditionBlocks = []string{}\n\tvar valueBlocks = []interface{}{}\n\n\tif filter.nameLike != nil {\n\t\twhereFlag = true\n\t\tconditionBlocks = append(conditionBlocks, \"name like ?\")\n\t\tvalueBlocks = append(valueBlocks, *(filter.nameLike))\n\t}\n\t// limit\n\tif filter.limit != nil {\n\t\tif *(filter.limit) < 0 {\n\t\t\treturn nil, ValidationError(\"limit < 0\")\n\t\t}\n\n\t\tconditionBlocks = append(conditionBlocks, \"limit ?\")\n\t\tvalueBlocks = append(valueBlocks, *(filter.limit))\n\t}\n\t// offset\n\tif filter.limit != nil && filter.offset != nil {\n\t\tif *(filter.offset) < 0 {\n\t\t\treturn nil, ValidationError(\"offset < 0\")\n\t\t}\n\n\t\tconditionBlocks = append(conditionBlocks, \"offset ?\")\n\t\tvalueBlocks = append(valueBlocks, *(filter.offset))\n\t}\n\t// add \"where\" statement if necessary\n\tif whereFlag {\n\t\tconditionBlocks = append([]string{\"where\"}, conditionBlocks...)\n\t}\n\tvar accounts []Account\n\n\t// query statement\n\tvar stmt = fmt.Sprintf(\"select %s from %s %s\", listColumns, tableName, strings.Join(conditionBlocks, \" \"))\n\tif rows, err = db.Query(stmt, valueBlocks...); err != nil {\n\t\treturn nil, SQLExecutionError(err)\n\t}\n\n\tfor rows.Next() {\n\t\tvar newAccount Account\n\t\tif err = rows.Scan(&newAccount.ID, &newAccount.Name, &newAccount.PermLevel); err != nil {\n\t\t\treturn nil, SQLExecutionError(err)\n\t\t}\n\n\t\taccounts = append(accounts, newAccount)\n\t}\n\n\treturn accounts, nil\n}", "func (a *AccountClient) List(paging PagingParams) (*Resources, error) {\n\n\tr := a.client.R().SetResult(&Resources{})\n\n\tif paging.number != \"\" {\n\t\tr.SetQueryParam(\"page[number]\", paging.number)\n\t}\n\n\tif paging.size != \"\" {\n\t\tr.SetQueryParam(\"page[size]\", paging.size)\n\t}\n\tresp, err := r.Get(\"/v1/organisation/accounts\")\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"list accounts failed: %s\", err)\n\t}\n\n\tif resp.Error() != nil {\n\t\treturn nil, getAPIError(resp)\n\t}\n\n\treturn resp.Result().(*Resources), nil\n}", "func LookupAccount(stmt *sql.Stmt, param string, usingId bool) (*ACCOUNT, error) {\n\tresult := new(ACCOUNT)\n\n\trows, err := stmt.Query(param)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tn, cd sql.NullString\n\t\t\tv, e sql.NullBool\n\t\t)\n\n\t\terr := rows.Scan(&n, &cd, &v, &e)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t} else {\n\t\t\tif usingId {\n\t\t\t\tresult.Id = param\n\t\t\t\tresult.Email = n.String\n\t\t\t} else {\n\t\t\t\tresult.Id = n.String\n\t\t\t\tresult.Email = param\n\t\t\t}\n\t\t\tresult.APICode = cd.String\n\t\t\tresult.Verified = v.Bool\n\t\t\tresult.Enabled = e.Bool\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn result, nil\n}", "func FindAccounts(tx *storage.Connection, userID uuid.UUID, pageParams *Pagination, sortParams *SortParams) ([]*Account, error) {\n\taccounts := []*Account{}\n\tvar err error\n\n\tpop.Debug = true\n\tq := tx.Q()\n\tif userID.String() != \"00000000-0000-0000-0000-000000000000\" {\n\t\t// UserID is not nil, so we have to query for the relations from\n\t\t// account_user\n\t\tq.RawQuery(`\n\t\tSELECT\n\t\t\taccounts.id as id,\n\t\t\taccounts.name as name,\n\t\t\taccounts.billing_name as billing_name,\n\t\t\taccounts.billing_email as billing_email,\n\t\t\taccounts.billing_details as billing_details,\n\t\t\taccounts.billing_period as billing_period,\n\t\t\taccounts.payment_method_id as payment_method_id,\n\t\t\taccounts.raw_owner_ids as raw_owner_ids,\n\t\t\taccounts.raw_account_meta_data as raw_account_meta_data,\n\t\t\taccounts.created_at as created_at,\n\t\t\taccounts.updated_at as updated_at\n\t\tFROM\n\t\t\taccounts_users as accounts_users\n\t\t\tJOIN accounts ON accounts.id = accounts_users.account_id\n\t\tWHERE\n\t\t\taccounts_users.user_id = ?`, userID)\n\n\t\terr = q.Eager(\"Roles\").All(&accounts)\n\t\treturn accounts, err\n\t}\n\n\tif sortParams != nil && len(sortParams.Fields) > 0 {\n\t\tfor _, field := range sortParams.Fields {\n\t\t\tq = q.Order(field.Name + \" \" + string(field.Dir))\n\t\t}\n\t}\n\n\tif pageParams != nil {\n\t\terr = q.Paginate(int(pageParams.Page), int(pageParams.PerPage)).Eager(\"Roles\").All(&accounts)\n\t\tpageParams.Count = uint64(q.Paginator.TotalEntriesSize)\n\t} else {\n\t\terr = q.Eager(\"Roles\").All(&accounts)\n\t}\n\treturn accounts, err\n}", "func (_FCToken *FCTokenSession) Accounts(arg0 *big.Int) (common.Address, error) {\n\treturn _FCToken.Contract.Accounts(&_FCToken.CallOpts, arg0)\n}", "func (_FCToken *FCTokenCaller) Accounts(opts *bind.CallOpts, arg0 *big.Int) (common.Address, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"accounts\", arg0)\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_FCToken *FCTokenCallerSession) Accounts(arg0 *big.Int) (common.Address, error) {\n\treturn _FCToken.Contract.Accounts(&_FCToken.CallOpts, arg0)\n}", "func ListAccounts(w http.ResponseWriter, r *http.Request) {\n\tisAdmin := false\n\tif oauth, ok := OAuthToken(r); ok {\n\t\tisAdmin = oauth.Match.Contains(\"account-admin\")\n\t}\n\n\tvar accounts []data.Account\n\tsearch := r.URL.Query().Get(\"q\")\n\tif search != \"\" {\n\t\taccounts = data.SearchAccounts(search)\n\t} else {\n\t\taccounts = data.ListAccounts()\n\t}\n\n\tmarshal := make([]data.AccountMarshaler, 0, len(accounts))\n\tfor i := 0; i < len(accounts); i++ {\n\t\tacc := &accounts[i]\n\t\tmarshal = append(marshal, data.AccountMarshaler{\n\t\t\tWithMail: isAdmin || acc.IsEmailPublic,\n\t\t\tWithAffiliation: isAdmin || acc.IsAffiliationPublic,\n\t\t\tAccount: acc,\n\t\t})\n\t}\n\n\tw.Header().Add(\"Cache-Control\", \"no-cache\")\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(marshal)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (s *Identity) AccountsGET(w http.ResponseWriter, r *http.Request) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\twriteResponse(s.addresses, w, r)\n}", "func (s *Service) GetAccounts(budgetID string, f *api.Filter) (*SearchResultSnapshot, error) {\n\tresModel := struct {\n\t\tData struct {\n\t\t\tAccounts []*Account `json:\"accounts\"`\n\t\t\tServerKnowledge uint64 `json:\"server_knowledge\"`\n\t\t} `json:\"data\"`\n\t}{}\n\n\turl := fmt.Sprintf(\"/budgets/%s/accounts\", budgetID)\n\tif f != nil {\n\t\turl = fmt.Sprintf(\"%s?%s\", url, f.ToQuery())\n\t}\n\tif err := s.c.GET(url, &resModel); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &SearchResultSnapshot{\n\t\tAccounts: resModel.Data.Accounts,\n\t\tServerKnowledge: resModel.Data.ServerKnowledge,\n\t}, nil\n}", "func (client *ClientImpl) GetAccounts(ctx context.Context, args GetAccountsArgs) (*[]Account, error) {\n\tqueryParams := url.Values{}\n\tif args.OwnerId != nil {\n\t\tqueryParams.Add(\"ownerId\", (*args.OwnerId).String())\n\t}\n\tif args.MemberId != nil {\n\t\tqueryParams.Add(\"memberId\", (*args.MemberId).String())\n\t}\n\tif args.Properties != nil {\n\t\tqueryParams.Add(\"properties\", *args.Properties)\n\t}\n\tlocationId, _ := uuid.Parse(\"229a6a53-b428-4ffb-a835-e8f36b5b4b1e\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"7.1-preview.1\", nil, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue []Account\n\terr = client.Client.UnmarshalCollectionBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\tdb, erro := database.Connect()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tdefer db.Close()\n\trepository := repositories.NewAccountRepository(db)\n\taccounts, erro := repository.FindAll()\n\tif erro != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, erro)\n\t\treturn\n\t}\n\tresponses.JSON(w, http.StatusOK, accounts)\n}", "func (am *AccountManager) ListAccounts(minconf int) map[string]float64 {\n\t// Create and fill a map of account names and their balances.\n\tpairs := make(map[string]float64)\n\tfor _, a := range am.AllAccounts() {\n\t\tpairs[a.name] = a.CalculateBalance(minconf)\n\t}\n\treturn pairs\n}", "func getAccounts() ([]string, error) {\n\tout, err := exec.Command(\"ykman\", \"oath\", \"accounts\", \"list\").Output()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//fmt.Printf(\"Cmd out:\\n%s\\n\", out)\n\treturn strings.Split(strings.ReplaceAll(string(out), \"\\r\\n\", \"\\n\"), \"\\n\"), nil\n}", "func GetAllClinicNameAddressID(c *gin.Context) {\n\tlog.Infof(\"Get all clinics associated with admin\")\n\tctx := c.Request.Context()\n\tpageSize, err := strconv.Atoi(c.Query(\"pageSize\"))\n\tif err != nil {\n\t\tpageSize = 0\n\t}\n\tcursor := c.Query(\"cursor\")\n\tif cursor != \"\" {\n\t\tcursor, _ = helpers.DecryptAndDecode(cursor)\n\t}\n\t_, _, gproject, err := getUserDetails(ctx, c.Request)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tgin.H{\n\t\t\t\tconstants.RESPONSE_JSON_DATA: nil,\n\t\t\t\tconstants.RESPONSDE_JSON_ERROR: err.Error(),\n\t\t\t},\n\t\t)\n\t\treturn\n\t}\n\tctx, span := trace.StartSpan(ctx, \"Get all clinics associated with admin\")\n\tdefer span.End()\n\tclinicMetaDB := datastoredb.NewClinicMetaHandler()\n\terr = clinicMetaDB.InitializeDataBase(ctx, gproject)\n\tif err != nil {\n\t\tc.AbortWithStatusJSON(\n\t\t\thttp.StatusInternalServerError,\n\t\t\tgin.H{\n\t\t\t\tconstants.RESPONSE_JSON_DATA: nil,\n\t\t\t\tconstants.RESPONSDE_JSON_ERROR: err.Error(),\n\t\t\t},\n\t\t)\n\t\treturn\n\t}\n\tif pageSize == 0 {\n\t\tregisteredClinics, err := clinicMetaDB.GetAllClinicsMeta(ctx)\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t\tgin.H{\n\t\t\t\t\tconstants.RESPONSE_JSON_DATA: nil,\n\t\t\t\t\tconstants.RESPONSDE_JSON_ERROR: err.Error(),\n\t\t\t\t},\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\tconstants.RESPONSE_JSON_DATA: registeredClinics,\n\t\t\tconstants.RESPONSDE_JSON_ERROR: nil,\n\t\t})\n\t} else {\n\t\tregisteredClinics, cursor, err := clinicMetaDB.GetAllClinicsMetaPaginate(ctx, pageSize, cursor)\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t\tgin.H{\n\t\t\t\t\tconstants.RESPONSE_JSON_DATA: nil,\n\t\t\t\t\tconstants.RESPONSDE_JSON_ERROR: err.Error(),\n\t\t\t\t},\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tvar results contracts.ClinicList\n\t\tresults.Clinics = registeredClinics\n\t\tresults.CursorNext, _ = helpers.EncryptAndEncode(cursor)\n\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\tconstants.RESPONSE_JSON_DATA: results,\n\t\t\tconstants.RESPONSDE_JSON_ERROR: nil,\n\t\t})\n\t}\n\tclinicMetaDB.Close()\n}", "func listAccounts(c echo.Context) error {\n\tvar errResp ErrorResponseData\n\tvar resp AccountListResponseData\n\n\tfromDateTime, err := strconv.Atoi(c.Param(\"dromDateTime\"))\n\n\tif (err != nil) || (fromDateTime <= 0) {\n\t\terrResp.Data.Code = \"invalid_parameter_error\"\n\t\terrResp.Data.Description = \"Invalid value in query parameter fromDateTime\"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusBadRequest)\n\t\treturn c.JSON(http.StatusBadRequest, errResp)\n\t}\n\ttoDateTime, err := strconv.Atoi(c.Param(\"toDateTime\"))\n\n\tif (err != nil) || (toDateTime <= 0) || toDateTime < fromDateTime {\n\t\terrResp.Data.Code = \"invalid_parameter_error\"\n\t\terrResp.Data.Description = \"Invalid value \"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusBadRequest)\n\t\treturn c.JSON(http.StatusBadRequest, errResp)\n\t}\n\n\ttotalItems, accounts, err := storage.GetAccountList(fromDateTime, toDateTime)\n\n\tif err != nil {\n\t\terrResp.Data.Code = \"error\"\n\t\terrResp.Data.Description = \"Unable to fetch list \"\n\t\terrResp.Data.Status = strconv.Itoa(http.StatusInternalServerError)\n\t\treturn c.JSON(http.StatusInternalServerError, errResp)\n\t}\n\n\tfor _, account := range accounts {\n\t\tvar respAccount UserResponseData\n\t\trespAccount.mapFromModel(account)\n\t\tresp.Data = append(resp.Data, respAccount.Data)\n\t}\n\n\tpageSize := 10\n\tresp.Meta.TotalPages = (totalItems / pageSize) + 1\n\n\treturn c.JSON(http.StatusOK, resp)\n}", "func getAccountsPageQuery(r *http.Request) (db2.PageQuery, error) {\n\tcursor, err := hchi.GetStringFromURL(r, actions.ParamCursor)\n\tif err != nil {\n\t\treturn db2.PageQuery{}, errors.Wrap(err, \"getting param cursor\")\n\t}\n\n\torder, err := getOrder(r)\n\tif err != nil {\n\t\treturn db2.PageQuery{}, errors.Wrap(err, \"getting param order\")\n\t}\n\n\tlimit, err := getLimit(r, db2.DefaultPageSize, db2.MaxPageSize)\n\tif err != nil {\n\t\treturn db2.PageQuery{}, errors.Wrap(err, \"getting param limit\")\n\t}\n\n\treturn db2.PageQuery{\n\t\tCursor: cursor,\n\t\tOrder: order,\n\t\tLimit: limit,\n\t}, nil\n}", "func (a *Api) GetAccounts(ctx echo.Context) error {\n\t// var result []Account\n\tvar accounts []Account\n\n\tdbResult := a.DB.Find(&accounts)\n\tif dbResult.Error != nil {\n\t\treturn sendApiError(ctx, http.StatusInternalServerError, \"DB error\")\n\t}\n\n\treturn ctx.JSONPretty(http.StatusOK, accounts, \" \")\n}", "func GetAllAccounts(w http.ResponseWriter, r *http.Request) {\n\t// Fetch the accounts.\n\n\tgetAccountsInput, err := parseGetAccountsInput(r)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteRequestValidationError(w, fmt.Sprintf(\"Error parsing query params\"))\n\t\treturn\n\t}\n\n\tresult, err := Dao.GetAccounts(getAccountsInput)\n\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t\treturn\n\t}\n\n\t// Serialize them for the JSON response.\n\taccountResponses := []*response.AccountResponse{}\n\n\tfor _, a := range result.Results {\n\t\tacctRes := response.AccountResponse(*a)\n\t\taccountResponses = append(accountResponses, &acctRes)\n\t}\n\n\t// If the DB result has next keys, then the URL to retrieve the next page is put into the Link header.\n\tif len(result.NextKeys) > 0 {\n\t\tnextURL := response.BuildNextURL(r, result.NextKeys, baseRequest)\n\t\tw.Header().Add(\"Link\", fmt.Sprintf(\"<%s>; rel=\\\"next\\\"\", nextURL.String()))\n\t}\n\n\terr = json.NewEncoder(w).Encode(accountResponses)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tresponse.WriteServerError(w)\n\t}\n}", "func accountsGet(c *gin.Context) {\n\tres := c.Query(\"result\")\n\n\tidStr := c.Query(\"id\")\n\n\tvar id int\n\tvar err error\n\tid, err = strconv.Atoi(idStr)\n\tif err != nil {\n\t\tid = noId\n\t}\n\n\t// if there is an id in the request (getting only one balance)\n\tif id != noId {\n\t\tbalance, err := manager.Get(id)\n\t\tif err != nil {\n\t\t\tlogger.Zap().Error(\"failed to get balance\", zap.Error(err))\n\t\t\t// TODO: return more explicit error code\n\t\t\tc.String(http.StatusInternalServerError, \"failed to get balance\")\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%d\", balance)\n\t\treturn\n\t}\n\n\t// getting all balances\n\tswitch res {\n\t// to return sum of all balances\n\tcase \"aggregate\":\n\t\tbalance, err := manager.GetAll()\n\t\tif err != nil {\n\t\t\tlogger.Zap().Error(\"failed to get all balances\", zap.Error(err))\n\t\t\t// TODO: return more explicit error code\n\t\t\tc.String(http.StatusInternalServerError, \"failed to get all balances\")\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%d\", balance)\n\t// to return the list all balances\n\tcase \"list\":\n\t\t// TODO: declare business api to support returning a list all the accounts (ids and values)\n\t\t// Its difference in concurrent mode would be the way we protect the global slice in the memory (which all go routines will add an account to)\n\t\t// We need to use locking (mutex) around the piece of code that inserts into the slice in that case\n\t\tc.String(http.StatusNotImplemented, \"not implemented\")\n\tdefault:\n\t\tc.String(http.StatusUnprocessableEntity, \"please specify the result mod (aggregate,...)\")\n\t}\n}", "func (owner *WalletOwnerAPI) Accounts() (*[]libwallet.AccountPathMapping, error) {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t}{\n\t\tToken: owner.token,\n\t}\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvl, err := owner.client.EncryptedRequest(\"accounts\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif envl == nil {\n\t\treturn nil, errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during Accounts\")\n\t\treturn nil, errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Err != nil {\n\t\treturn nil, errors.New(string(result.Err))\n\t}\n\tvar accounts []libwallet.AccountPathMapping\n\tif err = json.Unmarshal(result.Ok, &accounts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &accounts, nil\n}", "func getNames(db *sql.DB, start, count int) ([]namest, error) {\n\trows, err := db.Query(\n\t\t\"SELECT name, count FROM names LIMIT $1 OFFSET $2\",\n\t\tcount, start)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tnames := []namest{}\n\n\tfor rows.Next() {\n\t\tvar n namest\n\t\tif err := rows.Scan(&n.Name, &n.Count); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnames = append(names, n)\n\t}\n\n\treturn names, nil\n}", "func main() {\n\t\n\tvar accountRequested string = \"1d2df1ae-accb-11e6-bbbb-00ff5244ae7f\"\n\thttpClient := rpc.NewClient(\"127.0.0.1:46657\", \"\")\n\tvar path = \"/account/\" + accountRequested\n\tresult, err := httpClient.ABCIQuery(path, []byte(\"\"), false)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tvar returned *types.AccountsReturned\n\terr = json.Unmarshal(result.Response.Value, &returned)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"JSON unmarshal for message %v failed with: %v \", returned, err))\n\t}\n\n\tfmt.Println(returned)\n}", "func (api *API) GetAccounts(ctx context.Context, names ...string) ([]*Account, error) {\n\tvar resp []*Account\n\terr := api.call(ctx, \"get_accounts\", []interface{}{names}, &resp)\n\treturn resp, err\n}", "func (r *APIClientRepository) Accounts() (gin.Accounts, error) {\n\tclients := []domain.APIClient{}\n\tif err := r.DB.Select(&clients, \"select * from api_clients\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\taccounts := gin.Accounts{}\n\tfor _, client := range clients {\n\t\taccounts[client.Key] = client.Secret\n\t}\n\n\treturn accounts, nil\n}", "func Accounts(client *ticketmatic.Client) ([]*ticketmatic.AccountInfo, error) {\n\tr := client.NewRequest(\"GET\", \"/_/tools/accounts\", \"json\")\n\n\tvar obj []*ticketmatic.AccountInfo\n\terr := r.Run(&obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn obj, nil\n}", "func (cfg AccountsConfig) Lookup(code accountsTypes.Code) *Account {\n\tfor _, acct := range cfg.Accounts {\n\t\tif acct.Code == code {\n\t\t\treturn acct\n\t\t}\n\t}\n\treturn nil\n}", "func (_Storage *StorageCaller) Accounts(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Storage.contract.Call(opts, out, \"accounts\")\n\treturn *ret0, err\n}", "func parseAccounts(resp *http.Response) ([]Account, error) {\n\tdoc, err := goquery.NewDocumentFromResponse(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taccounts := []Account{}\n\tvar accErr interface{}\n\n\tdoc.Find(\".setup-accounts .section.group\").Not(\".setup-heading\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\tacc, err := parseAccount(s)\n\t\tif err != nil {\n\t\t\taccErr = err\n\t\t\treturn false\n\t\t}\n\t\taccounts = append(accounts, *acc)\n\t\treturn true\n\t})\n\n\tif accErr != nil {\n\t\treturn nil, accErr.(error)\n\t}\n\treturn accounts, nil\n}", "func (w *Wallet) ScanForAccounts() (err error) {\n\taccounts := make([]string, 10)\n\tfor i := range accounts {\n\t\ta, err := w.NewAccount(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taccounts[i] = a.Address()\n\t}\n\tbalances, err := w.RPC.AccountsBalances(accounts)\n\tif err != nil {\n\t\treturn\n\t}\n\tfrontiers, err := w.RPC.AccountsFrontiers(accounts)\n\tif err != nil {\n\t\treturn\n\t}\n\ti := len(accounts) - 1\n\tfor ; i >= 0; i-- {\n\t\tif balances[accounts[i]].Pending.Sign() > 0 {\n\t\t\tbreak\n\t\t}\n\t\tif frontiers[accounts[i]] != nil {\n\t\t\tbreak\n\t\t}\n\t\tw.nextIndex = w.accounts[accounts[i]].index\n\t\tdelete(w.accounts, accounts[i])\n\t}\n\tif i < 5 {\n\t\treturn\n\t}\n\treturn w.ScanForAccounts()\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexepcted value found, height needs to be string of int!\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Return accounts from staking client\n\taccounts, err := so.Addresses(context.Background(), height)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Accounts!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/accounts failed to retrieve Accounts : \",\n\t\t\terr)\n\t\treturn\n\t}\n\n\t// Respond with array of all accounts\n\tlgr.Info.Println(\"Request at /api/staking/accounts responding with \" +\n\t\t\"Accounts!\")\n\tjson.NewEncoder(w).Encode(responses.AllAccountsResponse{AllAccounts: accounts})\n}", "func (x *fastReflection_QueryModuleAccountByNameResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Account != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Account.ProtoReflect())\n\t\tif !f(fd_QueryModuleAccountByNameResponse_account, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (h *HUOBIHADAX) GetAccounts() ([]Account, error) {\n\ttype response struct {\n\t\tResponse\n\t\tAccountData []Account `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodGet, huobihadaxAccounts, url.Values{}, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn nil, errors.New(result.ErrorMessage)\n\t}\n\treturn result.AccountData, err\n}", "func (mw loggingMiddleware) GetAccounts(ctx context.Context) (accounts []Account, err error) {\n\tdefer func(begin time.Time) {\n\t\tmw.logger.Log(\"method\", \"GetAddresses\", \"took\", time.Since(begin), \"err\", err)\n\t}(time.Now())\n\treturn mw.next.GetAccounts(ctx)\n}", "func (t *TezTracker) AccountList(before string, limits Limiter) (accs []models.AccountListView, count int64, err error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.AccountFilter{\n\t\tType: models.AccountTypeAccount,\n\t\tOrderBy: models.AccountOrderFieldCreatedAt,\n\t\tAfter: before,\n\t}\n\tcount, accs, err = r.List(limits.Limit(), limits.Offset(), filter)\n\treturn accs, count, err\n}", "func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, cb func(account exported.Account) (stop bool)) {\n\tstore := ctx.KVStore(ak.key)\n\titerator := sdk.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix)\n\n\tdefer iterator.Close()\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\taccount := ak.decodeAccount(iterator.Value())\n\n\t\tif cb(account) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func List(params ...int) (DataList, error) {\n\tqueryParams := map[string]string{}\n\n\tif len(params) == 2 {\n\t\tqueryParams[\"page[number]\"] = strconv.Itoa(params[0])\n\t\tqueryParams[\"page[size]\"] = strconv.Itoa(params[1])\n\t}\n\n\tresponseStatus, responsePayload, err := doRequest(&request{\n\t\tmethod: \"GET\",\n\t\tresource: \"v1/organisation/accounts/\",\n\t\tqueryParams: queryParams,\n\t})\n\n\tif err != nil {\n\t\treturn DataList{}, err\n\t}\n\treturn handleResponseDataList(responsePayload, http.StatusOK, responseStatus)\n}", "func (b *Bitcoind) ListAccounts(minconf int32) (accounts map[string]float64, err error) {\n\tr, err := b.client.call(\"listaccounts\", []int32{minconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &accounts)\n\treturn\n}", "func (d *Dynamicd) GetMyAccounts() (*[]Account, error) {\n\tvar accountsGeneric map[string]interface{}\n\tvar accounts = []Account{}\n\treq, _ := NewRequest(\"dynamic-cli mybdapaccounts\")\n\trawResp := []byte(<-d.ExecCmdRequest(req))\n\terrUnmarshal := json.Unmarshal(rawResp, &accountsGeneric)\n\tif errUnmarshal != nil {\n\t\treturn &accounts, errUnmarshal\n\t}\n\tfor _, v := range accountsGeneric {\n\t\tb, err := json.Marshal(v)\n\t\tif err == nil {\n\t\t\tvar account Account\n\t\t\terrUnmarshal = json.Unmarshal(b, &account)\n\t\t\tif errUnmarshal != nil {\n\t\t\t\tutil.Error.Println(\"Inner error\", errUnmarshal)\n\t\t\t\treturn nil, errUnmarshal\n\t\t\t}\n\t\t\taccounts = append(accounts, account)\n\t\t}\n\t}\n\treturn &accounts, nil\n}", "func (api *PublicEthereumAPI) Accounts() ([]common.Address, error) {\n\tapi.logger.Debug(\"eth_accounts\")\n\tapi.keyringLock.Lock()\n\tdefer api.keyringLock.Unlock()\n\n\taddresses := make([]common.Address, 0) // return [] instead of nil if empty\n\n\tinfos, err := api.clientCtx.Keybase.List()\n\tif err != nil {\n\t\treturn addresses, err\n\t}\n\n\tfor _, info := range infos {\n\t\taddressBytes := info.GetPubKey().Address().Bytes()\n\t\taddresses = append(addresses, common.BytesToAddress(addressBytes))\n\t}\n\n\treturn addresses, nil\n}", "func (s *AccountsService) QueryAccounts(opt *QueryAccountOptions) (*[]AccountInfo, *Response, error) {\n\tu := \"accounts/\"\n\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new([]AccountInfo)\n\tresp, err := s.client.Do(req, v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func (controller *AccountController) GetAccounts(ctx *gin.Context) {\n\tinfo, err := authStuff.GetLoginInfoFromCtx(ctx)\n\tif err != nil {\n\t\tresponse, _ := restapi.NewErrorResponse(err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\n\taccs, err := controller.service.GetAccounts(info.Name)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\"user\": info.Name}).WithError(err).Error(\"Account Error GetAll\")\n\n\t\tresponse, _ := restapi.NewErrorResponse(\"Could not get accounts because: \" + err.Error()).Marshal()\n\t\tfmt.Fprint(ctx.Writer, string(response))\n\t\tctx.Abort()\n\t\treturn\n\t}\n\tresponse, _ := restapi.NewOkResponse(accs).Marshal()\n\tfmt.Fprint(ctx.Writer, string(response))\n\tctx.Next()\n\n}", "func (h *HUOBI) GetAccounts(ctx context.Context) ([]Account, error) {\n\tresult := struct {\n\t\tAccounts []Account `json:\"data\"`\n\t}{}\n\terr := h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet, huobiAccounts, url.Values{}, nil, &result, false)\n\treturn result.Accounts, err\n}", "func (c *Client) AccountsSearch(ctx context.Context, q string, limit int64) ([]*Account, error) {\n\tparams := url.Values{}\n\tparams.Set(\"q\", q)\n\tparams.Set(\"limit\", fmt.Sprint(limit))\n\n\tvar accounts []*Account\n\terr := c.doAPI(ctx, http.MethodGet, \"/api/v1/accounts/search\", params, &accounts, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn accounts, nil\n}", "func (ks *KeyStore) Find(a common.Address) ([]accounts.Account, error) {\n\taccs, err := ks.Accounts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfound := []accounts.Account{}\n\tfor _, acc := range accs {\n\t\tif acc.Address == a {\n\t\t\tfound = append(found, *acc)\n\t\t}\n\t}\n\treturn found, nil\n}", "func (c *IloClient) GetUserAccountsDell() ([]Accounts, error) {\n\n\turl := c.Hostname + \"/redfish/v1/Managers/iDRAC.Embedded.1/Accounts\"\n\n\tresp, _, _, err := queryData(c, \"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar x MemberCountDell\n\tvar users []Accounts\n\n\tjson.Unmarshal(resp, &x)\n\n\tfor i := range x.Members {\n\t\t_url := c.Hostname + x.Members[i].OdataId\n\t\tresp, _, _, err := queryData(c, \"GET\", _url, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar y AccountsInfoDell\n\n\t\tjson.Unmarshal(resp, &y)\n\n\t\tuser := Accounts{\n\t\t\tName: y.Name,\n\t\t\tEnabled: y.Enabled,\n\t\t\tLocked: y.Locked,\n\t\t\tRoleId: y.RoleID,\n\t\t\tUsername: y.UserName,\n\t\t}\n\t\tusers = append(users, user)\n\n\t}\n\n\treturn users, nil\n\n}", "func (x *fastReflection_QueryAccountsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.Accounts) != 0 {\n\t\tvalue := protoreflect.ValueOfList(&_QueryAccountsResponse_1_list{list: &x.Accounts})\n\t\tif !f(fd_QueryAccountsResponse_accounts, value) {\n\t\t\treturn\n\t\t}\n\t}\n\tif x.Pagination != nil {\n\t\tvalue := protoreflect.ValueOfMessage(x.Pagination.ProtoReflect())\n\t\tif !f(fd_QueryAccountsResponse_pagination, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (x *fastReflection_QueryModuleAccountsRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n}", "func (s *Scim) LoadAccountLookup(realm, acct string, tx storage.Tx) (*cpb.AccountLookup, error) {\n\tlookup := &cpb.AccountLookup{}\n\tstatus, err := s.readTx(storage.AccountLookupDatatype, realm, storage.DefaultUser, acct, storage.LatestRev, lookup, tx)\n\tif err != nil && status == http.StatusNotFound {\n\t\treturn nil, nil\n\t}\n\treturn lookup, err\n}", "func (x *fastReflection_QueryModuleAccountsResponse) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif len(x.Accounts) != 0 {\n\t\tvalue := protoreflect.ValueOfList(&_QueryModuleAccountsResponse_1_list{list: &x.Accounts})\n\t\tif !f(fd_QueryModuleAccountsResponse_accounts, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func GetUserListBySort(skip, limit int, sortOrder, preCursor, nextCursor string) (total int, users []Account, err error) {\n\n\tvar sortby string\n\n\tswitch sortOrder {\n\tcase \"logintime\":\n\t\tsortby = \"lastlogin\"\n\tcase \"-logintime\":\n\t\tsortby = \"-lastlogin\"\n\tcase \"userid\":\n\t\tsortby = \"_id\"\n\tcase \"-userid\":\n\t\tsortby = \"-_id\"\n\tcase \"nickname\":\n\t\tsortby = \"nickname\"\n\tcase \"-nickname\":\n\t\tsortby = \"-nickname\"\n\tcase \"score\":\n\t\tsortby = \"score\"\n\tcase \"-score\":\n\t\tsortby = \"-score\"\n\tcase \"regtime\":\n\t\tsortby = \"reg_time\"\n\tcase \"-regtime\":\n\t\tsortby = \"-reg_time\"\n\tcase \"age\":\n\t\tsortby = \"-birth\"\n\tcase \"-age\":\n\t\tsortby = \"birth\"\n\tcase \"gender\":\n\t\tsortby = \"gender\"\n\tcase \"-gender\":\n\t\tsortby = \"-gender\"\n\tcase \"ban\":\n\t\tsortby = \"timelimit\"\n\tcase \"-ban\":\n\t\tsortby = \"-timelimit\"\n\tdefault:\n\t\tsortby = \"-reg_time\"\n\t}\n\n\tquery := bson.M{\"reg_time\": bson.M{\"$gt\": time.Unix(0, 0)}}\n\n\tif err = search(accountColl, query, nil, skip, limit, []string{sortby}, &total, &users); err != nil {\n\t\treturn 0, nil, errors.NewError(errors.DbError, err.Error())\n\t}\n\n\treturn\n}", "func (c *Client) FindAccountAccountTemplates(criteria *Criteria, options *Options) (*AccountAccountTemplates, error) {\n\taats := &AccountAccountTemplates{}\n\tif err := c.SearchRead(AccountAccountTemplateModel, criteria, options, aats); err != nil {\n\t\treturn nil, err\n\t}\n\treturn aats, nil\n}", "func (s stdlib) LookupAC(string) ([]string, error) {\n\treturn nil, ErrNotImplemented\n}", "func (service *AccountService) List(budgetId string) (accounts []model.Account, err error) {\n\n\tvar result model.AccountsResponse\n\terr = service.Client.get(\"/budgets/\"+budgetId+\"/accounts\", &result)\n\tif err != nil {\n\t\treturn\n\t}\n\n\taccounts = model.FilterActive(&result.Data.Accounts)\n\treturn\n}", "func (t *TezTracker) AccountList(before string, limits Limiter, favorites []string) (accs []models.AccountListView, count int64, err error) {\n\tr := t.repoProvider.GetAccount()\n\tfilter := models.AccountFilter{\n\t\tType: models.AccountTypeAccount,\n\t\tOrderBy: models.AccountOrderFieldCreatedAt,\n\t\tAfter: before,\n\t\tFavorites: favorites,\n\t}\n\tcount, accs, err = r.List(limits.Limit(), limits.Offset(), filter)\n\treturn accs, count, err\n}", "func (e *Ethereum) Accounts() ([]string, error) {\n\tvar accounts []string\n\terr := e.rpcClient.CallContext(e.ctx, &accounts, \"eth_accounts\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"fail to call rpc.CallContext(eth_accounts)\")\n\t}\n\n\treturn accounts, nil\n}", "func (c *Client) Accounts() (*AddressesResponse, error) {\n\trequest := c.newRequest(EthAccounts)\n\n\tresponse := &AddressesResponse{}\n\n\treturn response, c.send(request, response)\n}", "func GetnumAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetnumberAccountsAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\t// data := map[string]int{\n\t// \t\"NumberOfAccounts\": len(accountdb.GetAllAccounts()),\n\t// }\n\t// var responsedata globalPkg.StructData\n\t// for key, value := range data {\n\t// \tresponsedata.Name = key\n\t// \tresponsedata.Length = value\n\t// }\n\t// jsonObj, _ := json.Marshal(responsedata)\n\n\tglobalPkg.SendResponseMessage(w, strconv.Itoa(len(accountdb.GetAllAccounts())))\n\tlogobj.OutputData = \"success to get number of accounts\"\n\tlogobj.Process = \"success\"\n\tglobalPkg.WriteLog(logobj, \"success to get number of accounts\", \"success\")\n\n}", "func getListingsByRange(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tstartKey := args[0]\n\tendKey := args[1]\n\n\tresultsIterator, err := stub.GetStateByRange(startKey, endKey)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\t// buffer is a JSON array containing QueryResults\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\n\tbArrayMemberAlreadyWritten := false\n\tfor resultsIterator.HasNext() {\n\t\taKeyValue, err := resultsIterator.Next()\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\tqueryResultKey := aKeyValue.Key\n\t\tqueryResultValue := aKeyValue.Value\n\n\t\t// Add a comma before array members, suppress it for the first array member\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResultKey)\n\t\tbuffer.WriteString(\"\\\"\")\n\n\t\tbuffer.WriteString(\", \\\"Record\\\":\")\n\t\t// Record is a JSON object, so we write as-is\n\t\tbuffer.WriteString(string(queryResultValue))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\n\tfmt.Printf(\"- getListingByRange queryResult:\\n%s\\n\", buffer.String())\n\n\treturn shim.Success(buffer.Bytes())\n}", "func LoadAccountByKind(s ent.Storage, kind AccountKind, limit int, fl ...ent.LookupFlags) ([]*Account, error) {\n\te := &Account{}\n\tr, err := ent.LoadEntsByIndex(s, e, &ent_Account_idx[1], limit, fl, 1, func(c ent.Encoder) {\n\t\tc.Int(int64(kind), 32)\n\t})\n\treturn ent_Account_slice_cast(r), err\n}", "func getAccountID(s State, n int) string {\n\tsa := make([]string, 0)\n\tfor k := range s.Accounts {\n\t\tsa = append(sa, k)\n\t}\n\tsort.Sort(sort.StringSlice(sa))\n\treturn sa[n]\n}", "func (sc Funcs) Accounts(ctx wasmlib.ScViewClientContext) *AccountsCall {\n\tf := &AccountsCall{Func: wasmlib.NewScView(ctx, HScName, HViewAccounts)}\n\twasmlib.NewCallResultsProxy(f.Func, &f.Results.Proxy)\n\treturn f\n}", "func GetnumberAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetnumberAccountsAPI\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tdata := map[string]interface{}{\n\t\t\t\"Number_Of_Accounts\": len(accountdb.GetAllAccounts()),\n\t\t}\n\t\tjsonObj, _ := json.Marshal(data)\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tlogobj.OutputData = \"success to get number of accounts\"\n\t\tlogobj.Process = \"success\"\n\t\tglobalPkg.WriteLog(logobj, \"success to get number of accounts\", \"success\")\n\t} else {\n\t\tglobalPkg.SendError(w, \"you are not admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all Emails and username \", \"failed\")\n\n\t}\n}", "func Find(in *accountstore.SearchRequest) ([]Account, error) {\n\tvar out []Account\n\treq := db.New()\n\n\tif in.InstagramUsername > \"\" {\n\t\treq = req.Where(\"instagram_username = ?\", strings.ToLower(in.InstagramUsername))\n\t}\n\n\tif in.InstagramId > 0 {\n\t\treq = req.Where(\"instagram_id = ?\", in.InstagramId)\n\t}\n\n\tif in.OwnerId > 0 {\n\t\treq = req.Where(\"owner_id = ?\", in.OwnerId)\n\t}\n\n\tif !in.IncludeInvalids {\n\t\treq = req.Where(\"valid != FALSE\")\n\t}\n\n\tif len(in.Roles) > 0 {\n\t\treq = req.Where(\"role in (?)\", in.Roles)\n\t}\n\n\terr := req.Find(&out).Error\n\treturn out, err\n}", "func (s *AccountsService) SuggestAccount(opt *QueryAccountOptions) (*[]AccountInfo, *Response, error) {\n\tu := \"accounts/\"\n\n\tu, err := addOptions(u, opt)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new([]AccountInfo)\n\tresp, err := s.client.Do(req, v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func FindAccountByKind(s ent.Storage, kind AccountKind, limit int, fl ...ent.LookupFlags) ([]uint64, error) {\n\treturn ent.FindIdsByIndex(s, \"account\", &ent_Account_idx[1], limit, fl, 1, func(c ent.Encoder) {\n\t\tc.Int(int64(kind), 32)\n\t})\n}", "func (client JobClient) listByAccountNextResults(ctx context.Context, lastResults JobResourceDescriptionList) (result JobResourceDescriptionList, err error) {\n req, err := lastResults.jobResourceDescriptionListPreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.JobClient\", \"listByAccountNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListByAccountSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.JobClient\", \"listByAccountNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListByAccountResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"microsoftazuremanagementaisupercomputer.JobClient\", \"listByAccountNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }", "func (s *ScanKeys) apiLookup(m libkb.MetaContext, id uint64) (username string, uid keybase1.UID, err error) {\n\treturn libkb.PGPLookup(m, id)\n}", "func (c *AccountController) List(ctx *app.ListAccountContext) error {\n\tusers, err := repositories.GetAllUsers(1, 100)\n\tif err != nil {\n\t\treturn ctx.InternalServerError()\n\t}\n\tresp := app.FtAccountCollection{}\n\tfor _, u := range users {\n\t\tresp = append(resp, &app.FtAccount{\n\t\t\tID: u.ID,\n\t\t\tFirstName: u.FirstName,\n\t\t\tLastName: u.LastName,\n\t\t\tEmail: u.Email,\n\t\t})\n\t}\n\treturn ctx.OK(resp)\n}", "func GetAllAccountsAPI(w http.ResponseWriter, req *http.Request) {\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(req)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"GetAllAccount\", \"Account\", \"_\", \"_\", \"_\", 0}\n\n\tAdminobj := admin.Admin{}\n\tdecoder := json.NewDecoder(req.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&Adminobj)\n\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request \")\n\t\tglobalPkg.WriteLog(logobj, \"failed to decode admin object\", \"failed\")\n\t\treturn\n\t}\n\t// if Adminobj.AdminUsername == globalPkg.AdminObj.AdminUsername && Adminobj.AdminPassword == globalPkg.AdminObj.AdminPassword {\n\tif admin.ValidationAdmin(Adminobj) {\n\t\tjsonObj, _ := json.Marshal(accountdb.GetAllAccounts())\n\t\tglobalPkg.SendResponse(w, jsonObj)\n\t\tglobalPkg.WriteLog(logobj, \"get all accounts\", \"success\")\n\t} else {\n\n\t\tglobalPkg.SendError(w, \"you are not the admin \")\n\t\tglobalPkg.WriteLog(logobj, \"you are not the admin to get all accounts \", \"failed\")\n\t}\n}", "func CreateListOfAccounts() string {\n\n\treturn fmt.Sprintf(`{\n\t\t\"data\": [\n\t\t{\n\t\t\t\"attributes\": {\n\t\t\t\"account_classification\": \"Personal\",\n\t\t\t\"account_number\": \"10000004\",\n\t\t\t\"alternative_bank_account_names\": null,\n\t\t\t\"bank_id\": \"400302\",\n\t\t\t\"bank_id_code\": \"GBDSC\",\n\t\t\t\"base_currency\": \"GBP\",\n\t\t\t\"bic\": \"NWBKGB42\",\n\t\t\t\"country\": \"GB\",\n\t\t\t\"customer_id\": \"da968913-79ae-4a1c-8490-5597d28ecf5b\",\n\t\t\t\"iban\": \"GB28NWBK40030212764204\"\n\t\t\t},\n\t\t\t\"created_on\": \"2020-08-25T21:24:39.999Z\",\n\t\t\t\"id\": \"%s\",\n\t\t\t\"modified_on\": \"2020-08-25T21:24:39.999Z\",\n\t\t\t\"organisation_id\": \"538fd1a0-b62d-4b56-beb8-7836a1fedd2e\",\n\t\t\t\"type\": \"accounts\",\n\t\t\t\"version\": 0\n\t\t},\n\t\t{\n\t\t\t\"attributes\": {\n\t\t\t\"account_classification\": \"Personal\",\n\t\t\t\"account_number\": \"10000004\",\n\t\t\t\"alternative_bank_account_names\": null,\n\t\t\t\"bank_id\": \"400302\",\n\t\t\t\"bank_id_code\": \"GBDSC\",\n\t\t\t\"base_currency\": \"GBP\",\n\t\t\t\"bic\": \"NWBKGB42\",\n\t\t\t\"country\": \"GB\",\n\t\t\t\"customer_id\": \"d64797ec-c107-4ecf-a1cb-436e70fb85b8\",\n\t\t\t\"iban\": \"GB28NWBK40030212764204\"\n\t\t\t},\n\t\t\t\"created_on\": \"2020-08-25T21:24:48.358Z\",\n\t\t\t\"id\": \"%s\",\n\t\t\t\"modified_on\": \"2020-08-25T21:24:48.358Z\",\n\t\t\t\"organisation_id\": \"538fd1a0-b62d-4b56-beb8-7836a1fedd2e\",\n\t\t\t\"type\": \"accounts\",\n\t\t\t\"version\": 0\n\t\t},\n\t\t{\n\t\t\t\"attributes\": {\n\t\t\t\"account_classification\": \"Personal\",\n\t\t\t\"account_number\": \"10000004\",\n\t\t\t\"alternative_bank_account_names\": null,\n\t\t\t\"bank_id\": \"400302\",\n\t\t\t\"bank_id_code\": \"GBDSC\",\n\t\t\t\"base_currency\": \"GBP\",\n\t\t\t\"bic\": \"NWBKGB42\",\n\t\t\t\"country\": \"GB\",\n\t\t\t\"customer_id\": \"eca70c57-4f13-4907-a974-30459363509f\",\n\t\t\t\"iban\": \"GB28NWBK40030212764204\"\n\t\t\t},\n\t\t\t\"created_on\": \"2020-08-25T21:24:50.979Z\",\n\t\t\t\"id\": \"%s\",\n\t\t\t\"modified_on\": \"2020-08-25T21:24:50.979Z\",\n\t\t\t\"organisation_id\": \"538fd1a0-b62d-4b56-beb8-7836a1fedd2e\",\n\t\t\t\"type\": \"accounts\",\n\t\t\t\"version\": 0\n\t\t}\n\t\t],\n\t\t\"links\": {\n\t\t\"first\": \"\",\n\t\t\"last\": \"\",\n\t\t\"self\": \"\"\n\t\t}\n\t}`, GenerateUUID(), GenerateUUID(), GenerateUUID())\n}", "func get_account_ (stub shim.ChaincodeStubInterface, account_name string) (*Account, error) {\n var account Account\n row_was_found,err := util.GetTableRow(stub, ACCOUNT_TABLE, []string{account_name}, &account, util.FAIL_IF_MISSING)\n if err != nil {\n return nil,fmt.Errorf(\"Could not retrieve account named \\\"%s\\\"; error was %v\", account_name, err.Error())\n }\n if !row_was_found {\n return nil,fmt.Errorf(\"Account named \\\"%s\\\" does not exist\", account_name)\n }\n return &account,nil\n}", "func (c Client) ListAccounts(query *queries.ListAccounts) (*responses.ListAccount, error) {\n\turl := fmt.Sprintf(\"%s/PasswordVault/api/Accounts%s\", c.BaseURL, httpJson.GetURLQuery(query))\n\tresponse, err := httpJson.Get(url, c.SessionToken, c.InsecureTLS, c.Logger)\n\tif err != nil {\n\t\treturn &responses.ListAccount{}, fmt.Errorf(\"Failed to list accounts. %s\", err)\n\t}\n\n\tjsonString, _ := json.Marshal(response)\n\tListSafesResponse := responses.ListAccount{}\n\terr = json.Unmarshal(jsonString, &ListSafesResponse)\n\treturn &ListSafesResponse, err\n}", "func (s *Accounts) ListFunc(rw http.ResponseWriter, r *http.Request) {\n\tlimit, err := strconv.Atoi(r.FormValue(\"limit\"))\n\tif err != nil {\n\t\tlimit = 0\n\t}\n\n\toffset, err := strconv.Atoi(r.FormValue(\"offset\"))\n\tif err != nil {\n\t\toffset = 0\n\t}\n\n\tres, err := s.service.List(limit, offset)\n\n\tif err != nil {\n\t\thandleError(rw, s.log, err)\n\t\treturn\n\t}\n\n\thandleJsonResponse(rw, http.StatusOK, res)\n}", "func (r *CompanyAccountsCollectionRequest) GetN(ctx context.Context, n int) ([]Account, error) {\n\tvar query string\n\tif r.query != nil {\n\t\tquery = \"?\" + r.query.Encode()\n\t}\n\treturn r.Paging(ctx, \"GET\", query, nil, n)\n}", "func (s *Repository) GetAll(ctx context.Context) ([]Account, error) {\n\tconst limit = 10\n\n\trows, err := s.pool.Query(\n\t\tctx,\n\t\t`select * from \"account\"\n\t\t\t order by \"createdAt\" desc\n\t\t\t limit $1`, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\treturn scanAccounts(limit, rows)\n}", "func find(ctx context.Context, claims auth.Claims, dbConn *sqlx.DB, query *sqlbuilder.SelectBuilder, args []interface{}, includedArchived bool) (UserAccounts, error) {\n\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.user_account.Find\")\n\tdefer span.Finish()\n\n\tquery.Select(userAccountMapColumns)\n\tquery.From(userAccountTableName)\n\n\tif !includedArchived {\n\t\tquery.Where(query.IsNull(\"archived_at\"))\n\t}\n\n\t// Check to see if a sub query needs to be applied for the claims\n\terr := applyClaimsSelect(ctx, claims, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqueryStr, queryArgs := query.Build()\n\tqueryStr = dbConn.Rebind(queryStr)\n\targs = append(args, queryArgs...)\n\n\t// fetch all places from the db\n\trows, err := dbConn.QueryContext(ctx, queryStr, args...)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\terr = errors.WithMessage(err, \"find user accounts failed\")\n\t\treturn nil, err\n\t}\n\n\t// iterate over each row\n\tresp := []*UserAccount{}\n\tfor rows.Next() {\n\t\tua, err := mapRowsToUserAccount(rows)\n\t\tif err != nil {\n\t\t\terr = errors.Wrapf(err, \"query - %s\", query.String())\n\t\t\treturn nil, err\n\t\t}\n\t\tresp = append(resp, ua)\n\t}\n\n\treturn resp, nil\n}", "func (inst *Instancer) lookup(ctx context.Context) ([]string, error) {\n\tentriesChan := make(chan *mdns.ServiceEntry, 100)\n\tinstances := make([]string, 0)\n\n\tvar lookupWG sync.WaitGroup\n\tlookupWG.Add(1)\n\tgo func() {\n\t\tdefer lookupWG.Done()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase entry, ok := <-entriesChan:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tinstance, err := getInstance(entry)\n\t\t\t\tif err != nil {\n\t\t\t\t\tinst.logger.Log(\"action\", \"lookup\", \"err\", err)\n\t\t\t\t} else {\n\t\t\t\t\tinstances = append(instances, instance)\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tparam := &mdns.QueryParam{\n\t\tService: inst.service,\n\t\tDomain: inst.opts.Domain,\n\t\tTimeout: inst.opts.LookupTimeout,\n\t\tInterface: inst.opts.Interface,\n\t\tEntries: entriesChan,\n\t\tWantUnicastResponse: inst.opts.WantUnicastResponse,\n\t}\n\terr := mdns.Query(param)\n\tclose(entriesChan)\n\tlookupWG.Wait()\n\n\tif err != nil {\n\t\tinst.logger.Log(\"action\", \"query\", \"err\", err)\n\t\treturn nil, err\n\t}\n\treturn instances, nil\n}", "func (s stdlib) LookupAAAAC(string) ([]string, error) {\n\treturn nil, ErrNotImplemented\n}", "func (_Storage *StorageSession) Accounts() (*big.Int, error) {\n\treturn _Storage.Contract.Accounts(&_Storage.CallOpts)\n}", "func (p *bitsharesAPI) GetAccounts(accounts ...objects.GrapheneObject) ([]objects.Account, error) {\n\tvar result []objects.Account\n\terr := p.call(p.databaseAPIID, \"get_accounts\", &result, accounts)\n\treturn result, err\n}", "func (client *Client) SearchMultiAccountResourcesWithCallback(request *SearchMultiAccountResourcesRequest, callback func(response *SearchMultiAccountResourcesResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *SearchMultiAccountResourcesResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.SearchMultiAccountResources(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func LoadAccountByPicture(s ent.Storage, picture []byte, limit int, fl ...ent.LookupFlags) ([]*Account, error) {\n\te := &Account{}\n\tr, err := ent.LoadEntsByIndexKey(s, e, &ent_Account_idx[2], picture, limit, fl)\n\treturn ent_Account_slice_cast(r), err\n}", "func (x *fastReflection_QueryModuleAccountByNameRequest) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {\n\tif x.Name != \"\" {\n\t\tvalue := protoreflect.ValueOfString(x.Name)\n\t\tif !f(fd_QueryModuleAccountByNameRequest_name, value) {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (hc *Client) GetAccounts() ([]Account, error) {\n\tvar (\n\t\tresult AccountResponse\n\t)\n\tendpoint := fmt.Sprintf(\"%s/v1/account/accounts\", huobiEndpoint)\n\tres, err := hc.sendRequest(\n\t\thttp.MethodGet,\n\t\tendpoint,\n\t\tmap[string]string{},\n\t\ttrue,\n\t)\n\tif err != nil {\n\t\treturn result.Data, err\n\t}\n\terr = json.Unmarshal(res, &result)\n\tif result.Status != StatusOK.String() {\n\t\treturn result.Data, fmt.Errorf(\"received unexpect status: err=%s code=%s msg=%s\",\n\t\t\tresult.Status,\n\t\t\tresult.ErrorCode,\n\t\t\tresult.ErrorMessage)\n\t}\n\treturn result.Data, err\n}", "func GetList(tx *sql.Tx) (list []Info, err error) {\n\tmapper := rlt.NewAccountMapper(tx)\n\trows, err := mapper.FindAccountAll()\n\tfor _, row := range rows {\n\t\tinfo := Info{}\n\t\tinfo.ID = row.ID\n\t\tinfo.Domain = row.Domain.String\n\t\tinfo.UserName = row.UserName\n\t\tinfo.DisplayName = row.DisplayName\n\t\tinfo.Email = row.Email\n\t\tlist = append(list, info) //数据写入\n\t}\n\treturn list, err\n}", "func LoadAccountBySize(s ent.Storage, width, height int, limit int, fl ...ent.LookupFlags) ([]*Account, error) {\n\te := &Account{}\n\tr, err := ent.LoadEntsByIndex(s, e, &ent_Account_idx[4], limit, fl, 2, func(c ent.Encoder) {\n\t\tc.Key(\"w\")\n\t\tc.Int(int64(width), 64)\n\t\tc.Key(\"h\")\n\t\tc.Int(int64(height), 64)\n\t})\n\treturn ent_Account_slice_cast(r), err\n}", "func (pca Client) Accounts(ctx context.Context) ([]Account, error) {\n\treturn pca.base.AllAccounts(ctx)\n}", "func GetAccounts(w http.ResponseWriter, r *http.Request) {\n\n\tjson.NewEncoder(w).Encode(nil)\n}", "func (h *accountHandler) List(ctx context.Context, req *api.Request, rsp *api.Response) error {\n\tlog.Info(\"Received Example.Call request\")\n\n\t// parse values from the get request\n\tlimitStr, ok := req.Get[\"limit\"]\n\n\tif !ok || len(limitStr.Values) == 0 {\n\t\treturn errors.BadRequest(\"go.micro.api.account\", \"no content\")\n\t}\n\n\tlimit, _ := strconv.Atoi(limitStr.Values[0])\n\t// make request\n\tresponse, err := h.userSrvClient.List(ctx, &userPB.UserListQuery{\n\t\tLimit: &wrappers.UInt32Value{Value: uint32(limit)},\n\t\tPage: &wrappers.UInt32Value{Value: 1},\n\t})\n\tif err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.api.account.call\", err.Error())\n\t}\n\tlog.Info(response)\n\n\t// set response status\n\trsp.StatusCode = 200\n\n\t// respond with some json\n\tb, _ := json.Marshal(response)\n\n\t// set json body\n\trsp.Body = string(b)\n\n\treturn nil\n}", "func GetAccountsIndex(db gorm.DB, search_vars fp.SearchVars) ([]AccountView, error) {\n\n\tvar rows []AccountView\n\tfmt.Println(\"getttttts=\", search_vars)\n\n\twhere := search_vars.GetSQL(\"company\", \"acc_active\")\n\tfmt.Println(\"where=\", where)\n\tdb.Table(ACCOUNT_VIEW).Select(ACCOUNT_VIEW_COLS).Where(where).Scan(&rows)\n\n\treturn rows, nil\n\n}", "func (service AccountsService) List(params Params) (*Response, []Account, error) {\n\treq, err := service.client.newRequest(\"GET\", \"accounts\", params, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar a struct {\n\t\tXMLName xml.Name `xml:\"accounts\"`\n\t\tAccounts []Account `xml:\"account\"`\n\t}\n\tres, err := service.client.do(req, &a)\n\n\tfor i := range a.Accounts {\n\t\ta.Accounts[i].BillingInfo = nil\n\t}\n\n\treturn res, a.Accounts, err\n}", "func accountId(addr *common.Address) string {\n\tvar sb strings.Builder\n\n\t// add the prefix and actual address\n\tsb.WriteString(accountExistenceCacheIdPrefix)\n\tsb.WriteString(addr.String())\n\n\treturn sb.String()\n}", "func GetUsernames(db *sql.DB, identifiers []*sharedModels.GetUsernamesRequest) ([]*sharedModels.GetUsernamesResponse, error) {\n\n\tif len(identifiers) < 1 {\n\t\treturn make([]*sharedModels.GetUsernamesResponse, 0), nil\n\t}\n\n\tquery := inQueryBuilder(identifiers)\n\trows, err := db.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpersons := make([]*sharedModels.GetUsernamesResponse, 0)\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar username string\n\t\terr = rows.Scan(&id, &username)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpersons = append(persons, &sharedModels.GetUsernamesResponse{ID: id, Username: username})\n\t}\n\treturn persons, nil\n}" ]
[ "0.5750897", "0.56853", "0.56486696", "0.5646235", "0.5644906", "0.5556404", "0.5544633", "0.5519726", "0.55192685", "0.54581314", "0.54003", "0.5372517", "0.5332015", "0.5319677", "0.5290591", "0.52856636", "0.5274148", "0.52607983", "0.5248461", "0.5248349", "0.5233114", "0.5233102", "0.5228218", "0.5210361", "0.52044266", "0.51965123", "0.5190995", "0.5125641", "0.5108299", "0.51081926", "0.5094224", "0.5076757", "0.5075965", "0.5073541", "0.50410694", "0.5014443", "0.5010529", "0.50014985", "0.49873972", "0.4967461", "0.49667004", "0.4953718", "0.49500728", "0.4940326", "0.4938855", "0.49354333", "0.49310985", "0.49306345", "0.49101308", "0.4909123", "0.49007237", "0.48977366", "0.48972353", "0.48965454", "0.48916334", "0.48885742", "0.48694518", "0.48683137", "0.48649588", "0.48517096", "0.48373064", "0.4832956", "0.4832347", "0.48323345", "0.4832141", "0.48305422", "0.48253012", "0.4822105", "0.4819638", "0.48185426", "0.48038927", "0.47891536", "0.47862366", "0.47790956", "0.4767569", "0.47521502", "0.47455984", "0.47433436", "0.4733946", "0.4721644", "0.47156262", "0.47131765", "0.4712672", "0.47122067", "0.4710765", "0.47100478", "0.47064415", "0.47064233", "0.46928596", "0.46884024", "0.46815363", "0.46676514", "0.46664733", "0.46652943", "0.4663001", "0.46572515", "0.46545374", "0.4653187", "0.46408525", "0.46406266" ]
0.8132988
0
Set callback to invoke as soon as a new block is applied
func (api *API) SetBlockAppliedCallback(notice func(header *types.BlockHeader, error error)) (err error) { err = api.setCallback("set_block_applied_callback", func(raw json.RawMessage) { var header []types.BlockHeader if err := json.Unmarshal(raw, &header); err != nil { notice(nil, err) } for _, b := range header { notice(&b, nil) } }) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *SelfTester) SetOnNewPoliciesReadyCb(cb func()) {\n}", "func (v *Vox) SetCb(cb audio.OnDataCb) {\n\tv.Lock()\n\tdefer v.Unlock()\n\tv.cb = cb\n}", "func (q *Queue) SetCallback(cb Callback) error {\n\tq.cb = cb\n\treturn nil\n}", "func TestCallbackInvokedWhenSetLate(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\tapp := blockedABCIApplication{\n\t\twg: wg,\n\t}\n\t_, c := setupClientServer(t, app)\n\treqRes := c.CheckTxAsync(types.RequestCheckTx{})\n\n\tdone := make(chan struct{})\n\tcb := func(_ *types.Response) {\n\t\tclose(done)\n\t}\n\treqRes.SetCallback(cb)\n\tapp.wg.Done()\n\t<-done\n\n\tvar called bool\n\tcb = func(_ *types.Response) {\n\t\tcalled = true\n\t}\n\treqRes.SetCallback(cb)\n\trequire.True(t, called)\n}", "func (mn *MockNetwork) SetConnectCallback(network.ConnectCallback) {\n\n}", "func (lp *loop) HandleCb(cb handleCb) {\n\tlp.handleCb = cb\n}", "func TestCallbackInvokedWhenSetEarly(t *testing.T) {\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\tapp := blockedABCIApplication{\n\t\twg: wg,\n\t}\n\t_, c := setupClientServer(t, app)\n\treqRes := c.CheckTxAsync(types.RequestCheckTx{})\n\n\tdone := make(chan struct{})\n\tcb := func(_ *types.Response) {\n\t\tclose(done)\n\t}\n\treqRes.SetCallback(cb)\n\tapp.wg.Done()\n\n\tcalled := func() bool {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\trequire.Eventually(t, called, time.Second, time.Millisecond*25)\n}", "func (s *Strava) SetCallbackHandler(\n\tsuccess func(auth *strava.AuthorizationResponse, w http.ResponseWriter, r *http.Request),\n\tfailure func(err error, w http.ResponseWriter, r *http.Request)) {\n\tpath, _ := s.authenticator.CallbackPath()\n\thttp.HandleFunc(path, s.authenticator.HandlerFunc(success, failure))\n}", "func (s *server) SetNewClientCB(callback func(c *Client)) {\n\ts.onNewClientCallback = callback\n}", "func (d *Doorman) SetCb(cb audio.OnDataCb) {\n\td.Lock()\n\tdefer d.Unlock()\n\td.onDataCb = cb\n}", "func (p *blockParser) emit(b Block) {\n\tp.blockChan <- b\n\tp.start = p.cur\n}", "func (policy *ticketPolicy) OnAddBlockFinish(block *types.BlockDetail) {\n\tif policy.needFlush {\n\t\t// 新增区块,由于ticket具有锁定期,所以这里不需要刷新\n\t\t//policy.flushTicket()\n\t}\n\tpolicy.needFlush = false\n}", "func (connection *SSEConnection) SetOnMessage(cb func([]byte)) {\n\n}", "func (l *Linenoise) SetCompletionCallback(fn func(string) []string) {\n\tl.completionCallback = fn\n}", "func (ps *PeerState) SetRoundCallback(height uint32, round uint16, f func()) {\n\tps.mtx.Lock()\n\tdefer ps.mtx.Unlock()\n\tif ps.height < height {\n\t\tps.cbHeight = height\n\t\tps.cbRound = round\n\t\tps.cbFunc = f\n\t\t// Wait until the height of the peerState changes.\n\t\t// We'll call cbFunc then.\n\t\treturn\n\t} else if ps.height == height {\n\t\tpeerRound := calcRound(ps.startTime)\n\t\tif peerRound < round {\n\t\t\t// Set a timer to call the cbFunc when the time comes.\n\t\t\tgo func() {\n\t\t\t\troundStart := calcRoundStartTime(round, ps.startTime)\n\t\t\t\ttime.Sleep(roundStart.Sub(time.Now()))\n\t\t\t\t// If peer height is still good\n\t\t\t\tps.mtx.Lock()\n\t\t\t\tpeerHeight := ps.height\n\t\t\t\tps.mtx.Unlock()\n\t\t\t\tif peerHeight == height {\n\t\t\t\t\tf()\n\t\t\t\t}\n\t\t\t}()\n\t\t} else if peerRound == round {\n\t\t\tgo f()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\treturn\n\t}\n}", "func (s *BaseConcertoListener) EnterBlock(ctx *BlockContext) {}", "func (req *Request) SetCallback(parserName string) *Request {\n\treq.Callback = parserName\n\treturn req\n}", "func (self *PhysicsP2) SetCallbackContextA(member interface{}) {\n self.Object.Set(\"callbackContext\", member)\n}", "func setCallback(a *apl.Apl, L, R apl.Value) (apl.Value, error) {\n\tw, ok := toWidget(L)\n\tif ok == false {\n\t\treturn nil, fmt.Errorf(\"u f: left argument must be a widget\")\n\t}\n\n\tlst, ok := R.(apl.List)\n\tif ok == false {\n\t\treturn nil, fmt.Errorf(\"u f: right argument must be a list\")\n\t}\n\tif len(lst) == 1 {\n\t\tif fn, ok := lst[0].(apl.Function); ok {\n\t\t\treturn setcb(a, w, fn)\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"u f: argument must be a list containing a single function\")\n}", "func newCallBackHandler() (raw.OnewayHandler, <-chan map[string]string) {\n\tserverCalledBack := make(chan map[string]string)\n\treturn func(ctx context.Context, body []byte) error {\n\t\tserverCalledBack <- extractBaggage(ctx)\n\t\treturn nil\n\t}, serverCalledBack\n}", "func (t *Tortoise) OnBlock(header types.BlockHeader) {\n\tstart := time.Now()\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\twaitBlockDuration.Observe(float64(time.Since(start).Nanoseconds()))\n\tt.trtl.onBlock(header, true, false)\n\tif t.tracer != nil {\n\t\tt.tracer.On(&BlockTrace{Header: header})\n\t}\n}", "func SetBlockFunc(blockFunc func([]byte) (cipher.Block, error)) Option {\n\treturn func(o *options) {\n\t\to.blockFunc = blockFunc\n\t}\n}", "func (app AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {}", "func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {}", "func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {}", "func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {}", "func (s *DefaultSelector) SetOnDataCb(cb OnDataCb) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.onDataCb = cb\n}", "func (wrapper *HTTPServerConnectionChainWrapper) AddCallback(callback ConnectionCallback) {\n\twrapper.callbacks = append(wrapper.callbacks, callback)\n}", "func (cs *Callbacks) AddAfterBanCallBack(f func(rc *RemoteClient)) {\n\tcs.Lock()\n\tcs.afterBan = append(cs.afterBan, f)\n\tcs.Unlock()\n}", "func OnBlockDoneOption(handler func(size int)) Option {\n\tif handler == nil {\n\t\thandler = onBlockDone\n\t}\n\treturn func(a applier) error {\n\t\tswitch rw := a.(type) {\n\t\tcase nil:\n\t\t\ts := fmt.Sprintf(\"OnBlockDoneOption(%s)\", reflect.TypeOf(handler).String())\n\t\t\treturn lz4errors.Error(s)\n\t\tcase *Writer:\n\t\t\trw.handler = handler\n\t\t\treturn nil\n\t\tcase *Reader:\n\t\t\trw.handler = handler\n\t\t\treturn nil\n\t\t}\n\t\treturn lz4errors.ErrOptionNotApplicable\n\t}\n}", "func (item *CacheItem) SetAboutToExpireCallback(f func(interface{})) {\n\tif len(item.aboutToExpire) > 0 {\n\t\titem.RemoveAboutToExpireCallbacks()\n\t}\n\titem.Lock()\n\tdefer item.Unlock()\n\titem.aboutToExpire = append(item.aboutToExpire, f)\n}", "func Callback(onFire func() error) *CB {\n\treturn &CB{\n\t\tonFire: onFire,\n\t}\n}", "func (e *GExit) AddCb(cb func()) {\n\te.mtx.Lock()\n\te.exits = append(e.exits, cb)\n\te.mtx.Unlock()\n}", "func (t *StreamTransport) SetCallBack(cb StreamTransportCallbacker) {\n\tt.cb = cb\n}", "func (ac *asyncCallbacksHandler) push(f func()) {\n\tac.cbQueue <- f\n}", "func (_m *TxManager) OnNewLongestChain(ctx context.Context, head *types.Head) {\n\t_m.Called(ctx, head)\n}", "func (player *Player) OnBlockPlaced(handler func(event *event.BlockPlaced)) {\n\tplayer.on(event.NameBlockPlaced, func(e interface{}) {\n\t\thandler(e.(*event.BlockPlaced))\n\t})\n}", "func (locator *ServiceLocatorImpl) InstallBeginCallBack(f func(Worker)) {\n\tlocator.beginCallBack = append(locator.beginCallBack, f)\n}", "func (mb *MenuButton) SetCallBack(callback Callback) {\n\tmb.callback = callback\n}", "func (t *Transaction) onBlock(block *types.Block) bool {\n\treturn t.onBlockNumberUpdate(block.NumberU64())\n}", "func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {}", "func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {}", "func (h *Handler) AddCallback(fn func(*Beacon)) {\n\th.Lock()\n\tdefer h.Unlock()\n\th.callbacks = append(h.callbacks, fn)\n}", "func (noopMeter) RegisterCallback([]instrument.Asynchronous, func(context.Context)) error {\n\treturn nil\n}", "func (g *goMetrics) AddCallback(f func(stats *runtime.MemStats)) {\n\tg.mu.Lock()\n\tg.cb = append(g.cb, f)\n\tg.mu.Unlock()\n}", "func (this *Blockchain) addBlock(block Block) {\n mutex.Lock()\n this.chain = append(this.chain, block)\n mutex.Unlock()\n // reset pending Transactions\n this.pendingTransactions = nil\n}", "func (p *blockParser) run() {\n\tfor p.state = parseBegin; p.state != nil; {\n\t\tp.state = p.state(p)\n\t}\n\tclose(p.blockChan)\n}", "func (s *BaseBundListener) EnterBlock(ctx *BlockContext) {}", "func (self *SinglePad) SetOnUpCallbackA(member interface{}) {\n self.Object.Set(\"onUpCallback\", member)\n}", "func OnBlockFinalizedConsumer(finalizedBlockID flow.Identifier) {\n\tfmt.Printf(\">>>>>>>>>>>>>>>>>>>> Received finalized block: %s\\n\", finalizedBlockID.String())\n}", "func (cs *Callbacks) AddAfterServedCallBack(f func(context *Context)) {\n\tcs.Lock()\n\tcs.afterServed = append(cs.afterServed, f)\n\tcs.Unlock()\n}", "func (s *server) SetNewMessageCB(callback func(c *Client, message string)) {\n\ts.onNewMessage = callback\n}", "func (s *scheduler) onPrecommitBlkDone(e sched.Event) {\n\tevent := e.(*precommitBlockEvent)\n\ts.commiters.mu.Lock()\n\tcommiter, ok := s.commiters.blkmap[event.Id.TableID]\n\tif !ok {\n\t\tcommiter = newMetaBlkCommiter(s.opts, s)\n\t\ts.commiters.blkmap[event.Id.TableID] = commiter\n\t}\n\tcommiter.Register(event.Id.BlockID)\n\ts.commiters.mu.Unlock()\n}", "func (self *SinglePad) SetCallbackContextA(member interface{}) {\n self.Object.Set(\"callbackContext\", member)\n}", "func (c *cell) AddCallback(f func(int)) CallbackHandle {\n\tc.callbacks[nextCallbackId] = f\n\tnextCallbackId++\n\treturn callbackHandle{id: nextCallbackId - 1}\n}", "func (o *ReaderOptions) SetPasswordCallback(cb func() string) {\n\to.cb = cb\n}", "func (d *dispatcher) dispatchBlockCommit(msg proto.Message, done chan bool) {\n\tif atomic.LoadInt32(&d.shutdown) != 0 {\n\t\tif done != nil {\n\t\t\tclose(done)\n\t\t}\n\t\treturn\n\t}\n\td.newsChan <- &blockMsg{(msg).(*pb.BlockPb), pb.MsgBlockProtoMsgType, done}\n}", "func (w *Watcher) Register(cb func(bts []byte)) {\n\tw.writeCallback = cb\n}", "func (am AppModule) BeginBlock(ctx sdk.Context, req abci.RequestBeginBlock) {\n}", "func (r *RuntimeImpl) Block() {\n\t<-r.blocker\n}", "func (this *ModuleManager) CallWithCallback(topic string, f, cb interface{}, cbParams, params []interface{}) (err error) {\n\tif m := this.GetModule(topic); m != nil {\n\t\terr = m.CallWithCallback(f, cb, cbParams, params)\n\t} else {\n\t\t// fmt.Println(this)\n\t\terr = Post.PutQueueWithCallback(f, cb, cbParams, params...)\n\t}\n\treturn\n}", "func (self *SinglePad) SetOnConnectCallbackA(member interface{}) {\n self.Object.Set(\"onConnectCallback\", member)\n}", "func (s *TcpServer) OnNewBytes(callback func(c *Client, bytes []byte)) {\r\n\ts.onNewBytes = callback\r\n}", "func (t *Tortoise) OnValidBlock(header types.BlockHeader) {\n\tstart := time.Now()\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\twaitBlockDuration.Observe(float64(time.Since(start).Nanoseconds()))\n\tt.trtl.onBlock(header, true, true)\n\tif t.tracer != nil {\n\t\tt.tracer.On(&BlockTrace{Header: header, Valid: true})\n\t}\n}", "func (self *PhysicsP2) SetPostBroadphaseCallbackA(member interface{}) {\n self.Object.Set(\"postBroadphaseCallback\", member)\n}", "func (s *scheduler) onCommitBlkDone(e sched.Event) {\n\tif err := e.GetError(); err != nil {\n\t\ts.opts.EventListener.BackgroundErrorCB(err)\n\t\treturn\n\t}\n\tevent := e.(*commitBlkEvent)\n\tif !event.Ctx.HasDataScope() {\n\t\treturn\n\t}\n\tnewMeta := event.Meta\n\tmctx := &Context{Opts: s.opts}\n\ttableData, err := s.tables.StrongRefTable(newMeta.Segment.Table.Id)\n\tif err != nil {\n\t\ts.opts.EventListener.BackgroundErrorCB(err)\n\t\treturn\n\t}\n\tlogutil.Infof(\" %s | Block %d | UpgradeBlkEvent | Started\", sched.EventPrefix, newMeta.Id)\n\tnewevent := NewUpgradeBlkEvent(mctx, newMeta, tableData)\n\ts.Schedule(newevent)\n}", "func (client *Client) QueryBlockWithCallback(request *QueryBlockRequest, callback func(response *QueryBlockResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *QueryBlockResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.QueryBlock(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (n *Node) AddCallback(f func(int)) Canceler {\n\tn.callbacks = append(n.callbacks, f)\n\treturn CallbackCanceler{n, len(n.callbacks) - 1}\n}", "func (s *Module) SetUpdateValidatorsCallback(f func(uint32, keys.PublicKeys)) {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\ts.updateValidatorsCb = f\n}", "func (p *Proxy) SetupHandlerOnProxyBalanceFunc(function func(model *BalanceModel, fbeType int, buffer []byte)) { p.HandlerOnProxyBalance = OnProxyBalanceFunc(function) }", "func (_AnchorChain *AnchorChainTransactor) Callback(opts *bind.TransactOpts, state bool, _result []string) (*types.Transaction, error) {\n\treturn _AnchorChain.contract.Transact(opts, \"callback\", state, _result)\n}", "func TestBasicCallback(t *testing.T) {\n\tr := New()\n\ti := r.CreateInput(1)\n\tc := r.CreateCompute1(i, func(v int) int { return v + 1 })\n\tvar observed []int\n\tc.AddCallback(func(v int) {\n\t\tobserved = append(observed, v)\n\t})\n\tif len(observed) != 0 {\n\t\tt.Fatalf(\"callback called before changes were made\")\n\t}\n\ti.SetValue(2)\n\tif len(observed) != 1 {\n\t\tt.Fatalf(\"callback not called when changes were made\")\n\t}\n\tif observed[0] != 3 {\n\t\tt.Fatalf(\"callback not called with proper value\")\n\t}\n}", "func WithBlockingCallback() Option {\n\treturn func(i interface{}) error {\n\t\tif c, ok := i.(*ceClient); ok {\n\t\t\tc.blockingCallback = true\n\t\t}\n\t\treturn nil\n\t}\n}", "func InvokeCallback(ctx *context.T, name string) {\n\tconfig, err := exec.ReadConfigFromOSEnv()\n\tif err != nil || config == nil {\n\t\treturn\n\t}\n\t// Device manager was started by self-update, notify the parent.\n\tcallbackName, err := config.Get(mgmt.ParentNameConfigKey)\n\tif err != nil {\n\t\t// Device manager was not started by self-update, return silently.\n\t\treturn\n\t}\n\tclient := device.ConfigClient(callbackName)\n\tctx, cancel := context.WithTimeout(ctx, rpcContextTimeout)\n\tdefer cancel()\n\tif err := client.Set(ctx, mgmt.ChildNameConfigKey, name); err != nil {\n\t\tctx.Fatalf(\"Set(%v, %v) failed: %v\", mgmt.ChildNameConfigKey, name, err)\n\t}\n}", "func NewCB(onFire func() error) *CB {\n\treturn Callback(onFire)\n}", "func (cell *SpreadsheetCell) AddCallback(callback func(int)) Canceler {\n\tcallbackID++\n\tcell.callbacks[callbackID] = callback\n\treturn spreadsheetCallbackCanceler{cell: cell, index: callbackID}\n}", "func (app *BurrowMint) BeginBlock(hash []byte, header *abci.Header) {\n\n}", "func (s *BaseConcertoListener) ExitBlock(ctx *BlockContext) {}", "func (ob *Observer) updateBlock(curHeight, nextHeight int64, curBlockHash string) error {\n\tblock, err := ob.deps.Recorder.Block(nextHeight)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[Observer.updateBlock]: failed to get block info, height=%d\", nextHeight)\n\t}\n\n\tif curHeight != 0 && block.ParentBlockHash != curBlockHash {\n\t\tif err := ob.DeleteBlock(curHeight); err != nil {\n\t\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to delete a forked block\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := ob.RecordBlockAndTxs(block); err != nil {\n\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to save and process block\")\n\t}\n\n\treturn nil\n}", "func (self *ComponentScaleMinMax) SetTransformCallbackA(member interface{}) {\n self.Object.Set(\"transformCallback\", member)\n}", "func runCallback(receivedMessage *Message, consumerMessage *sarama.ConsumerMessage) {\n\tcallback := subscribeMap[consumerMessage.Topic][receivedMessage.MessageType]\n\n\tif callback == nil {\n\t\tlogrus.Error(fmt.Sprintf(\"callback not found for topic : %s, message type : %s\", consumerMessage.Topic,\n\t\t\treceivedMessage.MessageType))\n\t\treturn\n\t}\n\n\tgo callback(&Message{\n\t\tTopic: consumerMessage.Topic,\n\t\tMessage: receivedMessage.Message,\n\t\tMessageType: receivedMessage.MessageType,\n\t\tService: receivedMessage.Service,\n\t\tTraceId: receivedMessage.TraceId,\n\t\tMessageId: receivedMessage.MessageId,\n\t}, nil)\n}", "func SetKeyCallback(f KeyHandler) {\n\tkey = append(key, f)\n\tC.glfwSetKeyCB()\n}", "func (p *PoliciesDirProvider) SetOnNewPoliciesReadyCb(cb func()) {\n\tp.onNewPoliciesReadyCb = cb\n}", "func (s *BaseCymbolListener) EnterBlock(ctx *BlockContext) {}", "func AddReceivedCallback(cb func(userMsg *UserMessage)) {\n\treceivedCallbacks = append(receivedCallbacks, cb)\n}", "func (c *Context) SetMonitorCallback(callback MonitorCallback) MonitorCallback {\n\tpreviousCallback := monitorCallback\n\tmonitorCallback = callback\n\tif callback != nil {\n\t\tC.goSetMonitorCallback()\n\t} else {\n\t\tC.goRemoveMonitorCallback()\n\t}\n\treturn previousCallback\n}", "func (c *Context) SetMonitorCallback(callback MonitorCallback) MonitorCallback {\n\tpreviousCallback := monitorCallback\n\tmonitorCallback = callback\n\tif callback != nil {\n\t\tC.goSetMonitorCallback()\n\t} else {\n\t\tC.goRemoveMonitorCallback()\n\t}\n\treturn previousCallback\n}", "func NewCallback(fnc func(v []Value)) Callback {\n\treturn CallbackOf(fnc)\n}", "func (l *label) SetFinishedFunc(handler func(key tcell.Key)) tview.FormItem {\n\tl.finished = handler\n\treturn l\n}", "func InitAfterTxCommitCallback(ctx context.Context) context.Context {\n\tafterCommitFunc := []AfterCommitCallback{}\n\treturn context.WithValue(ctx, CtxKeyAfterCommitCallback, &afterCommitFunc)\n}", "func (arg1 *UConverter) SetToUCallBack(arg2 func(bool, UConverter, []byte, []uint16, []int32, UConverterCallbackReason, *UErrorCode), arg3 *UErrorCode)", "func (fss *StreamingService) ListenBeginBlock(ctx context.Context, req abci.RequestBeginBlock, res abci.ResponseBeginBlock) error {\n\tfss.blockMetadata.RequestBeginBlock = &req\n\tfss.blockMetadata.ResponseBeginBlock = &res\n\tfss.currentBlockNumber = req.Header.Height\n\treturn nil\n}", "func (client *Client) ModifyPlanWithCallback(request *ModifyPlanRequest, callback func(response *ModifyPlanResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ModifyPlanResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ModifyPlan(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (_m *PrometheusBackend) SetMaxUnconfirmedBlocks(_a0 *big.Int, _a1 int64) {\n\t_m.Called(_a0, _a1)\n}", "func (client *Client) SetCasterConfigWithCallback(request *SetCasterConfigRequest, callback func(response *SetCasterConfigResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *SetCasterConfigResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.SetCasterConfig(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func Block(f *Feed) error {\n\tf.Channel.Block = ValueYes\n\treturn nil\n}", "func (item *CacheItem) AddAboutToExpireCallback(f func(interface{})) {\n\titem.Lock()\n\tdefer item.Unlock()\n\titem.aboutToExpire = append(item.aboutToExpire, f)\n}", "func (table *ConcurrentHashMap) CallBackUpdate(key KeyType, cb func(ValueType) ValueType) {\n\thashValue := table.mhash(key)\n\tshard := table.getShard(hashValue)\n\n\ttable.RWLocks[shard].Lock()\n\n\texists, value := table.shards[shard].shardGetVal(key, hashValue)\n\tif exists {\n\t\ttable.shards[shard].shardSet(key, hashValue, cb(value))\n\t}\n\n\ttable.RWLocks[shard].Unlock()\n\n}", "func (client *Client) ModifyUserEventPlanTimeWithCallback(request *ModifyUserEventPlanTimeRequest, callback func(response *ModifyUserEventPlanTimeResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ModifyUserEventPlanTimeResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ModifyUserEventPlanTime(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (s *BaseGraffleParserListener) EnterFunctions_block(ctx *Functions_blockContext) {}" ]
[ "0.5863456", "0.5697866", "0.568345", "0.5491504", "0.5381555", "0.5343357", "0.52973217", "0.52345043", "0.5169272", "0.5145329", "0.51420856", "0.51409525", "0.50777704", "0.5075929", "0.5064654", "0.50526845", "0.5041527", "0.50297105", "0.50177705", "0.50153047", "0.50027204", "0.49933857", "0.49787533", "0.4963633", "0.4963633", "0.4963633", "0.49497524", "0.49324408", "0.49249604", "0.4921031", "0.49171355", "0.4917067", "0.49150467", "0.48949152", "0.4891184", "0.487301", "0.48668164", "0.48486498", "0.48405436", "0.48302814", "0.48229545", "0.48229545", "0.48103362", "0.48098472", "0.4793861", "0.47936025", "0.47929403", "0.4792147", "0.47768322", "0.47747502", "0.47682545", "0.47680134", "0.4760542", "0.47566685", "0.47563633", "0.4753252", "0.47404817", "0.4732094", "0.4731049", "0.47188133", "0.47118017", "0.4709313", "0.47032452", "0.46968824", "0.46865112", "0.46861532", "0.4681247", "0.4680181", "0.46424657", "0.4641754", "0.46241844", "0.46200377", "0.46197158", "0.46166906", "0.46162134", "0.4606889", "0.45942706", "0.45895636", "0.45821548", "0.45781958", "0.4567142", "0.45651326", "0.4560865", "0.45513454", "0.45497018", "0.45352763", "0.45352763", "0.45334798", "0.45241147", "0.45229763", "0.45195642", "0.45144105", "0.4510673", "0.45062235", "0.45005435", "0.44904172", "0.44883534", "0.44855854", "0.44768623", "0.44753358" ]
0.6094151
0
NewCmdConfigUseContext returns a Command instance for 'config usecontext' sub command
func NewCmdConfigUseContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command { options := &useContextOptions{configAccess: configAccess} cmd := &cobra.Command{ Use: "use-context CONTEXT_NAME", DisableFlagsInUseLine: true, Short: i18n.T("Set the current-context in a kubeconfig file"), Aliases: []string{"use"}, Long: `Set the current-context in a kubeconfig file.`, Example: useContextExample, ValidArgsFunction: completion.ContextCompletionFunc, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(options.complete(cmd)) cmdutil.CheckErr(options.run()) fmt.Fprintf(out, "Switched to context %q.\n", options.contextName) }, } return cmd }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewCommandConfig(options *app.Options) *cobra.Command {\n\to := &ConfigOptions{\n\t\tOptions: options,\n\t}\n\n\t// root\n\tcmds := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Configuration command\",\n\t\tLong: \"This is a configuration command\",\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tc.Help()\n\t\t},\n\t}\n\n\t// add-context\n\tcmdC := &cobra.Command{\n\t\tUse: \"add-context (NAME | --name NAME) [options]\",\n\t\tShort: \"Add a context\",\n\t\tDisableFlagsInUseLine: true,\n\t\tArgs: app.BindCommandArgs(&o.Name),\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\tif len(o.Name) == 0 {\n\t\t\t\t\treturn fmt.Errorf(\"Name is required.\")\n\t\t\t\t}\n\t\t\t\tif _, ok := app.Config.Contexts[o.Name]; ok {\n\t\t\t\t\treturn fmt.Errorf(\"The context '%s' is alreaday exist\", o.Name)\n\t\t\t\t} else {\n\t\t\t\t\tvar sConf *app.CliConfig = new(app.CliConfig)\n\n\t\t\t\t\tsConf.ServerAddr = o.Spider_Server_addr\n\t\t\t\t\tsConf.Timeout = o.Spider_Timeout\n\t\t\t\t\tsConf.Interceptors.Opentracing.Jaeger.Endpoint = o.Spider_Endpoint\n\t\t\t\t\tsConf.Interceptors.Opentracing.Jaeger.ServiceName = o.Spider_Service_name\n\t\t\t\t\tsConf.Interceptors.Opentracing.Jaeger.SampleRate = o.Spider_Sample_rate\n\n\t\t\t\t\tvar gConf *app.CliConfig = new(app.CliConfig)\n\n\t\t\t\t\tgConf.ServerAddr = o.Ladybug_Server_addr\n\t\t\t\t\tgConf.Timeout = o.Ladybug_Timeout\n\t\t\t\t\tgConf.Interceptors.Opentracing.Jaeger.Endpoint = o.Ladybug_Endpoint\n\t\t\t\t\tgConf.Interceptors.Opentracing.Jaeger.ServiceName = o.Ladybug_Service_name\n\t\t\t\t\tgConf.Interceptors.Opentracing.Jaeger.SampleRate = o.Ladybug_Sample_rate\n\n\t\t\t\t\tapp.Config.Contexts[o.Name] = &app.ConfigContext{\n\t\t\t\t\t\tName: o.Name,\n\t\t\t\t\t\tNamespace: o.Namespace,\n\t\t\t\t\t\tLadybugcli: gConf,\n\t\t\t\t\t\tSpidercli: sConf,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tapp.Config.WriteConfig()\n\t\t\t\to.writeYaml(app.Config)\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t}\n\tcmdC.Flags().StringVarP(&o.Ladybug_Server_addr, \"ladybug_server_addr\", \"\", \"127.0.0.1:50254\", \"Server Addr URL\")\n\tcmdC.Flags().StringVarP(&o.Ladybug_Timeout, \"ladybug_timeout\", \"\", \"1000s\", \"Timeout\")\n\tcmdC.Flags().StringVarP(&o.Ladybug_Endpoint, \"ladybug_endpoint\", \"\", \"localhost:6834\", \"endpoint URL\")\n\tcmdC.Flags().StringVarP(&o.Ladybug_Service_name, \"ladybug_service_name\", \"\", \"ladybug grpc client\", \"Service Name\")\n\tcmdC.Flags().StringVarP(&o.Ladybug_Sample_rate, \"ladybug_sample_rate\", \"\", \"1\", \"sample rate\")\n\tcmdC.Flags().StringVarP(&o.Spider_Server_addr, \"spider_server_addr\", \"\", \"127.0.0.1:2048\", \"Server Addr URL\")\n\tcmdC.Flags().StringVarP(&o.Spider_Timeout, \"spider_timeout\", \"\", \"1000s\", \"Timeout\")\n\tcmdC.Flags().StringVarP(&o.Spider_Endpoint, \"spider_endpoint\", \"\", \"localhost:6832\", \"endpoint URL\")\n\tcmdC.Flags().StringVarP(&o.Spider_Service_name, \"spider_service_name\", \"\", \"spider grpc client\", \"Service Name\")\n\tcmdC.Flags().StringVarP(&o.Spider_Sample_rate, \"spider_sample_rate\", \"\", \"1\", \"sample rate\")\n\tcmds.AddCommand(cmdC)\n\n\t// view\n\tcmds.AddCommand(&cobra.Command{\n\t\tUse: \"view\",\n\t\tShort: \"Get contexts\",\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\to.writeYaml(app.Config)\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t})\n\n\t// get context\n\tcmds.AddCommand(&cobra.Command{\n\t\tUse: \"get-context (NAME | --name NAME) [options]\",\n\t\tShort: \"Get a context\",\n\t\tArgs: app.BindCommandArgs(&o.Name),\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\tif o.Name == \"\" {\n\t\t\t\t\tfor k := range app.Config.Contexts {\n\t\t\t\t\t\to.Println(k)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif app.Config.Contexts[o.Name] != nil {\n\t\t\t\t\t\to.writeYaml(app.Config.Contexts[o.Name])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t})\n\n\t// set context\n\tcmdS := &cobra.Command{\n\t\tUse: \"set-context (NAME | --name NAME) [options]\",\n\t\tShort: \"Set a context\",\n\t\tArgs: app.BindCommandArgs(&o.Name),\n\t\tDisableFlagsInUseLine: true,\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\tif o.Name == \"\" {\n\t\t\t\t\tc.Help()\n\t\t\t\t} else if app.Config.Contexts[o.Name] != nil {\n\t\t\t\t\tapp.Config.Contexts[o.Name].Name = o.Name\n\t\t\t\t\tif o.Ladybug_Server_addr != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Ladybugcli.ServerAddr = o.Ladybug_Server_addr\n\t\t\t\t\t}\n\t\t\t\t\tif o.Ladybug_Timeout != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Ladybugcli.Timeout = o.Ladybug_Timeout\n\t\t\t\t\t}\n\t\t\t\t\tif o.Ladybug_Endpoint != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Ladybugcli.Interceptors.Opentracing.Jaeger.Endpoint = o.Ladybug_Endpoint\n\t\t\t\t\t}\n\t\t\t\t\tif o.Ladybug_Service_name != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Ladybugcli.Interceptors.Opentracing.Jaeger.ServiceName = o.Ladybug_Service_name\n\t\t\t\t\t}\n\t\t\t\t\tif o.Ladybug_Sample_rate != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Ladybugcli.Interceptors.Opentracing.Jaeger.SampleRate = o.Ladybug_Sample_rate\n\t\t\t\t\t}\n\t\t\t\t\tif o.Spider_Server_addr != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Spidercli.ServerAddr = o.Spider_Server_addr\n\t\t\t\t\t}\n\t\t\t\t\tif o.Spider_Timeout != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Spidercli.Timeout = o.Spider_Timeout\n\t\t\t\t\t}\n\t\t\t\t\tif o.Spider_Endpoint != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Spidercli.Interceptors.Opentracing.Jaeger.Endpoint = o.Spider_Endpoint\n\t\t\t\t\t}\n\t\t\t\t\tif o.Spider_Service_name != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Spidercli.Interceptors.Opentracing.Jaeger.ServiceName = o.Spider_Service_name\n\t\t\t\t\t}\n\t\t\t\t\tif o.Spider_Sample_rate != \"\" {\n\t\t\t\t\t\tapp.Config.Contexts[o.Name].Spidercli.Interceptors.Opentracing.Jaeger.SampleRate = o.Spider_Sample_rate\n\t\t\t\t\t}\n\t\t\t\t\to.writeYaml(app.Config.Contexts[o.Name])\n\t\t\t\t} else {\n\t\t\t\t\to.Println(\"Not found a context (name=%s)\", o.Name)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t}\n\tcmdS.Flags().StringVarP(&o.Ladybug_Server_addr, \"ladybug_server_addr\", \"\", \"127.0.0.1:50254\", \"Server Addr URL\")\n\tcmdS.Flags().StringVarP(&o.Ladybug_Timeout, \"ladybug_timeout\", \"\", \"1000s\", \"Timeout\")\n\tcmdS.Flags().StringVarP(&o.Ladybug_Endpoint, \"ladybug_endpoint\", \"\", \"localhost:6834\", \"endpoint URL\")\n\tcmdS.Flags().StringVarP(&o.Ladybug_Service_name, \"ladybug_service_name\", \"\", \"ladybug grpc client\", \"Service Name\")\n\tcmdS.Flags().StringVarP(&o.Ladybug_Sample_rate, \"ladybug_sample_rate\", \"\", \"1\", \"sample rate\")\n\tcmdS.Flags().StringVarP(&o.Spider_Server_addr, \"spider_server_addr\", \"\", \"127.0.0.1:2048\", \"Server Addr URL\")\n\tcmdS.Flags().StringVarP(&o.Spider_Timeout, \"spider_timeout\", \"\", \"1000s\", \"Timeout\")\n\tcmdS.Flags().StringVarP(&o.Spider_Endpoint, \"spider_endpoint\", \"\", \"localhost:6832\", \"endpoint URL\")\n\tcmdS.Flags().StringVarP(&o.Spider_Service_name, \"spider_service_name\", \"\", \"spider grpc client\", \"Service Name\")\n\tcmdS.Flags().StringVarP(&o.Spider_Sample_rate, \"spider_sample_rate\", \"\", \"1\", \"sample rate\")\n\tcmds.AddCommand(cmdS)\n\n\t// current-context (get/set)\n\tcmds.AddCommand(&cobra.Command{\n\t\tUse: \"current-context (NAME | --name NAME) [options]\",\n\t\tShort: \"Get/Set a current context\",\n\t\tDisableFlagsInUseLine: true,\n\t\tArgs: app.BindCommandArgs(&o.Name),\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\tif len(o.Name) > 0 {\n\t\t\t\t\t_, ok := app.Config.Contexts[o.Name]\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tapp.Config.CurrentContext = o.Name\n\t\t\t\t\t\tapp.Config.WriteConfig()\n\t\t\t\t\t} else {\n\t\t\t\t\t\to.Println(\"context '%s' is not exist\\n\", o.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\to.writeYaml(app.Config.GetCurrentContext().Name)\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t})\n\n\t// delete-context\n\tcmds.AddCommand(&cobra.Command{\n\t\tUse: \"delete-context (NAME | --name NAME) [options]\",\n\t\tShort: \"Delete a context\",\n\t\tArgs: app.BindCommandArgs(&o.Name),\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\tif o.Name == \"\" {\n\t\t\t\t\treturn fmt.Errorf(\"Name Required.\")\n\t\t\t\t}\n\t\t\t\tconf := app.Config\n\t\t\t\tif len(conf.Contexts) > 1 {\n\t\t\t\t\tdelete(conf.Contexts, o.Name)\n\t\t\t\t\tif o.Name == conf.CurrentContext {\n\t\t\t\t\t\tconf.CurrentContext = func() string {\n\t\t\t\t\t\t\tif len(conf.Contexts) > 0 {\n\t\t\t\t\t\t\t\tfor k := range conf.Contexts {\n\t\t\t\t\t\t\t\t\treturn k\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t\tconf.WriteConfig()\n\t\t\t\t}\n\t\t\t\to.writeYaml(conf)\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t})\n\n\t// set-namespace\n\tcmds.AddCommand(&cobra.Command{\n\t\tUse: \"set-namespace (NAME | --name NAME) [options]\",\n\t\tShort: \"Set a namespace to context\",\n\t\tArgs: app.BindCommandArgs(&o.Name),\n\t\tDisableFlagsInUseLine: true,\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tapp.ValidateError(c, func() error {\n\t\t\t\tif len(app.Config.GetCurrentContext().Name) == 0 {\n\t\t\t\t\tc.Help()\n\t\t\t\t} else {\n\t\t\t\t\tapp.Config.GetCurrentContext().Namespace = args[0]\n\t\t\t\t\tapp.Config.WriteConfig()\n\t\t\t\t\to.writeYaml(app.Config.GetCurrentContext())\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}())\n\t\t},\n\t})\n\n\treturn cmds\n}", "func NewCmdConfigGetContext(rootSettings *environment.AirshipCTLSettings) *cobra.Command {\n\n\ttheContext := &config.ContextOptions{}\n\tgetcontextcmd := &cobra.Command{\n\t\tUse: \"get-context NAME\",\n\t\tShort: getContextLong,\n\t\tExample: getContextExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) == 1 {\n\t\t\t\ttheContext.Name = args[0]\n\t\t\t}\n\t\t\treturn runGetContext(theContext, cmd.OutOrStdout(), rootSettings.Config())\n\t\t},\n\t}\n\n\tgctxInitFlags(theContext, getcontextcmd)\n\n\treturn getcontextcmd\n}", "func NewSet() *cobra.Command {\n\tvar opts setContextOptions\n\n\treturn &cobra.Command{\n\t\tUse: \"set-context\",\n\t\tShort: \"Updates the active hub configuration context\",\n\t\tExample: heredoc.WithCLIName(`\n\t\t\t# Selects which Hub/Gateway server to use of via a prompt\n\t\t\t<cli> config set-context\n\t\t\t\n\t\t\t# Sets the specified Hub/Gateway server\n\t\t\t<cli> config set-context localhost:8080\n\t\t`, cli.Name),\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) > 0 {\n\t\t\t\topts.serverAddress = args[0]\n\t\t\t}\n\t\t\treturn setRun(opts)\n\t\t},\n\t}\n}", "func NewCmdConfigRenameContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {\n\toptions := &RenameContextOptions{configAccess: configAccess}\n\n\tcmd := &cobra.Command{\n\t\tUse: renameContextUse,\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: renameContextShort,\n\t\tLong: renameContextLong,\n\t\tExample: renameContextExample,\n\t\tValidArgsFunction: completion.ContextCompletionFunc,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(cmd, args, out))\n\t\t\tcmdutil.CheckErr(options.Validate())\n\t\t\tcmdutil.CheckErr(options.RunRenameContext(out))\n\t\t},\n\t}\n\treturn cmd\n}", "func newCmdInstallConfig(options *installOptions, parentFlags *pflag.FlagSet) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config [flags]\",\n\t\tArgs: cobra.NoArgs,\n\t\tShort: \"Output Kubernetes cluster-wide resources to install Linkerd\",\n\t\tLong: `Output Kubernetes cluster-wide resources to install Linkerd.\n\nThis command provides Kubernetes configs necessary to install cluster-wide\nresources for the Linkerd control plane. This command should be followed by\n\"linkerd install control-plane\".`,\n\t\tExample: ` # Default install.\n linkerd install config | kubectl apply -f -\n\n # Install Linkerd into a non-default namespace.\n linkerd install config -l linkerdtest | kubectl apply -f -`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif !options.ignoreCluster {\n\t\t\t\tif err := errAfterRunningChecks(options); err != nil {\n\t\t\t\t\tif healthcheck.IsCategoryError(err, healthcheck.KubernetesAPIChecks) {\n\t\t\t\t\t\tfmt.Fprintf(os.Stderr, errMsgCannotInitializeClient, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Fprintf(os.Stderr, errMsgGlobalResourcesExist, err)\n\t\t\t\t\t}\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn installRunE(options, configStage, parentFlags)\n\t\t},\n\t}\n\n\tcmd.Flags().AddFlagSet(options.allStageFlagSet())\n\n\treturn cmd\n}", "func NewContext(\n\targs []string, in io.Reader, out io.Writer, log io.Writer,\n) (*CommandContext, error) {\n\tctx := &CommandContext{\n\t\tin: in,\n\t\tout: out,\n\t\tLog: log,\n\t}\n\n\tctx.commandName = filepath.Base(args[0])\n\tif len(args) > 1 {\n\t\tctx.directory = args[1]\n\t}\n\n\treturn ctx, nil\n}", "func NewSetContextCommand(cfgFactory config.Factory) *cobra.Command {\n\to := &config.ContextOptions{}\n\tcmd := &cobra.Command{\n\t\tUse: \"set-context CONTEXT_NAME\",\n\t\tShort: \"Airshipctl command to create/modify context in airshipctl config file\",\n\t\tLong: setContextLong[1:],\n\t\tExample: setContextExample,\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: setContextRunE(cfgFactory, o),\n\t}\n\n\taddSetContextFlags(cmd, o)\n\treturn cmd\n}", "func newConfigCmd(env *agent.EnvSettings) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Print the runtime configuration of a running agent\",\n\t}\n\n\tcmd.AddCommand(\n\t\tnewConfigAgentCmd(env),\n\t\tnewConfigCheckCmd(env),\n\t\tnewConfigJmxCmd(env),\n\t\tnewConfigZshCmd(env),\n\t\tnewConfigBashCmd(env),\n\t)\n\n\treturn cmd\n}", "func NewConfigCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"List, get or set default value for command options\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\topt.HideGlobalFlags(cmd)\n\t\t\treturn cmd.Help()\n\t\t},\n\t\tExample: \"ktctl config <sub-command> [options]\",\n\t}\n\n\tcmd.AddCommand(general.SimpleSubCommand(\"show\", \"Show all available and configured options\", config.Show, config.ShowHandle))\n\tcmd.AddCommand(general.SimpleSubCommand(\"get\", \"Fetch default value of specified option\", config.Get, config.GetHandle))\n\tcmd.AddCommand(general.SimpleSubCommand(\"set\", \"Customize default value of specified option\", config.Set, config.SetHandle))\n\tcmd.AddCommand(general.SimpleSubCommand(\"unset\", \"Restore default value of specified option\", config.Unset, config.UnsetHandle))\n\tcmd.AddCommand(general.SimpleSubCommand(\"list-profile\", \"List all pre-saved profiles\", config.ListProfile, nil))\n\tcmd.AddCommand(general.SimpleSubCommand(\"save-profile\", \"Save current configured options as a profile\", config.SaveProfile, config.SaveProfileHandle))\n\tcmd.AddCommand(general.SimpleSubCommand(\"load-profile\", \"Load config from a profile\", config.LoadProfile, config.LoadProfileHandle))\n\tcmd.AddCommand(general.SimpleSubCommand(\"drop-profile\", \"Delete a profile\", config.DropProfile, config.DropProfileHandle))\n\n\tcmd.SetUsageTemplate(general.UsageTemplate(false))\n\topt.SetOptions(cmd, cmd.Flags(), opt.Get().Config, []opt.OptionConfig{})\n\treturn cmd\n}", "func NewConfigCmd(parent *kingpin.Application) {\n\to := &configOptions{}\n\tcmd := parent.Command(\"configure\", \"Configure Beaker options\")\n\tcmd.Command(\"interactive\", \"Interactive configuration\").Default().Action(o.interactive)\n\tcmd.Command(\"test\", \"Test the configuration\").Action(o.testConnection)\n}", "func NewSetContextCommand(rootSettings *environment.AirshipCTLSettings) *cobra.Command {\n\to := &config.ContextOptions{}\n\tcmd := &cobra.Command{\n\t\tUse: \"set-context NAME\",\n\t\tShort: \"Manage contexts\",\n\t\tLong: setContextLong[1:],\n\t\tExample: setContextExample,\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tnFlags := cmd.Flags().NFlag()\n\t\t\tif len(args) == 1 {\n\t\t\t\t// context name is made optional with --current flag added\n\t\t\t\to.Name = args[0]\n\t\t\t}\n\t\t\tif o.Name != \"\" && nFlags == 0 {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"Context %q not modified. No new options provided.\\n\", o.Name)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tmodified, err := config.RunSetContext(o, rootSettings.Config, true)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif modified {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"Context %q modified.\\n\", o.Name)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(cmd.OutOrStdout(), \"Context %q created.\\n\", o.Name)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\taddSetContextFlags(o, cmd)\n\treturn cmd\n}", "func NewConfigCmd(\n\tparent *kingpin.Application,\n\tparentOpts *options.AppOptions,\n\tconfig *config.Config,\n) {\n\to := &configOptions{AppOptions: parentOpts}\n\tcmd := parent.Command(\"config\", \"Manage Beaker configuration settings\")\n\n\t// Add automatic help generation for the command group.\n\tvar helpSubcommands []string\n\tcmd.Command(\"help\", \"Show help.\").Hidden().Default().PreAction(func(c *kingpin.ParseContext) error {\n\t\tfullCommand := append([]string{cmd.Model().Name}, helpSubcommands...)\n\t\tparent.Usage(fullCommand)\n\t\treturn nil\n\t}).Arg(\"command\", \"Show help on command.\").StringsVar(&helpSubcommands)\n\n\t// Attach subcommands.\n\tnewListCmd(cmd, o, config)\n\tnewSetCmd(cmd, o, config)\n\tnewTestCmd(cmd, o)\n\tnewUnsetCmd(cmd, o, config)\n}", "func NewConfigCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config <command>\",\n\t\tShort: \"manage config operations\",\n\t}\n\tcmd.AddCommand(\n\t\tnewConfigTaskCmd(),\n\t\tnewConfigSourceCmd(),\n\t\tnewConfigMasterCmd(),\n\t\tnewConfigWorkerCmd(),\n\t\tnewExportCfgsCmd(),\n\t\tnewImportCfgsCmd(),\n\t)\n\tcmd.PersistentFlags().StringP(\"path\", \"p\", \"\", \"specify the file path to export/import`\")\n\treturn cmd\n}", "func New(name string, desc string, cfg interface{}) *Config {\n\treturn NewWithCommand(\n\t\t&cobra.Command{\n\t\t\tUse: name,\n\t\t\tLong: desc,\n\t\t\tRun: func(cmd *cobra.Command, args []string) {},\n\t\t}, cfg)\n}", "func Context() *cobra.Command {\n\tctxOptions := &ContextOptions{}\n\tcmd := &cobra.Command{\n\t\tUse: \"context [url|k8s-context]\",\n\t\tAliases: []string{\"ctx\"},\n\t\tArgs: utils.MaximumNArgsAccepted(1, \"https://okteto.com/docs/reference/cli/#context\"),\n\t\tShort: \"Manage your okteto context\",\n\t\tLong: `Manage your okteto context\n\nA context is a group of cluster access parameters. Each context contains a Kubernetes cluster, a user, and a namespace.\nThe current context is the default cluster/namespace for any Okteto CLI command.\n\nIf you want to log into an Okteto Enterprise instance, specify a URL. For example, run:\n\n $ okteto context https://cloud.okteto.com\n\nto configure your context to access Okteto Cloud.\n\nYour browser will ask for your authentication to retrieve your API token.\n\nIf you need to automate authentication or if you don't want to use browser-based authentication, use the \"--token\" parameter:\n\n $ okteto context https://cloud.okteto.com --token ${OKTETO_TOKEN}\n\nYou can also specify the name of a Kubernetes context with:\n\n $ okteto context kubernetes_context_name\n\nOr show a list of available options with:\n\n $ okteto context\n`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := context.Background()\n\t\t\tif len(args) == 1 {\n\t\t\t\tctxOptions.Context = args[0]\n\t\t\t}\n\n\t\t\tctxOptions.isCtxCommand = true\n\t\t\tctxOptions.Save = true\n\t\t\terr := Run(ctx, ctxOptions)\n\t\t\tanalytics.TrackContext(err == nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.AddCommand(List())\n\tcmd.Flags().StringVarP(&ctxOptions.Token, \"token\", \"t\", \"\", \"API token for authentication\")\n\tcmd.Flags().StringVarP(&ctxOptions.Namespace, \"namespace\", \"n\", \"\", \"namespace of your okteto context\")\n\tcmd.Flags().StringVarP(&ctxOptions.Builder, \"builder\", \"b\", \"\", \"url of the builder service\")\n\tcmd.Flags().BoolVarP(&ctxOptions.OnlyOkteto, \"okteto\", \"\", false, \"only shows okteto cluster options\")\n\treturn cmd\n}", "func newGetCfgCommand() *cobra.Command {\n\tcommand := &cobra.Command{\n\t\tUse: \"get\",\n\t\tShort: \"get config\",\n\t\tRunE: func(command *cobra.Command, _ []string) error {\n\t\t\tcomp, err := command.Flags().GetString(\"comp\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstore, err := command.Flags().GetUint64(\"store\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// mock, err := command.Flags().GetBool(\"mock\")\n\t\t\t// if err != nil {\n\t\t\t// \treturn err\n\t\t\t// }\n\t\t\tconfig, err := defaultConfigClient.Get(comp, store)\n\t\t\tfmt.Println(config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcommand.Flags().StringP(\"comp\", \"c\", \"tikv\", \"update component config\")\n\tcommand.Flags().Uint64P(\"store\", \"s\", 1,\n\t\t\"update the given store ids value\")\n\treturn command\n}", "func newCmdCertsConfig() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Certs config\",\n\t\tAliases: []string{\"cfg\"},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tklog.Info(\"args is %v\", args)\n\t\t\treturn nil\n\t\t},\n\t\tArgs: cobra.NoArgs,\n\t}\n\tcmd.AddCommand(newCmdCertsConfigDefault())\n\tcmd.AddCommand(newCmdCertsConfigCheck())\n\treturn cmd\n}", "func Use(ctx context.Context, cfg *Config) context.Context {\n\treturn secrets.Use(ctx, New(cfg))\n}", "func NewWithCommand(cmd *cobra.Command, cfg interface{}) *Config {\n\t// To avoid panics vvv\n\tcmd.ResetFlags()\n\tcmd.ResetCommands()\n\n\tc := &Config{\n\t\tViper: viper.New(),\n\t\tCmd: cmd,\n\t\tcfg: cfg,\n\t}\n\tcmd.PreRunE = func(cmd *cobra.Command, args []string) error {\n\t\treturn c.checkRequiredFlags(cmd.Flags())\n\t}\n\tc.Cmd.PersistentFlags().String(\"config\", \"\", \"The configuration file\")\n\tc.Viper.BindPFlag(\"config\", c.Cmd.PersistentFlags().Lookup(\"config\"))\n\n\treturn c\n}", "func configCurrentContextFunc(cmd *cobra.Command, args []string) {\n\tlog.Info(options.GetCurrentContextName())\n}", "func NewContext(ctx context.Context, cfg *Config) context.Context {\n\treturn context.WithValue(ctx, cfgKey, cfg)\n}", "func NewConfigommand() *cobra.Command {\n\tbp := &cobra.Command{\n\t\tUse: \"cfg\",\n\t\tShort: \"Get/update cluster config!\",\n\t}\n\tbp.AddCommand(\n\t\tnewUpdateCfgCommand(),\n\t\tnewGetCfgCommand(),\n\t)\n\treturn bp\n}", "func NewUseCmd(o *globals.GlobalOpts) *cli.Command {\n\treturn &cli.Command{\n\t\tName: \"use\",\n\t\tUsage: `Sets the current [version] used by the \"run\" command`,\n\t\tArgsUsage: \"[version]\",\n\t\tDescription: fmt.Sprintf(`The '[version]' is from the \"versions -a\" command.\nThe Envoy [version] installs on-demand into $GETENVOY_HOME/versions/[version]\nif needed.\n\nThis updates %s or %s with [version],\ndepending on which is present.\n\nExample:\n$ getenvoy use %s`, envoy.CurrentVersionWorkingDirFile, envoy.CurrentVersionHomeDirFile, version.LastKnownEnvoy),\n\t\tBefore: validateVersionArg,\n\t\tAction: func(c *cli.Context) error {\n\t\t\tv := version.Version(c.Args().First())\n\t\t\tif _, err := envoy.InstallIfNeeded(c.Context, o, globals.CurrentPlatform, v); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn envoy.WriteCurrentVersion(v, o.HomeDir)\n\t\t},\n\t}\n}", "func newContext(config *Config) (*Context, error) {\n\tctx := &Context{Env: make(map[string]string)}\n\n\tfor _, envVarName := range config.Envvars {\n\t\tvalue := os.Getenv(envVarName)\n\t\tif value != \"\" {\n\t\t\t//log.Printf(\"Env var %s found with value '%s'\", envVarName, value)\n\t\t\tctx.Env[envVarName] = value\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Env var %s not defined!\", envVarName))\n\t\t}\n\t}\n\n\treturn ctx, nil\n}", "func NewConfigCommand(io ui.IO, store CredentialStore) *ConfigCommand {\n\treturn &ConfigCommand{\n\t\tio: io,\n\t\tcredentialStore: store,\n\t}\n}", "func New(appName string) (*ffcli.Command, *Config) {\n\tcfg := Config{\n\t\tAppName: appName,\n\t}\n\n\tfs := flag.NewFlagSet(appName, flag.ExitOnError)\n\tcfg.RegisterFlags(fs)\n\n\treturn &ffcli.Command{\n\t\tShortUsage: appName + \" [flags] <subcommand> [flags] [<arg>...]\",\n\t\tFlagSet: fs,\n\t\tExec: cfg.Exec,\n\t}, &cfg\n}", "func AddCommand(parentCmd *cobra.Command, defaults map[string]interface{}, appConfig interface{}, cmdName string) {\n\tconfig := Config{\n\t\tcmdName: cmdName,\n\t\tdefaults: defaults,\n\t\tappConfig: appConfig,\n\t}\n\n\tvar cmdPrefix string\n\tif cmdName != \"\" {\n\t\tcmdPrefix = cmdName + \"-\"\n\t}\n\tcobraCommand := cobra.Command{\n\t\tUse: cmdPrefix + \"config-tool\",\n\t\tShort: \"Read, unmarshal, then write config to file or '-' for stdout\",\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\trunWithConfig(cmd, args, &config)\n\t\t},\n\t}\n\tparentCmd.AddCommand(&cobraCommand)\n\tparentCmd.PersistentFlags().StringVar(&config.inputCfgFile, cmdPrefix + \"config-file\", \"\", \"config file to read\")\n\tparentCmd.PersistentFlags().StringVar(&config.viperConfigType, cmdPrefix + \"config-type\", \"yaml\", \"format of config (default is yaml)\")\n\tif parentCmd.PersistentFlags().Lookup(\"config-env\") == nil {\n\t\tparentCmd.PersistentFlags().StringVar(&envPrefix, \"config-env\", \"\", \"use env with prefix\")\n\t}\n\tif parentCmd.PersistentFlags().Lookup(\"use-env\") == nil {\n\t\tparentCmd.PersistentFlags().BoolVar(&useEnv, \"use-env\", false, \"use env\")\n\t}\n\tcobra.OnInitialize(func() {\n\t\tInitConfig(&config)\n\t})\n}", "func (ssh *SSHConfig) CommandContext(ctx context.Context, cmdString string) (*SSHCommand, error) {\n\ttunnels, sshConfig, err := ssh.CreateTunnels()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\tsshCmdString, keyFile, err := createSSHCmd(sshConfig, cmdString, false)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to create command : %s\", err.Error())\n\t}\n\n\tcmd := exec.CommandContext(ctx, \"bash\", \"-c\", sshCmdString)\n\tsshCommand := SSHCommand{\n\t\tcmd: cmd,\n\t\ttunnels: tunnels,\n\t\tkeyFile: keyFile,\n\t}\n\treturn &sshCommand, nil\n}", "func CreateConfigCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Proof parameters config to mix coin contract\",\n\t}\n\tcmd.AddCommand(mixConfigVerifyKeyParaCmd())\n\t//cmd.AddCommand(mixConfigAuthPubKeyParaCmd())\n\tcmd.AddCommand(mixConfigPaymentPubKeyParaCmd())\n\n\treturn cmd\n}", "func config() *clientcmdapi.Config {\n\treturn &clientcmdapi.Config{\n\t\tContexts: map[string]*clientcmdapi.Context{\n\t\t\t\"foo\": {\n\t\t\t\tCluster: \"foocluster\",\n\t\t\t\tAuthInfo: \"fooauthinfo\",\n\t\t\t\tNamespace: \"foonamespace\",\n\t\t\t},\n\t\t\t\"bar\": {\n\t\t\t\tCluster: \"barcluster\",\n\t\t\t\tNamespace: \"barnamespace\",\n\t\t\t},\n\t\t},\n\t\tCurrentContext: \"foo\",\n\t\tClusters: map[string]*clientcmdapi.Cluster{\n\t\t\t\"foocluster\": {\n\t\t\t\tServer: \"http://foo.io\",\n\t\t\t},\n\t\t\t\"barcluster\": {\n\t\t\t\tServer: \"http://bar.io\",\n\t\t\t},\n\t\t},\n\t\tAuthInfos: map[string]*clientcmdapi.AuthInfo{\n\t\t\t\"fooauthinfo\": {\n\t\t\t\tUsername: \"foouser\",\n\t\t\t},\n\t\t},\n\t}\n}", "func New(opts ...*option.Option) *Context {\n\tmerged := option.Merge(opts...)\n\tvar ctx *Context\n\tif merged.Context != nil {\n\t\tvar castOK bool\n\t\tctx, castOK = merged.Context.(*Context)\n\t\tif !castOK {\n\t\t\tpanic(\"passed in a non-Context for the WithContext() function!\")\n\t\t}\n\t\treturn ctx\n\t}\n\tctx = &Context{\n\t\talert: option.EnvOrDefaultAlerter(),\n\t\tChroot: *merged.Chroot,\n\t}\n\n\tif merged.Snapshot != nil {\n\t\tctx.SnapshotPath = merged.Snapshot.Path\n\t\t// root is optional, so a extra check is warranted\n\t\tif merged.Snapshot.Root != nil {\n\t\t\tctx.SnapshotRoot = *merged.Snapshot.Root\n\t\t}\n\t\tctx.SnapshotExclusive = merged.Snapshot.Exclusive\n\t}\n\n\tif merged.Alerter != nil {\n\t\tctx.alert = merged.Alerter\n\t}\n\n\tif merged.EnableTools != nil {\n\t\tctx.EnableTools = *merged.EnableTools\n\t}\n\n\tif merged.PathOverrides != nil {\n\t\tctx.PathOverrides = merged.PathOverrides\n\t}\n\n\t// New is not allowed to return error - it would break the established API.\n\t// so the only way out is to actually do the checks here and record the error,\n\t// and return it later, at the earliest possible occasion, in Setup()\n\tif ctx.SnapshotPath != \"\" && ctx.Chroot != option.DefaultChroot {\n\t\t// The env/client code supplied a value, but we are will overwrite it when unpacking shapshots!\n\t\tctx.err = fmt.Errorf(\"Conflicting options: chroot %q and snapshot path %q\", ctx.Chroot, ctx.SnapshotPath)\n\t}\n\treturn ctx\n}", "func CommandContext(ctx context.Context, name string, arg ...string) Cmd {\n\treturn execCommandContext(ctx, name, arg...)\n}", "func newCmdAddConfigMap(\n\tfSys filesys.FileSystem,\n\tldr ifc.KvLoader,\n\trf *resource.Factory) *cobra.Command {\n\tvar flags flagsAndArgs\n\tcmd := &cobra.Command{\n\t\tUse: \"configmap NAME [--behavior={create|merge|replace}] [--from-file=[key=]source] [--from-literal=key1=value1]\",\n\t\tShort: \"Adds a configmap to the kustomization file\",\n\t\tLong: \"\",\n\t\tExample: `\n\t# Adds a configmap to the kustomization file (with a specified key)\n\tkustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345\n\n\t# Adds a configmap to the kustomization file (key is the filename)\n\tkustomize edit add configmap my-configmap --from-file=file/path\n\n\t# Adds a configmap from env-file\n\tkustomize edit add configmap my-configmap --from-env-file=env/path.env\n\n\t# Adds a configmap from env-file with behavior merge\n\tkustomize edit add configmap my-configmap --behavior=merge --from-env-file=env/path.env\t\n`,\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\terr := flags.ExpandFileSource(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = flags.Validate(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Load the kustomization file.\n\t\t\tmf, err := kustfile.NewKustomizationFile(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkustomization, err := mf.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Add the flagsAndArgs map to the kustomization file.\n\t\t\terr = addConfigMap(ldr, kustomization, flags, rf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Write out the kustomization file with added configmap.\n\t\t\treturn mf.Write(kustomization)\n\t\t},\n\t}\n\n\tcmd.Flags().StringSliceVar(\n\t\t&flags.FileSources,\n\t\t\"from-file\",\n\t\t[]string{},\n\t\t\"Key file can be specified using its file path, in which case file basename will be used as configmap \"+\n\t\t\t\"key, or optionally with a key and file path, in which case the given key will be used. Specifying a \"+\n\t\t\t\"directory will iterate each named file in the directory whose basename is a valid configmap key.\")\n\tcmd.Flags().StringArrayVar(\n\t\t&flags.LiteralSources,\n\t\t\"from-literal\",\n\t\t[]string{},\n\t\t\"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringVar(\n\t\t&flags.EnvFileSource,\n\t\t\"from-env-file\",\n\t\t\"\",\n\t\t\"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).\")\n\tcmd.Flags().BoolVar(\n\t\t&flags.DisableNameSuffixHash,\n\t\t\"disableNameSuffixHash\",\n\t\tfalse,\n\t\t\"Disable the name suffix for the configmap\")\n\tcmd.Flags().StringVar(\n\t\t&flags.Behavior,\n\t\t\"behavior\",\n\t\t\"\",\n\t\t\"Specify the behavior for config map generation, i.e whether to create a new configmap (the default), \"+\n\t\t\t\"to merge with a previously defined one, or to replace an existing one. Merge and replace should be used only \"+\n\t\t\t\" when overriding an existing configmap defined in a base\")\n\n\treturn cmd\n}", "func (m *EnvconfigAnnotation) Context(c *typast.Context) *Context {\n\tvar configs []*Envconfig\n\tfor _, annot := range c.FindAnnot(m.isEnvconfig) {\n\t\tconfigs = append(configs, createEnvconfig(annot))\n\t}\n\treturn &Context{Context: c, Configs: configs}\n}", "func CommandContext(ctx context.Context, name string, arg ...string) *Cmd {\n\treturn &Cmd{Cmd: exec.CommandContext(ctx, name, arg...), ctx: ctx}\n}", "func NewCmdConfiguration(name, fullName string) *cobra.Command {\n\tconfigurationViewCmd := NewCmdView(viewCommandName, util.GetFullName(fullName, viewCommandName))\n\tconfigurationSetCmd := NewCmdSet(setCommandName, util.GetFullName(fullName, setCommandName))\n\tconfigurationUnsetCmd := NewCmdUnset(unsetCommandName, util.GetFullName(fullName, unsetCommandName))\n\tconfigurationCmd := &cobra.Command{\n\t\tUse: name,\n\t\tShort: \"Change or view configuration\",\n\t\tLong: fmt.Sprintf(configLongDesc, config.FormatLocallySupportedParameters()),\n\t\tExample: fmt.Sprintf(\"%s\\n%s\\n%s\",\n\t\t\tconfigurationViewCmd.Example,\n\t\t\tconfigurationSetCmd.Example,\n\t\t\tconfigurationUnsetCmd.Example,\n\t\t),\n\t\tAliases: []string{\"configuration\"},\n\t}\n\n\tconfigurationCmd.AddCommand(configurationViewCmd, configurationSetCmd)\n\tconfigurationCmd.AddCommand(configurationUnsetCmd)\n\tconfigurationCmd.SetUsageTemplate(util.CmdUsageTemplate)\n\tconfigurationCmd.Annotations = map[string]string{\"command\": \"main\"}\n\n\treturn configurationCmd\n}", "func CommandContext(ctx context.Context, name string, arg ...string) *Cmd {\n\tcmd := &Cmd{\n\t\tCmd: exec.CommandContext(ctx, name, arg...),\n\t}\n\n\tcmd.setupCmd()\n\n\treturn cmd\n}", "func New(rootConfig *rootcmd.Config) *ffcli.Command {\n\tfs := flag.NewFlagSet(CmdName, flag.ContinueOnError)\n\tcfg := &Config{\n\t\trootConfig: rootConfig,\n\t\tfs: fs,\n\t}\n\tcfg.registerFlags()\n\n\tcmd := &ffcli.Command{\n\t\tName: CmdName,\n\t\tShortHelp: \"list specific resources\",\n\t\tFlagSet: fs,\n\t\tExec: func(ctx context.Context, args []string) error {\n\t\t\treturn cfg.rootConfig.CollectOutput(\n\t\t\t\tcfg,\n\t\t\t\tcfg.GetQuery(),\n\t\t\t\tutils.GetCacheKey(CmdName, cfg.all),\n\t\t\t)\n\t\t},\n\t}\n\n\treturn cmd\n}", "func NewCmd(fileUtil file.File) *cobra.Command {\n\tvar (\n\t\tcpHost string\n\t\temailID string\n\t\taccessToken string\n\t\tconnectionTimeOutSecs int\n\t)\n\tconfigCmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Configure octavius client\",\n\t\tLong: \"This command helps configure client with control plane host, email id and access token\",\n\t\tExample: \"octavius config [flags]\",\n\t\tArgs: cobra.MaximumNArgs(0),\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tconfigFilePath := filepath.Join(config.ConfigFileDir(), \"octavius_client.yaml\")\n\t\t\tisConfigFileExist := fileUtil.IsFileExist(configFilePath)\n\n\t\t\tif isConfigFileExist == true {\n\t\t\t\tlog.Warn(fmt.Sprintln(\"[Warning] This will overwrite current config:\"))\n\t\t\t\tprinter.Println(\"[Warning] This will overwrite the current config.\", color.FgYellow)\n\n\t\t\t\texistingOctaviusConfig, err := fileUtil.ReadFile(configFilePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err, fmt.Sprintln(existingOctaviusConfig))\n\t\t\t\t\tprinter.Println(\"error while reading the existing configurations\", color.FgRed)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tprinter.Println(\"Do you want to continue (Y/n)?\\t\", color.FgYellow)\n\t\t\t\tuserPermission, err := fileUtil.GetUserInput()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err, \"error getting user permission for overwriting config\")\n\t\t\t\t\tprinter.Println(\"error while getting the user permission\", color.FgRed)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif userPermission != \"y\\n\" && userPermission != \"Y\\n\" {\n\t\t\t\t\tlog.Info(fmt.Sprintln(\"Skipped configuring octavius client\"))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := fileUtil.CreateDirIfNotExist(config.ConfigFileDir())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err, \"error in creating config file directory\")\n\t\t\t\t\tprinter.Println(\"error in creating config file directory\", color.FgRed)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terr = fileUtil.CreateFile(configFilePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err, \"error in creating config file\")\n\t\t\t\t\tprinter.Println(\"error in creating config file\", color.FgRed)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tprinter.Println(\"Applying the configurations.\", color.FgBlack)\n\n\t\t\tvar configFileContent string\n\t\t\tconfigFileContent += fmt.Sprintf(\"%s: %s\\n\", config.OctaviusCPHost, cpHost)\n\t\t\tconfigFileContent += fmt.Sprintf(\"%s: %s\\n\", config.EmailID, emailID)\n\t\t\tconfigFileContent += fmt.Sprintf(\"%s: %s\\n\", config.AccessToken, accessToken)\n\t\t\tconfigFileContent += fmt.Sprintf(\"%s: %v\\n\", config.ConnectionTimeoutSecs, connectionTimeOutSecs)\n\n\t\t\terr := fileUtil.WriteFile(configFilePath, configFileContent)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err, fmt.Sprintf(\"error writing content %v to config file %s \\n\", configFileContent, configFilePath))\n\t\t\t\tprinter.Println(\"error in writing the configurations\", color.FgRed)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Info(\"Octavius client configured successfully\")\n\t\t\tprinter.Println(\"Octavius client configured successfully.\", color.FgGreen)\n\t\t},\n\t}\n\tconfigCmd.Flags().StringVarP(&cpHost, \"cp-host\", \"\", \"\", \"CP_HOST port address(required)\")\n\tconfigCmd.Flags().StringVarP(&emailID, \"email-id\", \"\", \"\", \"Client Email-id\")\n\tconfigCmd.Flags().StringVarP(&accessToken, \"token\", \"\", \"\", \"Client Access Token\")\n\tconfigCmd.Flags().IntVarP(&connectionTimeOutSecs, \"time-out\", \"\", 0, \"Connection Time Out In Sec\")\n\terr := configCmd.MarkFlagRequired(\"cp-host\")\n\tif err != nil {\n\t\tlog.Error(err, \"error while setting the flag required\")\n\t\tprinter.Println(\"error while setting the flag required\", color.FgRed)\n\t\treturn nil\n\t}\n\treturn configCmd\n}", "func New(c *Cfg) Cmd {\n\tif c.New != nil {\n\t\treturn c.New()\n\t}\n\treturn (*nilCmd)(c)\n}", "func NewCommand(logger log.Logger, streams cmd.IOStreams) *cobra.Command {\n\tflags := &flagpole{}\n\tcmd := &cobra.Command{\n\t\tArgs: cobra.NoArgs,\n\t\tUse: \"kubeconfig\",\n\t\tShort: \"Prints cluster kubeconfig\",\n\t\tLong: \"Prints cluster kubeconfig\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcli.OverrideDefaultName(cmd.Flags())\n\t\t\treturn runE(logger, streams, flags)\n\t\t},\n\t}\n\tcmd.Flags().StringVarP(\n\t\t&flags.Name,\n\t\t\"name\",\n\t\t\"n\",\n\t\tcluster.DefaultName,\n\t\t\"the cluster context name\",\n\t)\n\tcmd.Flags().BoolVar(\n\t\t&flags.Internal,\n\t\t\"internal\",\n\t\tfalse,\n\t\t\"use internal address instead of external\",\n\t)\n\treturn cmd\n}", "func NewCmdGenConfig() *cobra.Command {\n\tvar GenCommand = &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Generates a sonobuoy config for input to sonobuoy gen or run.\",\n\t\tRun: genConfigCobra,\n\t\tArgs: cobra.ExactArgs(0),\n\t}\n\n\treturn GenCommand\n}", "func New(rootConfig *rootcmd.Config) *ffcli.Command {\n\tfs := flag.NewFlagSet(CmdName, flag.ContinueOnError)\n\tcfg := &Config{\n\t\trootConfig: rootConfig,\n\t\tfs: fs,\n\t}\n\n\tcmd := &ffcli.Command{\n\t\tName: CmdName,\n\t\tShortHelp: \"list nodes\",\n\t\tFlagSet: fs,\n\t\tExec: func(ctx context.Context, args []string) error {\n\t\t\treturn cfg.rootConfig.CollectOutput(\n\t\t\t\tcfg,\n\t\t\t\tcfg.GetQuery(),\n\t\t\t\tutils.GetCacheKey(CmdName, false),\n\t\t\t)\n\t\t},\n\t}\n\treturn cmd\n}", "func NewConfig(writer io.Writer) (*CmdOptions, error) {\n\tv := viper.New()\n\tp, err := Parse(writer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tflagSet := cmdArgSet{p}\n\tif err = v.BindFlagValues(flagSet); err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot bind command-line flag values with viper: %w\", err)\n\t}\n\tflagSet.setDefaults(v)\n\tif v.IsSet(\"config\") {\n\t\tv.SetConfigFile(v.GetString(\"config\"))\n\t\terr := v.ReadInConfig() // Find and read the config file\n\t\tif err != nil { // Handle errors reading the config file\n\t\t\treturn nil, fmt.Errorf(\"Fatal error reading config file: %w\", err)\n\t\t}\n\t}\n\tconf := &CmdOptions{}\n\tif err = v.Unmarshal(conf); err != nil {\n\t\treturn nil, fmt.Errorf(\"Fatal error unmarshalling config file: %w\", err)\n\t}\n\tif conf.ClientName == \"\" {\n\t\tbuf := bytes.NewBufferString(\"The required flag `-c, --clientname` was not specified\\n\")\n\t\tp.WriteHelp(buf)\n\t\treturn conf, errors.New(buf.String())\n\t}\n\treturn conf, nil\n}", "func ConfigCmd() prompter.Command {\n\n\tresetCmd := prompter.Command{\n\t\tName: \"reset\",\n\t\tDescription: \"reset borrowed time and overwrite current configuration\",\n\t\tExecutor: resetExecutor,\n\t}\n\tresetCmd.AddArguments(prompter.Argument{\n\t\tName: \"-file\",\n\t\tDescription: \"(optional) backup file before reset\",\n\t\tArgumentCompleter: resetCompleter,\n\t})\n\n\tbackupCmd := prompter.Command{\n\t\tName: \"backup\",\n\t\tDescription: \"backup configuration and templates\",\n\t\tExecutor: backupExecutor,\n\t}\n\tbackupCmd.AddArguments(prompter.Argument{\n\t\tName: \"-file\",\n\t\tDescription: \"(optional) backup file\",\n\t\tArgumentCompleter: resetCompleter,\n\t})\n\n\teditConfigCmd := prompter.Command{\n\t\tName: \"edit\",\n\t\tDescription: \"edit the configuration directory\",\n\t\tExecutor: editConfigExecutor,\n\t}\n\n\tconfigCmd := prompter.Command{\n\t\tName: \"config\",\n\t\tDescription: \"configure workspace\",\n\t\tExecutor: configExecutor,\n\t}\n\tconfigCmd.AddArguments(prompter.Argument{\n\t\tName: \"restore\",\n\t\tDescription: \"restore configuration and templates\",\n\t\tArgumentCompleter: restoreCompleter,\n\t})\n\tconfigCmd.AddSubCommands(resetCmd, backupCmd, editConfigCmd)\n\n\treturn configCmd\n}", "func newConfigTaskUpdateCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"update <command>\",\n\t\tShort: \"update config task\",\n\t\tHidden: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn errors.Errorf(\"this function will be supported later\")\n\t\t},\n\t}\n\treturn cmd\n}", "func NewContext(ctx context.Context, config *Config) context.Context {\n\treturn context.WithValue(ctx, configContextKey{}, config)\n}", "func newCmdConfigShow(ctx api.Context) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse: \"show <name>\",\n\t\tShort: \"Print the configuration file related to the current cluster\",\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcluster, err := ctx.Cluster()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tconf := cluster.Config()\n\n\t\t\t// Show a given config key from the store.\n\t\t\tif len(args) == 1 {\n\t\t\t\tkey := args[0]\n\t\t\t\tif val := conf.Get(key); val != nil {\n\t\t\t\t\tfmt.Fprintf(ctx.Out(), \"%v\\n\", val)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"unknown key \\\"%s\\\"\", key)\n\t\t\t}\n\n\t\t\t// Show all config keys present in the store.\n\t\t\tfor _, key := range conf.Keys() {\n\t\t\t\tif val := conf.Get(key); val != nil {\n\n\t\t\t\t\t// The ACS token should be masked when printing the whole config as it is sensitive data.\n\t\t\t\t\tif key == \"core.dcos_acs_token\" {\n\t\t\t\t\t\tval = \"********\"\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintf(ctx.Out(), \"%s %v\\n\", key, val)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func CommandContext(ctx context.Context, args ...string) *exec.Cmd {\n\tcmd := exec.CommandContext(ctx, Self())\n\tcmd.Args = args\n\treturn cmd\n}", "func NewContext(config, secrets map[string]interface{}) *Context {\n\treturn &Context{\n\t\tresults: starlark.StringDict{},\n\t\tvalues: starlark.StringDict{},\n\t\tconfig: config,\n\t\tsecrets: secrets,\n\t}\n}", "func CommandContext(conf Config, state State, ctx, query Query) error {\n\tif len(os.Args) < 3 {\n\t\tfmt.Println(ctx)\n\t} else if os.Args[2] == \"none\" {\n\t\tif err := state.SetContext(Query{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := state.SetContext(query); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstate.Save(conf.StateFile)\n\treturn nil\n}", "func NewContext(opts *ContextOpts) (*Context, error) {\n\t// Validate the version requirement if it is given\n\tif opts.Module != nil {\n\t\tif err := CheckRequiredVersion(opts.Module); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Copy all the hooks and add our stop hook. We don't append directly\n\t// to the Config so that we're not modifying that in-place.\n\tsh := new(stopHook)\n\thooks := make([]Hook, len(opts.Hooks)+1)\n\tcopy(hooks, opts.Hooks)\n\thooks[len(opts.Hooks)] = sh\n\n\tstate := opts.State\n\tif state == nil {\n\t\tstate = new(State)\n\t\tstate.init()\n\t}\n\n\t// If our state is from the future, then error. Callers can avoid\n\t// this error by explicitly setting `StateFutureAllowed`.\n\tif !opts.StateFutureAllowed && state.FromFutureTerraform() {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Terraform doesn't allow running any operations against a state\\n\"+\n\t\t\t\t\"that was written by a future Terraform version. The state is\\n\"+\n\t\t\t\t\"reporting it is written by Terraform '%s'.\\n\\n\"+\n\t\t\t\t\"Please run at least that version of Terraform to continue.\",\n\t\t\tstate.TFVersion)\n\t}\n\n\t// Explicitly reset our state version to our current version so that\n\t// any operations we do will write out that our latest version\n\t// has run.\n\tstate.TFVersion = version.Version\n\n\t// Determine parallelism, default to 10. We do this both to limit\n\t// CPU pressure but also to have an extra guard against rate throttling\n\t// from providers.\n\tpar := opts.Parallelism\n\tif par == 0 {\n\t\tpar = 10\n\t}\n\n\t// Set up the variables in the following sequence:\n\t// 0 - Take default values from the configuration\n\t// 1 - Take values from TF_VAR_x environment variables\n\t// 2 - Take values specified in -var flags, overriding values\n\t// set by environment variables if necessary. This includes\n\t// values taken from -var-file in addition.\n\tvariables := make(map[string]interface{})\n\tif opts.Module != nil {\n\t\tvar err error\n\t\tvariables, err = Variables(opts.Module, opts.Variables)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Bind available provider plugins to the constraints in config\n\tvar providers map[string]ResourceProviderFactory\n\tif opts.ProviderResolver != nil {\n\t\tvar err error\n\t\tdeps := ModuleTreeDependencies(opts.Module, state)\n\t\treqd := deps.AllPluginRequirements()\n\t\tif opts.ProviderSHA256s != nil && !opts.SkipProviderVerify {\n\t\t\treqd.LockExecutables(opts.ProviderSHA256s)\n\t\t}\n\t\tproviders, err = resourceProviderFactories(opts.ProviderResolver, reqd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tproviders = make(map[string]ResourceProviderFactory)\n\t}\n\n\tdiff := opts.Diff\n\tif diff == nil {\n\t\tdiff = &Diff{}\n\t}\n\n\treturn &Context{\n\t\tcomponents: &basicComponentFactory{\n\t\t\tproviders: providers,\n\t\t\tprovisioners: opts.Provisioners,\n\t\t},\n\t\tdestroy: opts.Destroy,\n\t\tdiff: diff,\n\t\thooks: hooks,\n\t\tmeta: opts.Meta,\n\t\tmodule: opts.Module,\n\t\tshadow: opts.Shadow,\n\t\tstate: state,\n\t\ttargets: opts.Targets,\n\t\tuiInput: opts.UIInput,\n\t\tvariables: variables,\n\n\t\tparallelSem: NewSemaphore(par),\n\t\tproviderInputConfig: make(map[string]map[string]interface{}),\n\t\tproviderSHA256s: opts.ProviderSHA256s,\n\t\tsh: sh,\n\t}, nil\n}", "func (p *Platform) newContext(destroy bool) (*terraform.Context, error) {\n\tcfg, err := p.config()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvars, err := p.variables(cfg.Module.Variables)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// providerResolver := providers.ResolverFixed(p.Providers)\n\t// provisioners := p.Provisioners\n\n\t// Create ContextOpts with the current state and variables to apply\n\tctxOpts := terraform.ContextOpts{\n\t\tConfig: cfg,\n\t\tDestroy: destroy,\n\t\tState: p.State,\n\t\tVariables: vars,\n\t\tProviderResolver: providers.ResolverFixed(p.Providers),\n\t\tProvisioners: p.Provisioners,\n\t\tHooks: p.Hooks,\n\t}\n\n\tctx, diags := terraform.NewContext(&ctxOpts)\n\tif diags.HasErrors() {\n\t\treturn nil, diags.Err()\n\t}\n\n\t// Validate the context\n\tif diags = ctx.Validate(); diags.HasErrors() {\n\t\treturn nil, diags.Err()\n\t}\n\n\treturn ctx, nil\n}", "func newImportCfgsCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"import\",\n\t\tShort: \"Import the configurations of sources and tasks\",\n\t\tRunE: importCfgsFunc,\n\t}\n\tcmd.Flags().StringP(\"dir\", \"d\", \"\", \"specify the configs directory, default is `./configs`\")\n\t_ = cmd.Flags().MarkHidden(\"dir\")\n\treturn cmd\n}", "func NewContextViewCommand(settings *environment.Settings) *cobra.Command {\n\tc := ViewCommand{}\n\n\tc.Settings = settings\n\n\tcmd := &cobra.Command{\n\t\tUse: \"view [context-name]\",\n\t\tShort: \"View a context\",\n\t\tLong: \"View a context, default view current context\",\n\t\tArgs: c.ParseArgs(),\n\t\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\treturn c.Run()\n\t\t},\n\t}\n\n\tc.AddArg(&c.Name)\n\n\tcmd.SetOutput(c.Settings.Streams.Out)\n\n\treturn cmd\n}", "func NewConfigContext() *configContext {\n\treturn &configContext{\n\t\tpipelineImages: make(map[api.PipelineImageStreamTagReference]string),\n\t}\n}", "func CmdConfig(ctx *system.Context) {\n\tctx.ReplyNotify(help)\n}", "func newConfigService(sling *sling.Sling) *ConfigService {\n\treturn &ConfigService{\n\t\tsling: sling.Path(\"help/\"),\n\t}\n}", "func NewCtx(\n\tservice string,\n\tc *config.Config,\n\tl log.Logger,\n\ts stats.Stats,\n\tsd disco.Agent,\n) Ctx {\n\t// Build background registry\n\treg := bg.NewReg(service, l, s)\n\n\tlf := []log.Field{\n\t\tlog.String(\"node\", c.Node),\n\t\tlog.String(\"version\", c.Version),\n\t\tlog.String(\"log_type\", \"A\"),\n\t}\n\n\tctx, cancelFunc := goc.WithCancel(goc.Background())\n\n\treturn &context{\n\t\tservice: service,\n\t\tappConfig: c,\n\t\tbgReg: reg,\n\t\tdisco: sd,\n\t\tc: ctx,\n\t\tcancelFunc: cancelFunc,\n\t\tl: l.AddCalldepth(1),\n\t\tlFields: lf,\n\t\tstats: s,\n\t}\n}", "func NewConfig() *Config {\n\tcfg := &Config{}\n\n\tif len(os.Args) <= 1 {\n\t\tfmt.Printf(\"You have to specify a subcommand: %v\\n\", []string{ActionCreate, ActionGet, ActionDelete, ActionList, ActionShow, ActionCurator})\n\t\tos.Exit(2)\n\t}\n\tcfg.Action = os.Args[1]\n\n\tif !isValidAction(cfg.Action) {\n\t\tfmt.Printf(\"You have to specify a valid subcommand: %v\\n\", []string{ActionCreate, ActionGet, ActionDelete, ActionList, ActionShow, ActionCurator})\n\t\tos.Exit(2)\n\t}\n\n\tvar err error\n\tvar argParser *arg.Parser\n\n\tswitch cfg.Action {\n\tcase ActionCreate:\n\t\tcfg.Create = &CreateConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t\tAWSPartSize: 1, //1MB chunk\n\t\t\tSavePassword: false,\n\t\t}\n\n\t\tcfg.Create.argParser, _ = arg.NewParser(arg.Config{}, cfg.Create)\n\t\targParser = cfg.Create.argParser\n\t\terr = cfg.Create.argParser.Parse(os.Args[2:])\n\tcase ActionGet:\n\t\tcfg.Get = &GetConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t\tAWSPollInterval: 30 * time.Minute,\n\t\t\tAWSTier: \"Standard\",\n\t\t}\n\n\t\tcfg.Get.argParser, _ = arg.NewParser(arg.Config{}, cfg.Get)\n\t\targParser = cfg.Get.argParser\n\t\terr = cfg.Get.argParser.Parse(os.Args[2:])\n\tcase ActionList:\n\t\tcfg.List = &ListConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t}\n\n\t\tcfg.List.argParser, err = arg.NewParser(arg.Config{}, cfg.List)\n\t\targParser = cfg.List.argParser\n\t\terr = cfg.List.argParser.Parse(os.Args[2:])\n\t\tif err == nil {\n\t\t\tif cfg.List.Kb {\n\t\t\t\tcfg.List.Factor = 1000\n\t\t\t} else if cfg.List.Kib {\n\t\t\t\tcfg.List.Factor = 1024\n\t\t\t} else if cfg.List.Mb {\n\t\t\t\tcfg.List.Factor = 1000 * 1000\n\t\t\t} else if cfg.List.Mib {\n\t\t\t\tcfg.List.Factor = 1024 * 1024\n\t\t\t} else if cfg.List.Gb {\n\t\t\t\tcfg.List.Factor = 1000 * 1000 * 1000\n\t\t\t} else if cfg.List.Gib {\n\t\t\t\tcfg.List.Factor = 1024 * 1024 * 1024\n\t\t\t}\n\t\t}\n\tcase ActionShow:\n\t\tcfg.Show = &ShowConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\t\t}\n\n\t\tcfg.Show.argParser, _ = arg.NewParser(arg.Config{}, cfg.Show)\n\t\targParser = cfg.Show.argParser\n\t\terr = cfg.Show.argParser.Parse(os.Args[2:])\n\tcase ActionDelete:\n\t\tcfg.Delete = &DeleteConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\n\t\t\tDontAsk: false,\n\t\t}\n\n\t\tcfg.Delete.argParser, _ = arg.NewParser(arg.Config{}, cfg.Delete)\n\t\targParser = cfg.Delete.argParser\n\t\terr = cfg.Delete.argParser.Parse(os.Args[2:])\n\tcase ActionCurator:\n\t\tcfg.Curator = &CuratorConfig{\n\t\t\tGeneralConfig: GeneralConfig{\n\t\t\t\tLogLevel: \"INFO\",\n\t\t\t},\n\t\t\tDatabaseConfig: DatabaseConfig{\n\t\t\t\tDatabase: DefaultDatabase,\n\t\t\t},\n\n\t\t\tDontAsk: false,\n\t\t}\n\n\t\tcfg.Curator.argParser, _ = arg.NewParser(arg.Config{}, cfg.Curator)\n\t\targParser = cfg.Curator.argParser\n\t\terr = cfg.Curator.argParser.Parse(os.Args[2:])\n\t}\n\n\tif err != nil {\n\t\tif err == arg.ErrHelp {\n\t\t\targParser.WriteHelp(os.Stdout)\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\tfmt.Printf(\"Error while parsing arguments: %s\", err.Error())\n\t\tos.Exit(3)\n\t}\n\n\treturn cfg\n}", "func commandContext(ctx context.Context, name string, arg ...string) (*exec.Cmd, func(), error) {\n\treturn exec.CommandContext(ctx, name, arg...), func() {}, nil\n}", "func ConfigGetCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"get [<key1> [<key2> ...]]\",\n\t\tShort: \"Get configuration values\",\n\t\tLong: fmt.Sprintf(`Get configuration values.\n\n The key values can be specific.\n e.g. %[1]s get telemetry.service-name moniker.\n Or they can be parent field names\n e.g. %[1]s get api consensus\n Or they can be a type of config file:\n \"cosmos\", \"app\" -> %[2]s configuration values.\n e.g. %[1]s get app\n \"tendermint\", \"tm\", \"config\" -> %[3]s configuration values.\n e.g. %[1]s get tm\n \"client\" -> %[4]s configuration values.\n e.g. %[1]s get client\n Or they can be the word \"all\" to get all configuration values.\n e.g. %[1]s get all\n If no keys are provided, all values are retrieved.\n\n Displayed values will reflect settings defined through environment variables.\n\n`, configCmdStart, provconfig.AppConfFilename, provconfig.TmConfFilename, provconfig.ClientConfFilename),\n\t\tExample: fmt.Sprintf(`$ %[1]s get telemetry.service-name moniker \\\n$ %[1]s get api consensus \\\n$ %[1]s get app \\\n$ %[1]s get tm \\\n$ %[1]s get client \\\n$ %[1]s get all \\\n\t\t\t`, configCmdStart),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := runConfigGetCmd(cmd, args)\n\t\t\t// Note: If a RunE returns an error, the usage information is displayed.\n\t\t\t// That ends up being kind of annoying with this command.\n\t\t\t// So just output the error and still return nil.\n\t\t\tif err != nil {\n\t\t\t\tcmd.Printf(\"Error: %v\\n\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treturn cmd\n}", "func NewConfigContext(ctx context.Context, v *Config) context.Context {\n\treturn context.WithValue(ctx, configKey{}, v)\n}", "func (code *InterpCode) NewContext(cfg *ContextConfig) (ictx Context, err error) {\n\tdefer func() {\n\t\tierr := recover()\n\t\tif ierr == nil {\n\t\t\treturn\n\t\t}\n\t\tif v, ok := ierr.(error); ok {\n\t\t\terr = v\n\t\t}\n\t\terr = fmt.Errorf(\"%s\", ierr)\n\t}()\n\tdefer CaptureTrap(&err)\n\tvm, err := exec.NewVM(code.module,\n\t\texec.WithLazyCompile(true),\n\t\texec.WithGasMapper(new(GasMapper)),\n\t\texec.WithGasLimit(cfg.GasLimit))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvm.RecoverPanic = true\n\tctx := &wagonContext{\n\t\tmodule: code.module,\n\t\tvm: vm,\n\t\tuserData: make(map[string]interface{}),\n\t}\n\tvm.UserData = ctx\n\tictx = ctx\n\treturn\n}", "func newOptions() (*Options, error) {\n\to := &Options{\n\t\tconfig: new(componentconfig.CoordinatorConfiguration),\n\t}\n\treturn o, nil\n}", "func newConfigSourceUpdateCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"update <command>\",\n\t\tShort: \"update config source\",\n\t\tHidden: true,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn errors.Errorf(\"this function will be supported later\")\n\t\t},\n\t}\n\treturn cmd\n}", "func (c Command) WithContext(context interface{}) *Builder {\n\tb := c.builder()\n\tb.context = context\n\treturn b\n}", "func (m *Exec) CommandContext(ctx context.Context, args ...string) *exec.Cmd {\n\texe := exec.CommandContext(ctx, m.f.Name(), args...)\n\tfor _, opt := range m.opts {\n\t\topt(exe)\n\t}\n\treturn exe\n}", "func NewConfig(context, kubeconfig string) *Config {\n\treturn &Config{\n\t\tKubeConfig: kubeconfig,\n\t\tContext: context,\n\t}\n}", "func NewContext() {\n\tCfg, err := ini.LoadSources(ini.LoadOptions{\n\t\tIgnoreInlineComment: true,\n\t}, \"conf/app.ini\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to parse 'conf/app.ini': %v\", err)\n\t}\n\t// log.Printf(\"%q\\n\", Cfg.Section(\"server\").Keys())\n\n\t// set AppName and AppURL\n\tsec := Cfg.Section(\"server\")\n\tAppName = Cfg.Section(\"\").Key(\"APP_NAME\").MustString(\"Letitgo\")\n\tAppURL = sec.Key(\"ROOT_URL\").MustString(\"http://localhost:9000/\")\n\tif AppURL[len(AppURL)-1] != '/' {\n\t\tAppURL += \"/\"\n\t}\n\tDomain = sec.Key(\"DOMAIN\").MustString(\"localhost\")\n\tHTTPAddr = sec.Key(\"HTTP_ADDR\").MustString(\"0.0.0.0\")\n\tHTTPPort = sec.Key(\"HTTP_PORT\").MustString(\"9000\")\n\tDisableRouterLog = sec.Key(\"DISABLE_ROUTER_LOG\").MustBool()\n}", "func (ne *NSEnter) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {\n\thostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)\n\tfullArgs := append([]string{fmt.Sprintf(\"--mount=%s\", hostProcMountNsPath), \"--\"},\n\t\tappend([]string{ne.AbsHostPath(cmd)}, args...)...)\n\tklog.V(5).Infof(\"Running nsenter command: %v %v\", nsenterPath, fullArgs)\n\treturn ne.executor.CommandContext(ctx, nsenterPath, fullArgs...)\n}", "func New(o *Options) *cobra.Command {\n\tcmd := &cobra.Command{}\n\tcmd.Flags().StringVar(&o.KubeConfigPath, \"kubeconfig\", o.KubeConfigPath, \"absolute path of kubeconfig\")\n\tcmd.Flags().StringVar(&o.Provider, \"provider\", o.Provider, \"provider name of ACME\")\n\tcmd.Flags().StringVar(&o.BackendURL, \"backend\", o.BackendURL, \"URL for backend\")\n\tcmd.Flags().StringVar(&o.CaddyHost, \"caddy-host\", o.CaddyHost, \"hostname or ip of caddy\")\n\n\t// cloudflare provider\n\tcmd.Flags().StringVar(&o.CloudFlareEmail, \"cloudflare-email\", o.CloudFlareEmail, \"[cloudflare] Email\")\n\tcmd.Flags().StringVar(&o.CloudFlareAPIToken, \"cloudflare-api-token\", o.CloudFlareAPIToken, \"[cloudflare] API Token\")\n\treturn cmd\n}", "func AddConfigCommand() *cobra.Command {\n\tvar opt opts.ConfigOpts\n\n\tvar command = &cobra.Command{\n\t\tUse: \"add\",\n\t\tShort: \"Add an new user config\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Println(\"Add an user config.\")\n\n\t\t\treader := bufio.NewReader(os.Stdin)\n\n\t\t\tflags := cmd.Flags()\n\t\t\tname, err := flags.GetString(\"name\")\n\t\t\tfor name == \"\" && err == nil {\n\t\t\t\tfmt.Print(\"Enter your name: \")\n\t\t\t\tname, err = reader.ReadString('\\n')\n\t\t\t\tname = strings.TrimSpace(name)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error: \" + err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\temail, err := flags.GetString(\"email\")\n\t\t\tfor email == \"\" && err == nil {\n\t\t\t\tfmt.Print(\"Enter your email: \")\n\t\t\t\temail, err = reader.ReadString('\\n')\n\t\t\t\temail = strings.TrimSpace(email)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error: \" + err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tkey, err := flags.GetString(\"key\")\n\t\t\tfor key == \"\" && err == nil {\n\t\t\t\tfmt.Print(\"Enter file in which the ssh-key is (such as ~/.ssh/id_rsa): \")\n\t\t\t\tkey, err = reader.ReadString('\\n')\n\t\t\t\tkey = strings.TrimSpace(key)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error: \" + err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\ttag, err := flags.GetString(\"tag\")\n\t\t\tfor data.CheckTag(tag) && err == nil {\n\t\t\t\tif tag != \"\" {\n\t\t\t\t\tfmt.Println(\"The tag is used.\")\n\t\t\t\t}\n\t\t\t\tfmt.Print(\"Enter a tag for the new config: \")\n\t\t\t\ttag, err = reader.ReadString('\\n')\n\t\t\t\ttag = strings.TrimSpace(tag)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error: \" + err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\terr = data.Add(opts.ConfigOpts{\n\t\t\t\tName: name,\n\t\t\t\tEmail: email,\n\t\t\t\tKeyPath: key,\n\t\t\t\tTag: tag,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error: \" + err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t},\n\t}\n\n\tcommand.Flags().StringVarP(&opt.Name, \"name\", \"n\", \"\", \"override user.name\")\n\tcommand.Flags().StringVarP(&opt.Email, \"email\", \"e\", \"\", \"override user.email\")\n\tcommand.Flags().StringVarP(&opt.KeyPath, \"key\", \"k\", \"\", \"override ssh-key\")\n\tcommand.Flags().StringVarP(&opt.Tag, \"tag\", \"t\", \"\", \"tag for the new config\")\n\n\treturn command\n}", "func SetConfig() cli.Command {\n\tr := routesCmd{}\n\treturn cli.Command{\n\t\tName: \"route\",\n\t\tUsage: \"Store a configuration key for this route\",\n\t\tDescription: \"This command sets configurations for a route.\",\n\t\tCategory: \"MANAGEMENT COMMAND\",\n\t\tAliases: []string{\"routes\", \"r\"},\n\t\tBefore: func(c *cli.Context) error {\n\t\t\tvar err error\n\t\t\tr.provider, err = client.CurrentProvider()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tr.client = r.provider.APIClient()\n\t\t\treturn nil\n\t\t},\n\t\tArgsUsage: \"<app-name> </path> <key> <value>\",\n\t\tAction: r.setConfig,\n\t}\n}", "func Kubeconfig() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"kubeconfig\",\n\t\tShort: \"Download credentials for the Kubernetes cluster selected via 'okteto context'\",\n\t\tArgs: utils.NoArgsAccepted(\"https://okteto.com/docs/reference/cli/#kubeconfig\"),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\t\terr := contextCMD.UpdateKubeconfigCMD().RunE(cmd, args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn err\n\t\t},\n\t}\n\treturn cmd\n}", "func newCommand(tb DirCleaner, opts ...server.CommandOption) *Command {\n\tpath := tb.TempDir()\n\n\t// Set aggressive close timeout by default to avoid hanging tests. This was\n\t// a problem with PDK tests which used pilosa/client as well. We put it at the\n\t// beginning of the option slice so that it can be overridden by user-passed\n\t// options.\n\topts = append([]server.CommandOption{\n\t\tserver.OptCommandCloseTimeout(time.Millisecond * 2),\n\t}, opts...)\n\n\tm := &Command{commandOptions: opts}\n\toutput := io.Discard\n\tif testing.Verbose() {\n\t\toutput = os.Stderr\n\t}\n\tm.Command = server.NewCommand(output, opts...)\n\t// pick etcd ports using a socket rather than a real port\n\terr := GetPortsGenConfigs(tb, []*Command{m})\n\tif err != nil {\n\t\ttb.Fatalf(\"generating config: %v\", err)\n\t}\n\tm.Config.DataDir = path\n\tdefaultConf := server.NewConfig()\n\n\tif m.Config.Bind == defaultConf.Bind {\n\t\tm.Config.Bind = \"http://localhost:0\"\n\t}\n\n\tif m.Config.BindGRPC == defaultConf.BindGRPC {\n\t\tm.Config.BindGRPC = \"http://localhost:0\"\n\t}\n\n\tm.Config.Translation.MapSize = 140000\n\tm.Config.WorkerPoolSize = 2\n\n\treturn m\n}", "func NewConfigCommand() *Command {\n\tcmd := &Command{\n\t\tName: \"profile\",\n\t\tUsage: \"Manage your CLI profiles.\",\n\t\tSubCommands: Mux{\n\t\t\t\"create\": newCreateProfileCmd(),\n\t\t\t\"delete\": newDeleteProfileCmd(),\n\t\t\t\"info\": newProfileInfoCmd(),\n\t\t\t\"list\": newListCmd(),\n\t\t\t\"switch\": newSwitchCmd(),\n\t\t},\n\t}\n\tcmd.NewFlagSet(\"iobeam profile\")\n\n\treturn cmd\n}", "func AddContextToConfig(config *api.Config, contextName string, clusterName string, authInfoName string) error {\n\tlogger := logging.GetProjectLogger()\n\tlogger.Infof(\"Appending context %s to kubectl config.\", contextName)\n\tnewContext := api.NewContext()\n\tnewContext.Cluster = clusterName\n\tnewContext.AuthInfo = authInfoName\n\tconfig.Contexts[contextName] = newContext\n\tlogger.Infof(\"Successfully appended context to kubectl config.\")\n\treturn nil\n}", "func GetConfig() cli.Command {\n\tr := routesCmd{}\n\treturn cli.Command{\n\t\tName: \"route\",\n\t\tUsage: \"Inspect configuration key for this route\",\n\t\tDescription: \"This command gets the configurations for a route.\",\n\t\tAliases: []string{\"routes\", \"r\"},\n\t\tCategory: \"MANAGEMENT COMMAND\",\n\t\tBefore: func(c *cli.Context) error {\n\t\t\tvar err error\n\t\t\tr.provider, err = client.CurrentProvider()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tr.client = r.provider.APIClient()\n\t\t\treturn nil\n\t\t},\n\t\tArgsUsage: \"<app-name> </path> <key>\",\n\t\tAction: r.getConfig,\n\t}\n}", "func newProjectCommandContext(ctx *command.Context,\n\tcmd command.Name,\n\tapplyCmd string,\n\tapprovePoliciesCmd string,\n\tplanCmd string,\n\tprojCfg valid.MergedProjectCfg,\n\tsteps []valid.Step,\n\tpolicySets valid.PolicySets,\n\tescapedCommentArgs []string,\n\tautomergeEnabled bool,\n\tparallelApplyEnabled bool,\n\tparallelPlanEnabled bool,\n\tverbose bool,\n\tabortOnExcecutionOrderFail bool,\n\tscope tally.Scope,\n\tpullStatus models.PullReqStatus,\n) command.ProjectContext {\n\n\tvar projectPlanStatus models.ProjectPlanStatus\n\tvar projectPolicyStatus []models.PolicySetStatus\n\n\tif ctx.PullStatus != nil {\n\t\tfor _, project := range ctx.PullStatus.Projects {\n\n\t\t\t// if name is not used, let's match the directory\n\t\t\tif projCfg.Name == \"\" && project.RepoRelDir == projCfg.RepoRelDir {\n\t\t\t\tprojectPlanStatus = project.Status\n\t\t\t\tprojectPolicyStatus = project.PolicyStatus\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif projCfg.Name != \"\" && project.ProjectName == projCfg.Name {\n\t\t\t\tprojectPlanStatus = project.Status\n\t\t\t\tprojectPolicyStatus = project.PolicyStatus\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn command.ProjectContext{\n\t\tCommandName: cmd,\n\t\tApplyCmd: applyCmd,\n\t\tApprovePoliciesCmd: approvePoliciesCmd,\n\t\tBaseRepo: ctx.Pull.BaseRepo,\n\t\tEscapedCommentArgs: escapedCommentArgs,\n\t\tAutomergeEnabled: automergeEnabled,\n\t\tDeleteSourceBranchOnMerge: projCfg.DeleteSourceBranchOnMerge,\n\t\tRepoLocking: projCfg.RepoLocking,\n\t\tParallelApplyEnabled: parallelApplyEnabled,\n\t\tParallelPlanEnabled: parallelPlanEnabled,\n\t\tParallelPolicyCheckEnabled: parallelPlanEnabled,\n\t\tAutoplanEnabled: projCfg.AutoplanEnabled,\n\t\tSteps: steps,\n\t\tHeadRepo: ctx.HeadRepo,\n\t\tLog: ctx.Log,\n\t\tScope: scope,\n\t\tProjectPlanStatus: projectPlanStatus,\n\t\tProjectPolicyStatus: projectPolicyStatus,\n\t\tPull: ctx.Pull,\n\t\tProjectName: projCfg.Name,\n\t\tPlanRequirements: projCfg.PlanRequirements,\n\t\tApplyRequirements: projCfg.ApplyRequirements,\n\t\tImportRequirements: projCfg.ImportRequirements,\n\t\tRePlanCmd: planCmd,\n\t\tRepoRelDir: projCfg.RepoRelDir,\n\t\tRepoConfigVersion: projCfg.RepoCfgVersion,\n\t\tTerraformVersion: projCfg.TerraformVersion,\n\t\tUser: ctx.User,\n\t\tVerbose: verbose,\n\t\tWorkspace: projCfg.Workspace,\n\t\tPolicySets: policySets,\n\t\tPolicySetTarget: ctx.PolicySet,\n\t\tClearPolicyApproval: ctx.ClearPolicyApproval,\n\t\tPullReqStatus: pullStatus,\n\t\tJobID: uuid.New().String(),\n\t\tExecutionOrderGroup: projCfg.ExecutionOrderGroup,\n\t\tAbortOnExcecutionOrderFail: abortOnExcecutionOrderFail,\n\t}\n}", "func ConfigCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"config\",\n\t\tAliases: []string{\"conf\"},\n\t\tShort: \"Manage configuration values\",\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\tcmd.AddCommand(\n\t\tConfigGetCmd(),\n\t\tConfigSetCmd(),\n\t\tConfigChangedCmd(),\n\t\tConfigPackCmd(),\n\t\tConfigUnpackCmd(),\n\t)\n\treturn cmd\n}", "func Cmd() *cobra.Command {\n\treturn configCmd\n}", "func NewConfigPluginCmd(opt *common.CommonOption) (cmd *cobra.Command) {\n\tcmd = &cobra.Command{\n\t\tUse: \"plugin\",\n\t\tShort: i18n.T(\"Manage plugins for jcli\"),\n\t\tLong: i18n.T(`Manage plugins for jcli\nIf you want to submit a plugin for jcli, please see also the following project.\nhttps://github.com/jenkins-zh/jcli-plugins`),\n\t\tAnnotations: map[string]string{\n\t\t\tcommon.Since: common.VersionSince0028,\n\t\t},\n\t}\n\n\tcmd.AddCommand(NewConfigPluginListCmd(opt),\n\t\tNewConfigPluginFetchCmd(opt),\n\t\tNewConfigPluginInstallCmd(opt),\n\t\tNewConfigPluginUninstallCmd(opt))\n\treturn\n}", "func NewWithConfig(config Config, opt ...session.Option) echo.MiddlewareFunc {\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultConfig.Skipper\n\t}\n\n\tmanageKey = config.ManageKey\n\tif manageKey == \"\" {\n\t\tmanageKey = DefaultConfig.ManageKey\n\t}\n\n\tstoreKey = config.StoreKey\n\tif storeKey == \"\" {\n\t\tstoreKey = DefaultConfig.StoreKey\n\t}\n\n\tmanage := session.NewManager(opt...)\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tc.Set(manageKey, manage)\n\t\t\tstore, err := manage.Start(nil, c.Response(), c.Request())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.Set(storeKey, store)\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func NewContext() *Context {\n\treturn &Context{\n\t\tAutoShell: true,\n\t\tForeground: true,\n\t\tBlock: true,\n\t\tDry: false,\n\t}\n}", "func (config *DirectClientConfig) getContext() (clientcmdapi.Context, error) {\n\tcontexts := config.config.Contexts\n\tcontextName, required := config.getContextName()\n\n\tmergedContext := clientcmdapi.NewContext()\n\tif configContext, exists := contexts[contextName]; exists {\n\t\tmergo.Merge(mergedContext, configContext, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.Context{}, fmt.Errorf(\"context %q does not exist\", contextName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedContext, config.overrides.Context, mergo.WithOverride)\n\t}\n\n\treturn *mergedContext, nil\n}", "func NewConfigureCmd(\n\tparent *kingpin.Application,\n\tparentOpts *options.AppOptions,\n\tcfg *config.Config,\n) {\n\to := &configOptions{AppOptions: parentOpts}\n\tcmd := parent.Command(\"configure\", \"Manage Beaker configuration settings\")\n\tcmd.Command(\"interactive\", \"Interactive configuration\").Default().Action(\n\t\tfunc(c *kingpin.ParseContext) error {\n\t\t\treturn config.InteractiveConfiguration()\n\t\t})\n\n\t// Attach subcommands.\n\tnewTestCmd(cmd, o)\n}", "func (c *Config) newGitRepoContext(repo *git.Repository) (*Context, error) {\n\tremote, err := repo.Remote(origin)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not generate context from git repository\")\n\t}\n\n\tgitRemoteURL := remote.Config().URLs[0]\n\n\trepoURL, err := parseGitURL(gitRemoteURL)\n\tif err != nil {\n\t\tlog.Infof(\"instance %s is not a valid URL: %v\", remote.String(), err)\n\t}\n\n\tlog.Debugf(\"found repo remote: %v\", repoURL)\n\n\tfor instName, instCfg := range c.Instances {\n\t\tif repoURL.Host == instCfg.url.Host {\n\t\t\tlog.Debugf(\"repo URL matches Instance URL %q, creating context with Group %v\", repoURL.Host, repoURL.Path)\n\t\t\treturn &Context{\n\t\t\t\tInstanceName: instName,\n\t\t\t\tNamespace: repoURL.Path,\n\t\t\t\tinstanceConfig: instCfg,\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn nil, errors.Errorf(\"no instance match found for git repository %q\", repoURL)\n}", "func NewSampleConfig(cfg config.Sampler) func(Pather) *cobra.Command {\n\treturn func(pather Pather) *cobra.Command {\n\t\tvar cmd = &cobra.Command{\n\t\t\tUse: \"config\",\n\t\t\tShort: \"Display sample configuration file\",\n\t\t\tExample: fmt.Sprintf(\" %[1]s config > cfg.toml\", pather.CommandPath()),\n\t\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\t\t(cfg).Sample(os.Stdout, nil, nil)\n\t\t\t},\n\t\t}\n\t\treturn cmd\n\t}\n}", "func NewConnectCmd(f factory.Factory) *cobra.Command {\n\tconnectCmd := &cobra.Command{\n\t\tUse: \"connect\",\n\t\tShort: \"Connect an external cluster to devspace cloud\",\n\t\tLong: `\n#######################################################\n################# devspace connect ####################\n#######################################################\n\t`,\n\t\tArgs: cobra.NoArgs,\n\t}\n\n\tconnectCmd.AddCommand(newClusterCmd(f))\n\n\treturn connectCmd\n}", "func CommandContext(ctx context.Context, name string, args ...string) *exec.Cmd {\n\tserver.wg.Wait()\n\targs = append([]string{name}, args...)\n\treturn exec.CommandContext(ctx, \"wine\", args...)\n}", "func NewSysContext(corinf informers.SharedInformerFactory) *SysContext {\n\tvar sclister corelister.SecretLister\n\tvar cmlister corelister.ConfigMapLister\n\tif corinf != nil {\n\t\tsclister = corinf.Core().V1().Secrets().Lister()\n\t\tcmlister = corinf.Core().V1().ConfigMaps().Lister()\n\t}\n\n\treturn &SysContext{\n\t\tsclister: sclister,\n\t\tcmlister: cmlister,\n\t\tunqualifiedRegistries: []string{\"docker.io\"},\n\t}\n}", "func NewCmd(streams genericclioptions.IOStreams) *cobra.Command {\n\to := NewOptions(streams)\n\n\tcmd := &cobra.Command{\n\t\tUse: \"aad login [flags]\",\n\t\tShort: \"login to azure active directory and populate kubeconfig with AAD tokens\",\n\t\tExample: fmt.Sprintf(cmdExample, \"kubectl\"),\n\t\tSilenceUsage: true,\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\t\t\tif err := o.Complete(c, args); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.Validate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := o.Run(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(&o.useServicePrincipal, \"service-principal\", o.useServicePrincipal,\n\t\tfmt.Sprintf(\"if true, it will use service principal to login using %s and %s envrionment variables\",\n\t\t\tenvServicePrincipalClientID, envServicePrincipalClientSecret))\n\tcmd.Flags().BoolVar(&o.useUserPrincipal, \"user-principal\", o.useUserPrincipal,\n\t\tfmt.Sprintf(\"if true, it will use user principal to login using %s and %s envrionment variables\",\n\t\t\tenvROPCUsername, envROPCPassword))\n\tcmd.Flags().BoolVar(&o.forceRefresh, \"force\", o.forceRefresh, \"if true, it will always login and disregard the access token in kubeconfig\")\n\to.configFlags.AddFlags(cmd.Flags())\n\n\treturn cmd\n}", "func newProcessContext(workdir string, stdin io.Reader, stdout, stderr io.Writer) *processContext {\n\treturn &processContext{\n\t\tworkdir: workdir,\n\t\tenv: os.Environ(),\n\t\tstdin: stdin,\n\t\tstdout: stdout,\n\t\tstderr: stderr,\n\t\toutlog: log.New(stdout, \"\", 0),\n\t\terrlog: log.New(stderr, \"gocdk: \", 0),\n\t}\n}", "func FromContext(ctx context.Context) *Config {\n\treturn ctx.Value(cfgKey{}).(*Config)\n}", "func FromContext(ctx context.Context) *Config {\n\treturn ctx.Value(cfgKey{}).(*Config)\n}", "func NewCmdGetVaultConfig(commonOpts *opts.CommonOptions) *cobra.Command {\n\toptions := &GetVaultConfigOptions{\n\t\tCommonOptions: commonOpts,\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"vault-config\",\n\t\tShort: \"Gets the configuration for using the Vault CLI\",\n\t\tLong: getVaultConfigLong,\n\t\tExample: getVaultConfigExample,\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\toptions.Cmd = c\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\thelper.CheckErr(err)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&options.Namespace, \"namespace\", \"n\", \"\", \"Namespace from where to get the Vault config\")\n\tcmd.Flags().StringVarP(&options.Name, \"name\", \"m\", \"\", \"Name of the Vault to get the config for\")\n\tcmd.Flags().StringVarP(&options.terminal, \"terminal\", \"t\", \"\", \"terminal type output override. Values: ['sh', 'cmd'].\")\n\treturn cmd\n}", "func Use(c context.Context) context.Context {\n\treturn UseWithAppID(c, \"dev~app\")\n}", "func NewCommand(ctx context.CLIContext) *cobra.Command {\n\tvar cmd = &cobra.Command{\n\t\tUse: ctx.Config.CommandName,\n\t\tLong: ctx.Config.Description,\n\t\tVersion: ctx.Config.Version,\n\t}\n\n\t// Setup flag\n\tverbosity := cmd.PersistentFlags().CountP(\"verbose\", \"v\", \"more verbose output (-vv... to further increase verbosity)\")\n\tlogLevel := cmd.PersistentFlags().String(\"log-level\", log.GetDefaultLevel(), \"set logs level: \"+strings.Join(log.LevelNames, \", \"))\n\n\t// Normally flags are parsed by cobra on Execute(), but we need to determine\n\t// logging level before executing command, so Parse() needs to be called here\n\t// manually. As far as I checked, this doesn't interfere with cobra parsing\n\t// rest of the flags later on.\n\tcmd.PersistentFlags().Parse(os.Args)\n\n\t// Set log level. In order to pass log level to installed subcommands we need\n\t// set env variable as well.\n\tlog.SetLevel(*logLevel)\n\tlog.IncreaseLevel(*verbosity)\n\n\tenvLogLevel, ok := os.LookupEnv(\"KLIO_LOG_LEVEL\")\n\tif ok {\n\t\tlog.SetLevel(envLogLevel)\n\t} else {\n\t\t_ = os.Setenv(\"KLIO_LOG_LEVEL\", log.GetLevel())\n\t}\n\n\t// Discover commands\n\tdepsMgr := dependency.NewManager(ctx)\n\tglobalCommands, err := depsMgr.GetInstalledCommands(dependency.GlobalScope)\n\tif err != nil {\n\t\tlog.Verbose(err)\n\t}\n\tprojectCommands, err := depsMgr.GetInstalledCommands(dependency.ProjectScope)\n\tif err != nil {\n\t\tlog.Verbose(err)\n\t}\n\n\t// Register builtin commands\n\tcmd.AddCommand(getCommand.NewCommand(ctx))\n\n\t// Register external commands\n\tfor _, dep := range projectCommands {\n\t\tloadExternalCommand(ctx, cmd, dep, false)\n\t}\n\n\t// Register global commands (installed under user's home directory)\n\tfor _, path := range globalCommands {\n\t\tloadExternalCommand(ctx, cmd, path, true)\n\t}\n\n\treturn cmd\n}", "func NewContext(fns ...SetContextFn) (ctx context.Context) {\n\tctx = context.TODO()\n\tctx = ApplyContext(ctx, fns...)\n\treturn\n}" ]
[ "0.74391395", "0.6349216", "0.624942", "0.6107694", "0.6100607", "0.6080159", "0.60459125", "0.60392904", "0.59372085", "0.58892083", "0.5855555", "0.58185875", "0.57851416", "0.57795674", "0.57705146", "0.5729567", "0.5684045", "0.5587479", "0.5549792", "0.55303764", "0.55268496", "0.54751414", "0.54510385", "0.5444919", "0.5413629", "0.53948045", "0.5392309", "0.53603", "0.5326446", "0.5308145", "0.5283284", "0.5224571", "0.5216774", "0.5208217", "0.51962405", "0.5186901", "0.5185118", "0.51834506", "0.51736444", "0.5166577", "0.5158862", "0.5153464", "0.51471025", "0.51345336", "0.5119335", "0.511545", "0.509839", "0.50927913", "0.5089496", "0.5078103", "0.50744754", "0.50718933", "0.50681543", "0.50638527", "0.5050181", "0.5032803", "0.5019061", "0.5012975", "0.5011842", "0.5009463", "0.49991158", "0.49949452", "0.49875027", "0.49826503", "0.49752912", "0.49741048", "0.49627715", "0.49567693", "0.49513614", "0.49463338", "0.49276105", "0.49155158", "0.490016", "0.48984605", "0.4886967", "0.48554853", "0.4853394", "0.4848479", "0.48471013", "0.4846576", "0.4845237", "0.48444325", "0.48293355", "0.4827961", "0.4824976", "0.48184642", "0.48168075", "0.48025605", "0.4800579", "0.4799838", "0.47973597", "0.4796041", "0.4792152", "0.47836798", "0.4781186", "0.4781186", "0.47810522", "0.47810447", "0.47801036", "0.47751933" ]
0.8202349
0
Validate validates this tweet
func (m *Tweet) Validate(formats strfmt.Registry) error { var res []error if err := m.validateCreatedAt(formats); err != nil { res = append(res, err) } if err := m.validateFullText(formats); err != nil { res = append(res, err) } if err := m.validateID(formats); err != nil { res = append(res, err) } if err := m.validateTwitterID(formats); err != nil { res = append(res, err) } if err := m.validateTwitterUserID(formats); err != nil { res = append(res, err) } if err := m.validateTwitterUsername(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mt *Bottle) Validate() (err error) {\n\tif mt.ID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"id\"))\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"name\"))\n\t}\n\n\tif utf8.RuneCountInString(mt.Name) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.name`, mt.Name, utf8.RuneCountInString(mt.Name), 1, true))\n\t}\n\tif mt.Rating < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.rating`, mt.Rating, 1, true))\n\t}\n\tif mt.Rating > 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.rating`, mt.Rating, 5, false))\n\t}\n\tif mt.Vintage < 1900 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.vintage`, mt.Vintage, 1900, true))\n\t}\n\treturn\n}", "func (mt *UserTiny) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"href\"))\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"name\"))\n\t}\n\treturn\n}", "func (mt *Post) Validate() (err error) {\n\n\tif mt.URLName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"url_name\"))\n\t}\n\tif mt.Title == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"title\"))\n\t}\n\tif mt.Contents == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"contents\"))\n\t}\n\tif mt.Status == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"status\"))\n\t}\n\tif !(mt.Status == \"draft\" || mt.Status == \"published\") {\n\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.status`, mt.Status, []interface{}{\"draft\", \"published\"}))\n\t}\n\treturn\n}", "func (t *Trip) Validate() bool {\n\tif t.Title != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s TextBlockObject) Validate() error {\n\tif s.Type != \"plain_text\" && s.Type != \"mrkdwn\" {\n\t\treturn errors.New(\"type must be either of plain_text or mrkdwn\")\n\t}\n\n\t// https://github.com/slack-go/slack/issues/881\n\tif s.Type == \"mrkdwn\" && s.Emoji {\n\t\treturn errors.New(\"emoji cannot be true in mrkdown\")\n\t}\n\n\treturn nil\n}", "func (t *Term) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: t.Name, Name: \"Name\"},\n\t\t&validators.IntIsPresent{Field: t.Dmal, Name: \"Dmal\"},\n\t), nil\n}", "func (t *SecurityTxt) Validate() error {\n\treturn nil\n}", "func (t *Thing) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: t.Name, Name: \"Name\"},\n\t\t&validators.StringIsPresent{Field: t.Notes, Name: \"Notes\"},\n\t\t&validators.StringIsPresent{Field: t.Secret, Name: \"Secret\"},\n\t\t&validators.StringIsPresent{Field: t.Status, Name: \"Status\"},\n\t), nil\n}", "func (rft *RemittanceFreeText) Validate() error {\n\tif rft.tag != TagRemittanceFreeText {\n\t\treturn fieldError(\"tag\", ErrValidTagForType, rft.tag)\n\t}\n\tif err := rft.isAlphanumeric(rft.LineOne); err != nil {\n\t\treturn fieldError(\"LineOne\", err, rft.LineOne)\n\t}\n\tif err := rft.isAlphanumeric(rft.LineTwo); err != nil {\n\t\treturn fieldError(\"LineTwo\", err, rft.LineTwo)\n\t}\n\tif err := rft.isAlphanumeric(rft.LineThree); err != nil {\n\t\treturn fieldError(\"LineThree\", err, rft.LineThree)\n\t}\n\treturn nil\n}", "func (mt *Bottle) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"href\", err)\n\t}\n\tif mt.Name == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"name\", err)\n\t}\n\tif mt.Vineyard == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"vineyard\", err)\n\t}\n\tif mt.Varietal == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"varietal\", err)\n\t}\n\n\tif mt.Color == \"\" {\n\t\terr = goa.MissingAttributeError(`response`, \"color\", err)\n\t}\n\n\tif mt.Account.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.Account.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.account.created_at`, *mt.Account.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif mt.Account.CreatedBy != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatEmail, *mt.Account.CreatedBy); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.account.created_by`, *mt.Account.CreatedBy, goa.FormatEmail, err2, err)\n\t\t}\n\t}\n\tif !(mt.Color == \"red\" || mt.Color == \"white\" || mt.Color == \"rose\" || mt.Color == \"yellow\" || mt.Color == \"sparkling\") {\n\t\terr = goa.InvalidEnumValueError(`response.color`, mt.Color, []interface{}{\"red\", \"white\", \"rose\", \"yellow\", \"sparkling\"}, err)\n\t}\n\tif mt.Country != nil {\n\t\tif len(*mt.Country) < 2 {\n\t\t\terr = goa.InvalidLengthError(`response.country`, *mt.Country, len(*mt.Country), 2, true, err)\n\t\t}\n\t}\n\tif mt.CreatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.CreatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.created_at`, *mt.CreatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif len(mt.Name) < 2 {\n\t\terr = goa.InvalidLengthError(`response.name`, mt.Name, len(mt.Name), 2, true, err)\n\t}\n\tif mt.Rating != nil {\n\t\tif *mt.Rating < 1 {\n\t\t\terr = goa.InvalidRangeError(`response.rating`, *mt.Rating, 1, true, err)\n\t\t}\n\t}\n\tif mt.Rating != nil {\n\t\tif *mt.Rating > 5 {\n\t\t\terr = goa.InvalidRangeError(`response.rating`, *mt.Rating, 5, false, err)\n\t\t}\n\t}\n\tif mt.Review != nil {\n\t\tif len(*mt.Review) < 3 {\n\t\t\terr = goa.InvalidLengthError(`response.review`, *mt.Review, len(*mt.Review), 3, true, err)\n\t\t}\n\t}\n\tif mt.Review != nil {\n\t\tif len(*mt.Review) > 300 {\n\t\t\terr = goa.InvalidLengthError(`response.review`, *mt.Review, len(*mt.Review), 300, false, err)\n\t\t}\n\t}\n\tif mt.Sweetness != nil {\n\t\tif *mt.Sweetness < 1 {\n\t\t\terr = goa.InvalidRangeError(`response.sweetness`, *mt.Sweetness, 1, true, err)\n\t\t}\n\t}\n\tif mt.Sweetness != nil {\n\t\tif *mt.Sweetness > 5 {\n\t\t\terr = goa.InvalidRangeError(`response.sweetness`, *mt.Sweetness, 5, false, err)\n\t\t}\n\t}\n\tif mt.UpdatedAt != nil {\n\t\tif err2 := goa.ValidateFormat(goa.FormatDateTime, *mt.UpdatedAt); err2 != nil {\n\t\t\terr = goa.InvalidFormatError(`response.updated_at`, *mt.UpdatedAt, goa.FormatDateTime, err2, err)\n\t\t}\n\t}\n\tif len(mt.Varietal) < 4 {\n\t\terr = goa.InvalidLengthError(`response.varietal`, mt.Varietal, len(mt.Varietal), 4, true, err)\n\t}\n\tif len(mt.Vineyard) < 2 {\n\t\terr = goa.InvalidLengthError(`response.vineyard`, mt.Vineyard, len(mt.Vineyard), 2, true, err)\n\t}\n\tif mt.Vintage < 1900 {\n\t\terr = goa.InvalidRangeError(`response.vintage`, mt.Vintage, 1900, true, err)\n\t}\n\tif mt.Vintage > 2020 {\n\t\terr = goa.InvalidRangeError(`response.vintage`, mt.Vintage, 2020, false, err)\n\t}\n\treturn\n}", "func (tg Timing) validate() error {\n\tvar err error\n\tif tg.length != len(tg.ts) {\n\t\terr = errors.New(\"ts is wrong length\")\n\t}\n\tif tg.length != len(tg.te) {\n\t\terr = errors.New(\"te is wrong length\")\n\t}\n\tif tg.length != len(tg.Td) {\n\t\terr = errors.New(\"Td is wrong length\")\n\t}\n\tfor i, _ := range tg.te {\n\t\tif tg.te[i].Sub(tg.ts[i]) < 0 {\n\t\t\terr = errors.New(\"time travel detected\")\n\t\t}\n\t}\n\treturn err\n}", "func (r *Reddit) Validate(username string) (violations candidate.Violations) {\n\tlength := utf8.RuneCountInString(username)\n\n\tif length > maxLength {\n\t\tviolations = append(violations, candidate.NameTooLong)\n\t}\n\n\tif length < minLength {\n\t\tviolations = append(violations, candidate.NameTooShort)\n\t}\n\n\tif !legalRunesRegexp.MatchString(username) {\n\t\tviolations = append(violations, candidate.NameContainsIllegalCharacters)\n\t}\n\n\treturn violations\n}", "func (t Topic) Validate() error {\n\treturn validateResource(string(t), \"topics\")\n}", "func ValidatePost(request AddStoryRequest) error {\n\ts := strings.Split(request.Word, \" \")\n\tif len(s) > 1 {\n\t\treturn errors.New(utils.MultipleWordError)\n\t}\n\treturn nil\n}", "func (mt *Message) Validate() (err error) {\n\tif mt.GoogleUserID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"googleUserID\"))\n\t}\n\tif mt.Body == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"body\"))\n\t}\n\n\tif utf8.RuneCountInString(mt.Body) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.body`, mt.Body, utf8.RuneCountInString(mt.Body), 1, true))\n\t}\n\tif utf8.RuneCountInString(mt.Body) > 400 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.body`, mt.Body, utf8.RuneCountInString(mt.Body), 400, false))\n\t}\n\treturn\n}", "func (a AfterRule) Validate(t interface{}) error {\n\tend, ok := t.(*timestamppb.Timestamp)\n\tif !ok {\n\t\treturn fmt.Errorf(\"end is not a timestamp\")\n\t}\n\n\tif a.Timestamp.AsTime().After(end.AsTime()) {\n\t\treturn fmt.Errorf(\"start timestamp must be before end\")\n\t}\n\n\treturn nil\n}", "func (a Topic) Validate() error {\n\tif strings.TrimSpace(string(a)) == \"\" {\n\t\treturn ErrTopicMustNotBeBlank\n\t}\n\treturn nil\n}", "func (mt *Article) Validate() (err error) {\n\n\tif mt.Text == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"text\"))\n\t}\n\n\treturn\n}", "func (t *Token) validate(nbfCheck bool) (err error) {\n\tvar zu = uuid.UUID{}\n\tvar ve = &ValidationError{}\n\tvar now = Timestamp(time.Now().Unix())\n\n\tif bytes.Equal(zu[:], t.Id[:]) {\n\t\tve.append(\"Token.Id is invalid (zero-UUID)\")\n\t}\n\n\tif bytes.Equal(zu[:], t.Subject[:]) {\n\t\tve.append(\"Token.Subject is invalid (zero-UUID)\")\n\t}\n\n\tif 0 == t.Issued {\n\t\tve.append(\"Token.Issued is invalid (zero-Timestamp)\")\n\t} else if t.Issued > now {\n\t\tve.append(\"Token.Issued is > time.Now()\")\n\t}\n\n\tif t.Expires != 0 && t.Expires < (now+5) {\n\t\tve.append(fmt.Sprintf(\n\t\t\t\"Token.Expires is < time.Now(); expired %v\",\n\t\t\tt.Expires.Time().String()))\n\t\tve.exp = true\n\t}\n\n\tif nbfCheck &&\n\t\tt.NotBefore != 0 &&\n\t\tint64(t.NotBefore) > (time.Now().Unix()-5) {\n\t\tve.append(fmt.Sprintf(\n\t\t\t\"Token.NotBefore is < time.Now(); not before %v\",\n\t\t\tt.Expires.Time().String()))\n\t\tve.nbf = true\n\t}\n\n\tif 0 != len(ve.errstrs) || ve.exp || ve.nbf {\n\t\terr = ve\n\t}\n\n\treturn\n}", "func (ut *todoPayload) Validate() (err error) {\n\tif ut.Title != nil {\n\t\tif utf8.RuneCountInString(*ut.Title) < 8 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.title`, *ut.Title, utf8.RuneCountInString(*ut.Title), 8, true))\n\t\t}\n\t}\n\treturn\n}", "func (ut *TodoPayload) Validate() (err error) {\n\tif ut.Title != nil {\n\t\tif utf8.RuneCountInString(*ut.Title) < 8 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.title`, *ut.Title, utf8.RuneCountInString(*ut.Title), 8, true))\n\t\t}\n\t}\n\treturn\n}", "func (t UnixTime) Validate() error {\n\tif t < minUnixTime {\n\t\treturn errors.Wrap(errors.ErrState, \"time must be an A.D. value\")\n\t}\n\tif t > maxUnixTime {\n\t\treturn errors.Wrap(errors.ErrState, \"time must be an before year 10000\")\n\t}\n\treturn nil\n}", "func (t *Time) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (this RedditFeed) Validate() (err error) {\n\tif this.Name == \"\" {\n\t\treturn fmt.Errorf(\"Empty feed name\")\n\t}\n\tif !regexp.MustCompile(\"^[-_a-zA-Z0-9]+$\").MatchString(this.Name) {\n\t\treturn fmt.Errorf(\"Invalid feed name, must contain only chars from A-Z, a-z, 0-9, '_', & '-'\")\n\t}\n\tif this.Description == \"\" {\n\t\treturn fmt.Errorf(\"Empty feed description\")\n\t}\n\tif !(this.Media == MEDIA_TYPE_IMAGE || this.Media == MEDIA_TYPE_TEXT) {\n\t\treturn fmt.Errorf(\n\t\t\t\"Invalid media type: '%s', must be one of '%s' or '%s'\",\n\t\t\tthis.Media,\n\t\t\tMEDIA_TYPE_IMAGE,\n\t\t\tMEDIA_TYPE_TEXT,\n\t\t)\n\t}\n\treturn nil\n}", "func (post *Post) Validate() map[string]string {\n\n\t// if user.Name == \"\" && len(user.Name) < 5 {\n\t// \treturn err(\"The Name you entered was too short\")\n\t// }\n\n\treturn map[string]string{\"Message\": \"\", \"IsValid\": \"1\"}\n}", "func (t *Task) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: t.Description, Name: \"Description\"},\n\t\t&validators.StringIsPresent{Field: t.Status, Name: \"Status\"},\n\t\t&validators.StringIsPresent{Field: t.RequesterName, Name: \"RequesterName\"},\n\t\t&validators.StringIsPresent{Field: t.ExecutorName, Name: \"ExecutorName\"},\n\t), nil\n}", "func SaveTweet(w http.ResponseWriter, r *http.Request) {\n\tvar message models.Tweet\n\terr := json.NewDecoder(r.Body).Decode(&message)\n\n\t/* tweet */\n\tregister := models.SaveTweet{\n\t\tUserID: IDUser,\n\t\tMessage: message.Message,\n\t\tDate: time.Now(),\n\t}\n\n\tvar status bool\n\t_, status, err = db.InsertTweet(register)\n\tif err != nil {\n\t\thttp.Error(w, \"An error occurred while inserting the tweet, try again \"+err.Error(), 400)\n\t\treturn\n\t}\n\n\tif status == false {\n\t\thttp.Error(w, \"The tweet isn't registered\", 400)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (t *Token) Validate() errstack.Builder {\n\tvar errb = errstack.NewBuilder()\n\tt.CreatedAt = time.Now().UTC()\n\tif len(t.ID) < 3 {\n\t\terrb.Put(\"id\", \"must be at least 3-characters long\")\n\t}\n\tif t.MaxTotalContrib.Int != nil && t.MaxTotalContrib.Cmp(zero) < 0 {\n\t\terrb.Put(\"maxTotalContrib\", \"can't be negative\")\n\t}\n\treturn errb\n}", "func (pt MDTurbo) Validate() bool {\n\tif pt.Magic != 52426 {\n\t\treturn false\n\t}\n\tif pt.Partitions1[0].Start != 256 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (t AuthToken) Validate() error {\n\t// Holds names of empty fields\n\tempty := []string{}\n\n\t// Check user id\n\tif len(t.UserID) == 0 {\n\t\tempty = append(empty, \"UserID\")\n\t}\n\n\t// Check device id\n\tif len(t.DeviceID) == 0 {\n\t\tempty = append(empty, \"DeviceID\")\n\t}\n\n\t// Check if any empty fields\n\tif len(empty) != 0 {\n\t\treturn fmt.Errorf(\"the following fields were empty: %s\",\n\t\t\tStrings.join(empty))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (time CueTime) Validate() bool {\n\tret := true\n\tif ret == true && time.up != (Time{}) {\n\t\tret = time.up.Validate()\n\t}\n\n\tif ret == true && time.down != (Time{}) {\n\t\tret = time.down.Validate()\n\t}\n\n\tif ret == true && time.delay != (Delay{}) {\n\t\tret = time.delay.Validate()\n\t}\n\n\tif ret == true && time.follow != (Follow{}) {\n\t\tret = time.follow.Validate()\n\t}\n\n\tif ret != true {\n\t\tlog.Println(\"Failed to validate time '\" + time.value + \"'\")\n\t}\n\treturn ret\n}", "func Valid(text string) bool {\n\treturn true\n}", "func (this Subreddit) Validate() (err error) {\n\tif this.Name == \"\" {\n\t\treturn fmt.Errorf(\"Empty subreddit name\")\n\t}\n\tif this.Percentile < 0.0 || this.Percentile > 100.0 {\n\t\treturn fmt.Errorf(\"Percentile out of 0-100 range. : %f\", this.Percentile)\n\t}\n\tif this.MaxDailyPosts < 0 {\n\t\treturn fmt.Errorf(\"MaxDailyPosts must be a +ve integer. : %d\", this.MaxDailyPosts)\n\t}\n\treturn nil\n}", "func (t *Team) Validate() error {\n\treturn validator.New().Struct(t)\n}", "func (t UnixTime) Validate() error {\n\tif t < minUnixTime {\n\t\treturn errors.Wrap(errors.ErrInvalidState, \"time must be an A.D. value\")\n\t}\n\tif t > maxUnixTime {\n\t\treturn errors.Wrap(errors.ErrInvalidState, \"time must be an before year 10000\")\n\t}\n\treturn nil\n}", "func (m Name) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := validate.Pattern(\"\", \"body\", string(m), `^[A-Za-z0-1.\\-_]*$`); 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}", "func (m *TicketPosts) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validatePosts(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}", "func (t *Trader) Validate(action Action) error {\n\treturn nil\n}", "func (mt *RankdbBackupStatusTiny) Validate() (err error) {\n\n\tif mt.URI == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"uri\"))\n\t}\n\n\treturn\n}", "func (m *Word) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Id\n\n\tif v, ok := interface{}(m.GetCreatedAt()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn WordValidationError{\n\t\t\t\tfield: \"CreatedAt\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetUpdatedAt()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn WordValidationError{\n\t\t\t\tfield: \"UpdatedAt\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\tif v, ok := interface{}(m.GetDeletedAt()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn WordValidationError{\n\t\t\t\tfield: \"DeletedAt\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\t// no validation rules for Content\n\n\t// no validation rules for AudioSrc\n\n\t// no validation rules for Skill_Id\n\n\tif v, ok := interface{}(m.GetSkill()).(interface{ Validate() error }); ok {\n\t\tif err := v.Validate(); err != nil {\n\t\t\treturn WordValidationError{\n\t\t\t\tfield: \"Skill\",\n\t\t\t\treason: \"embedded message failed validation\",\n\t\t\t\tcause: err,\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (ut *TeamPayload) Validate() (err error) {\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\tif ut.SportID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"sportId\"))\n\t}\n\tif ut.HomeTownID == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"homeTownId\"))\n\t}\n\tif ut.ShortName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"shortName\"))\n\t}\n\treturn\n}", "func (t *Tag) Validate() error {\n\t// TODO consider returning a list of errors, one per invalid frame,\n\t// specifying the reason\n\n\tpanic(\"not implemented\") // FIXME\n\n\tif t.HasFrame(\"TSRC\") && len(t.GetTextFrame(\"TSRC\")) != 12 {\n\t\t// TODO invalid TSRC frame\n\t}\n\n\treturn nil\n}", "func (o *NewThreadBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateBaseReq(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}", "func (body *CreateResponseBody) Validate() (err error) {\n\tif body.ID == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"id\", \"body\"))\n\t}\n\tif body.Color == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"color\", \"body\"))\n\t}\n\tif body.Cron == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingFieldError(\"cron\", \"body\"))\n\t}\n\tif body.Name != nil {\n\t\tif utf8.RuneCountInString(*body.Name) > 100 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(\"body.name\", *body.Name, utf8.RuneCountInString(*body.Name), 100, false))\n\t\t}\n\t}\n\tif body.Color != nil {\n\t\tif !(*body.Color == \"red\" || *body.Color == \"yellow\" || *body.Color == \"green\" || *body.Color == \"off\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(\"body.color\", *body.Color, []interface{}{\"red\", \"yellow\", \"green\", \"off\"}))\n\t\t}\n\t}\n\treturn\n}", "func (mt *Status) Validate() (err error) {\n\tif mt.Commit == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"commit\"))\n\t}\n\tif mt.BuildTime == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"buildTime\"))\n\t}\n\tif mt.StartTime == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"startTime\"))\n\t}\n\tif mt.DatabaseStatus == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"databaseStatus\"))\n\t}\n\tif mt.ConfigurationStatus == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"configurationStatus\"))\n\t}\n\treturn\n}", "func (m *OAuthCallbackData) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (r UsernameTakenRequest) Validate() error {\n\treturn validation.ValidateStruct(&r,\n\t\tvalidUsername(&r.Username),\n\t)\n}", "func (m *Nrt) Validate() error {\n\treturn m.validate(false)\n}", "func (c *HTLCTimeoutAccept) Validate() error {\n\t// We're good!\n\treturn nil\n}", "func (time Time) Validate() bool {\n\tret := true\n\tif ret == true && time.hours != (Hours{}) {\n\t\tret = time.hours.Validate()\n\t}\n\n\tif ret == true && time.minutes != (Minutes{}) {\n\t\tret = time.minutes.Validate()\n\t}\n\n\tif ret == true && time.seconds != (Seconds{}) {\n\t\tret = time.seconds.Validate()\n\t}\n\n\tif ret == true && time.delay != (Delay{}) {\n\t\tret = time.delay.Validate()\n\t}\n\n\tif ret != true {\n\t\tlog.Println(\"Failed to validate time '\" + time.value + \"'\")\n\t}\n\treturn ret\n}", "func (t *Token) Validate() error {\n\tif t.JWT == nil {\n\t\treturn ErrEmptyToken\n\t}\n\tif !t.new && !t.JWT.Valid {\n\t\treturn ErrTokenInvalid\n\t}\n\n\treturn nil\n}", "func ValidateStatusText(text string) bool {\n\targs := strings.Split(text, \" \")\n\tif len(args) != 1 {\n\t\treturn false\n\t}\n\tid, err := strconv.Atoi(args[0])\n\tif err != nil || id < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (wc *WordCreate) check() error {\n\tif _, ok := wc.mutation.CreateTime(); !ok {\n\t\treturn &ValidationError{Name: \"create_time\", err: errors.New(\"ent: missing required field \\\"create_time\\\"\")}\n\t}\n\tif _, ok := wc.mutation.UpdateTime(); !ok {\n\t\treturn &ValidationError{Name: \"update_time\", err: errors.New(\"ent: missing required field \\\"update_time\\\"\")}\n\t}\n\tif _, ok := wc.mutation.Lang1(); !ok {\n\t\treturn &ValidationError{Name: \"lang1\", err: errors.New(\"ent: missing required field \\\"lang1\\\"\")}\n\t}\n\tif v, ok := wc.mutation.Lang1(); ok {\n\t\tif err := word.Lang1Validator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"lang1\", err: fmt.Errorf(\"ent: validator failed for field \\\"lang1\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := wc.mutation.Lang2(); !ok {\n\t\treturn &ValidationError{Name: \"lang2\", err: errors.New(\"ent: missing required field \\\"lang2\\\"\")}\n\t}\n\tif v, ok := wc.mutation.Lang2(); ok {\n\t\tif err := word.Lang2Validator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"lang2\", err: fmt.Errorf(\"ent: validator failed for field \\\"lang2\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := wc.mutation.Word1(); !ok {\n\t\treturn &ValidationError{Name: \"word1\", err: errors.New(\"ent: missing required field \\\"word1\\\"\")}\n\t}\n\tif v, ok := wc.mutation.Word1(); ok {\n\t\tif err := word.Word1Validator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"word1\", err: fmt.Errorf(\"ent: validator failed for field \\\"word1\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := wc.mutation.Word2(); !ok {\n\t\treturn &ValidationError{Name: \"word2\", err: errors.New(\"ent: missing required field \\\"word2\\\"\")}\n\t}\n\tif v, ok := wc.mutation.Word2(); ok {\n\t\tif err := word.Word2Validator(v); err != nil {\n\t\t\treturn &ValidationError{Name: \"word2\", err: fmt.Errorf(\"ent: validator failed for field \\\"word2\\\": %w\", err)}\n\t\t}\n\t}\n\treturn nil\n}", "func (m *SubnetPost) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateMtu(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}", "func (f *FileUpload) Validate() error {\n\tif !filenameRe.MatchString(f.Name) {\n\t\treturn fmt.Errorf(\"bad filename\")\n\t}\n\tif !guidRe.MatchString(f.GUID) {\n\t\treturn fmt.Errorf(\"bad guid\")\n\t}\n\tif !eventHashRe.MatchString(f.EventHash) {\n\t\treturn fmt.Errorf(\"bad event hash\")\n\t}\n\treturn nil\n}", "func IsValidUsername(s string) bool {\n\tif s == \"\" {\n\t\treturn false\n\t}\n\n\t// match twitter names like @name_123\n\tr, err := regexp.Compile(`^[@](\\w){1,15}$`)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn r.MatchString(s)\n}", "func (gist *Gist) Validate() bool {\n\tgist.Errors = make(map[string]string)\n\n\tif gist.Title == \"\" {\n\t\tgist.Errors[\"Title\"] = \"You must provide a title.\"\n\t}\n\n\tif gist.Content == \"\" {\n\t\tgist.Errors[\"Content\"] = \"You must provide content.\"\n\t}\n\n\treturn len(gist.Errors) == 0\n}", "func (mt *Rating) Validate() (err error) {\n\n\tif mt.MovieID < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.movieId`, mt.MovieID, 1, true))\n\t}\n\tif mt.Rating < 0.500000 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.rating`, mt.Rating, 0.500000, true))\n\t}\n\tif mt.Rating > 5.000000 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.rating`, mt.Rating, 5.000000, false))\n\t}\n\tif mt.UserID < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.userId`, mt.UserID, 1, true))\n\t}\n\treturn\n}", "func (o *PostcommentsBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (h Howout) Valid() error {\n\tswitch h {\n\tcase Bowled, Catch, Runout, Notout, Didnotbat, Stumped:\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Invalid howout, it has to be one of [b,c,ro,no,dnb,st] \")\n}", "func (a *LiveTwitterAPI) PostTweet(message string) (*Tweet, error) {\n\treq, err := a.newAuthorizedRequest(\"POST\", \"https://api.twitter.com/1.1/statuses/update.json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Printf(\"Posting tweet: %v\\n\", message)\n\n\tquery := req.URL.Query()\n\tquery.Add(\"status\", message)\n\n\tvar tweet *liveTweet\n\terr = a.encodeAndExecuteRequest(req, query, &tweet)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcreatedAt, err := parseTwitterTime(tweet.CreatedAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Tweet{\n\t\tCreatedAt: createdAt,\n\t\tID: tweet.ID,\n\t\tMessage: tweet.Text,\n\t}, nil\n}", "func (t *TrafficControl) Validate() error {\n\tif t.Share < 0 || t.Share > 100 {\n\t\treturn errorf(ErrInvalidShare, \"must be between 0 and 100\")\n\t}\n\n\treturn nil\n}", "func (mt *ComJossemargtSaoDraft) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"href\"))\n\t}\n\tif ok := goa.ValidatePattern(`[_a-zA-Z0-9\\-]+`, mt.ContestSlug); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.contestSlug`, mt.ContestSlug, `[_a-zA-Z0-9\\-]+`))\n\t}\n\tif ok := goa.ValidatePattern(`[_a-zA-Z0-9\\-]+`, mt.TaskSlug); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.taskSlug`, mt.TaskSlug, `[_a-zA-Z0-9\\-]+`))\n\t}\n\treturn\n}", "func (mt *ComJossemargtSaoDraft) Validate() (err error) {\n\n\tif mt.Href == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"href\"))\n\t}\n\tif ok := goa.ValidatePattern(`[_a-zA-Z0-9\\-]+`, mt.ContestSlug); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.contestSlug`, mt.ContestSlug, `[_a-zA-Z0-9\\-]+`))\n\t}\n\tif ok := goa.ValidatePattern(`[_a-zA-Z0-9\\-]+`, mt.TaskSlug); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.taskSlug`, mt.TaskSlug, `[_a-zA-Z0-9\\-]+`))\n\t}\n\treturn\n}", "func (delay Delay) Validate() bool {\n\tret := true\n\n\ttime := &Time{}\n\ttime.SetValue(delay.value)\n\tret = time.Validate()\n\n\tif ret != true {\n\t\tlog.Println(\"Failed to validate delay '\" + delay.value + \"'\")\n\t}\n\n\treturn ret\n}", "func (m *Upstream_Timeout) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\tif m.GetConnect() <= 0 {\n\t\treturn Upstream_TimeoutValidationError{\n\t\t\tfield: \"Connect\",\n\t\t\treason: \"value must be greater than 0\",\n\t\t}\n\t}\n\n\tif m.GetSend() <= 0 {\n\t\treturn Upstream_TimeoutValidationError{\n\t\t\tfield: \"Send\",\n\t\t\treason: \"value must be greater than 0\",\n\t\t}\n\t}\n\n\tif m.GetRead() <= 0 {\n\t\treturn Upstream_TimeoutValidationError{\n\t\t\tfield: \"Read\",\n\t\t\treason: \"value must be greater than 0\",\n\t\t}\n\t}\n\n\treturn nil\n}", "func validatePost(post *pb.Post) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch x := r.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(x)\n\t\t\tcase error:\n\t\t\t\terr = x\n\t\t\tdefault:\n\t\t\t\terr = ErrPostUnknownValidationPanic\n\t\t\t}\n\t\t}\n\t}()\n\n\t// Slug\n\tif post.Slug == \"\" {\n\t\treturn ErrPostSlugNotEmpty\n\t}\n\tif len(post.Slug) > SentenceMaxCharacters {\n\t\treturn ErrPostSlugTooLong\n\t}\n\tif strings.Contains(post.Slug, \" \") {\n\t\treturn ErrPostSlugContainsSpaces\n\t}\n\tif strings.Contains(post.Slug, \"/\") {\n\t\treturn ErrPostSlugContainsSlashes\n\t}\n\n\t// Type\n\tif _, ok := pb.Post_PostType_value[post.PostType.String()]; !ok {\n\t\treturn ErrPostInvalidType\n\t}\n\n\t// Status\n\tif len(post.Status) > PostStatusMaxCharacters {\n\t\treturn ErrPostStatusTooLong\n\t}\n\n\t// Long Form\n\tif len(post.LongForm) > PostLongFormMaxCharacters {\n\t\treturn ErrPostBodyTooLong\n\t}\n\n\t// Tags\n\tif len(post.Tags) > PostMaximumTotalTags {\n\t\treturn ErrPostTagsTooMany\n\t}\n\tfor _, tag := range post.Tags {\n\t\tif tag == \"\" {\n\t\t\treturn ErrPostTagsEmpty\n\t\t}\n\t\tif len(tag) > PostTagsMaxCharacters {\n\t\t\treturn ErrPostTagTooLong\n\t\t}\n\t}\n\n\t// Channels\n\tif len(post.Channels) > PostMaximumTotalChannels {\n\t\treturn ErrPostChannelsTooMany\n\t}\n\tfor _, channel := range post.Channels {\n\t\tif len(channel) > PostChannelsMaxCharacters {\n\t\t\treturn ErrPostChannelTooLong\n\t\t}\n\t}\n\n\t// Reference\n\tif post.PostType == pb.Post_COMMENT || post.PostType == pb.Post_REPOST {\n\t\tif post.Reference == \"\" {\n\t\t\treturn ErrPostReferenceEmpty\n\t\t}\n\t\tif len(post.Reference) > PostReferenceMaxCharacters {\n\t\t\treturn ErrPostReferenceTooLong\n\t\t}\n\t\tif strings.Contains(post.Reference, \" \") {\n\t\t\treturn ErrPostReferenceContainsSpaces\n\t\t}\n\t}\n\n\t// Images\n\tif len(post.Images) > MaxListItems {\n\t\treturn ErrPostImagesTooMany\n\t}\n\tfor _, img := range post.Images {\n\t\t_, err := cid.Decode(img.Tiny)\n\t\tif err != nil {\n\t\t\treturn ErrPostImageTinyFormatInvalid\n\t\t}\n\t\t_, err = cid.Decode(img.Small)\n\t\tif err != nil {\n\t\t\treturn ErrPostImageSmallFormatInvalid\n\t\t}\n\t\t_, err = cid.Decode(img.Medium)\n\t\tif err != nil {\n\t\t\treturn ErrPostImageMediumFormatInvalid\n\t\t}\n\t\t_, err = cid.Decode(img.Large)\n\t\tif err != nil {\n\t\t\treturn ErrPostImageLargeFormatInvalid\n\t\t}\n\t\t_, err = cid.Decode(img.Original)\n\t\tif err != nil {\n\t\t\treturn ErrPostImageOriginalFormatInvalid\n\t\t}\n\t\tif img.Filename == \"\" {\n\t\t\treturn ErrPostImageFilenameNil\n\t\t}\n\t\tif len(img.Filename) > FilenameMaxCharacters {\n\t\t\treturn ErrPostImageFilenameTooLong\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *PassResetTemp) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateJwt(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validatePasswordNew(formats); err != nil {\n\t\t// prop\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}", "func (c *Chat) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}", "func (u *User) Validate() error {\n\t// check name first: must have no special character\n\tmatched, _ := regexp.Match(\"^[A-Za-z0-9\\\\s]+$\", []byte(u.Name))\n\tif !matched {\n\t\treturn errors.New(\"Nama hanya boleh mengandung karakter alfanumerik\")\n\t}\n\n\t// check phone\n\treturn nil\n}", "func (o *options) Validate() error {\n\tif len(o.tmKubeconfigPath) == 0 {\n\t\treturn errors.New(\"tm-kubeconfig-path is required\")\n\t}\n\tif len(o.testrunNamePrefix) == 0 {\n\t\treturn errors.New(\"testrun-prefix is required\")\n\t}\n\tif len(o.testrunPath) == 0 {\n\t\treturn errors.New(\"file is required\")\n\t}\n\treturn nil\n}", "func (swr *SearchWordsRequest) Validate(r *http.Request) (bool, *SearchWordsRespnse) {\n\n\tsearchWordsRespnse := new(SearchWordsRespnse)\n\n\t// Check if body is empty, because we expect some input\n\tif r.Body == nil {\n\n\t\tsearchWordsRespnse.Code = status.EmptyBody\n\t\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.EmptyBody, Message: status.Text(status.EmptyBody)})\n\t\treturn false, searchWordsRespnse\n\t}\n\n\t// Decode request\n\terr := json.NewDecoder(r.Body).Decode(&swr)\n\n\tdefer r.Body.Close()\n\n\tif err != nil {\n\t\tsearchWordsRespnse.Code = status.IncorrectBodyFormat\n\t\tsearchWordsRespnse.Errors = append(searchWordsRespnse.Errors, Error{Code: status.IncorrectBodyFormat, Message: status.Text(status.IncorrectBodyFormat)})\n\t\treturn false, searchWordsRespnse\n\t}\n\n\treturn true, searchWordsRespnse\n}", "func (m TransferStarted) Validate() error {\n\tif m.TransactionID == \"\" {\n\t\treturn errors.New(\"TransferStarted must not have an empty transaction ID\")\n\t}\n\tif m.FromAccountID == \"\" {\n\t\treturn errors.New(\"TransferStarted must not have an empty 'from' account ID\")\n\t}\n\tif m.ToAccountID == \"\" {\n\t\treturn errors.New(\"TransferStarted must not have an empty 'to' account ID\")\n\t}\n\tif m.FromAccountID == m.ToAccountID {\n\t\treturn errors.New(\"TransferStarted from account ID and to account ID must be different\")\n\t}\n\tif m.Amount < 1 {\n\t\treturn errors.New(\"TransferStarted must have a positive amount\")\n\t}\n\n\treturn nil\n}", "func (v Timestamp) Validate() error {\n\tif v < 0 {\n\t\treturn fmt.Errorf(\"api: Timestamp value cannot be negative: %d\", v)\n\t}\n\treturn nil\n}", "func (m *Submission) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func tweet() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: tweetCreate,\n\t\tRead: tweetRead,\n\t\tUpdate: tweetUpdate,\n\t\tDelete: tweetDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"message\": &schema.Schema{\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t},\n\t}\n}", "func Validate([]byte) error { return nil }", "func (h *Handler) NewTweet(c echo.Context) (err error) {\n\tuserID := userIDFromToken(c)\n\n\tdb := h.DB.Clone()\n\tdefer db.Close()\n\n\ttweet := &model.Tweet{ID: bson.NewObjectId(), Owner: string(userID), Timestamp: time.Now()}\n\tif err = c.Bind(tweet); err != nil {\n\t\treturn\n\t}\n\t\n\t\n\t// Validation\n\tif tweet.Message == \"\" {\n\t\treturn &echo.HTTPError{Code: http.StatusBadRequest, Message: \"Message cannot be empty.\"}\n\t}\n\t\n\t// Save tweet in database\n\terr = db.DB(\"se_avengers\").C(\"tweets\").Insert(tweet)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn c.JSON(http.StatusCreated, tweet)\n}", "func SaveTweet(tw models.Tweet) (string, bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\tdefer cancel()\n\n\tdb := MongoConnection.Database(\"gotwitor\")\n\tcollection := db.Collection(\"tweet\")\n\n\ttweet := bson.M{\n\t\t\"userid\": tw.UserID,\n\t\t\"message\": tw.Message,\n\t\t\"createdate\": tw.CreateDate,\n\t}\n\n\tresult, err := collection.InsertOne(ctx, tweet)\n\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\tobjI, _ := result.InsertedID.(primitive.ObjectID)\n\n\treturn objI.Hex(), true, nil\n}", "func (c Cooldown) validate() error {\n\treturn nil\n}", "func (e *CancelTransaction) Validate(\n\tr *http.Request,\n) error {\n\tctx := r.Context()\n\n\tswitch authentication.Get(ctx).Status {\n\tcase authentication.AutStSkipped:\n\t\t// Validate hop.\n\t\thop, err := ValidateHop(ctx, r.PostFormValue(\"hop\"))\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\te.Hop = *hop\n\t}\n\n\t// Validate id.\n\tid, owner, token, err := ValidateID(ctx, pat.Param(r, \"transaction\"))\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\te.ID = *id\n\te.Token = *token\n\te.Owner = *owner\n\n\treturn nil\n}", "func (o *PostcommentsOKBody) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (t *Ticket) Validate() error {\n\tif t.Id == \"\" {\n\t\treturn fmt.Errorf(\"invalid ticket id: %s\", t.Id)\n\t}\n\n\tif t.Timestamp.IsZero() {\n\t\treturn fmt.Errorf(\"invalid ticket creation time: %s\", t.Timestamp.Format(time.RFC3339))\n\t}\n\n\tif _, err := sdk.AccAddressFromBech32(t.Owner); err != nil {\n\t\treturn fmt.Errorf(\"invalid ticket owner: %s\", t.Owner)\n\t}\n\n\treturn nil\n}", "func (r *NotifyRequest) Validate() error {\n\tif r.Credentials == nil && r.OAuthToken.Token == \"\" {\n\t\treturn errors.New(\"secret was empty\")\n\t}\n\tif len(r.Channels) == 0 {\n\t\treturn errors.New(\"channels was empty\")\n\t}\n\tif r.Title == \"\" {\n\t\treturn errors.New(\"title was empty\")\n\t}\n\treturn nil\n}", "func (m *JumboMtu) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateMaxMtu(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}", "func (m *Stream) Validate() error {\n\treturn m.validate(false)\n}", "func (t *Term) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.NewErrors(), nil\n}", "func (c Pet) Validate() error {\n\tif helpers.ContainsString(allowedStatuses, c.Status) {\n\t\treturn nil\n\t}\n\treturn errors.New(\"status is not valid\")\n}", "func (this *Twitter) PostTweet(userId int, tweetId int) {\n \n}", "func (mt *RankdbElementTiny) Validate() (err error) {\n\n\tif mt.Payload == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"payload\"))\n\t}\n\tif mt.ID < 0 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.id`, mt.ID, 0, true))\n\t}\n\tif mt.Score < 0 {\n\t\terr = goa.MergeErrors(err, goa.InvalidRangeError(`response.score`, mt.Score, 0, true))\n\t}\n\treturn\n}", "func (payload *CreateCommentPayload) Validate() (err error) {\n\n\tif payload.Text == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\n\treturn\n}", "func (b Book) Validate() error {\n\tvar zeroTime time.Time\n\tif len(b.Title) == 0 {\n\t\treturn ErrTitleIsRequired\n\t}\n\tif len(b.Author) == 0 {\n\t\treturn ErrAuthorIsRequired\n\t}\n\tif b.PubDate == zeroTime {\n\t\treturn ErrPubDateIsRequired\n\t}\n\tif err := b.validateRating(); err != nil {\n\t\treturn err\n\t}\n\treturn b.validateStatus()\n}", "func (tl *Timeline) Tweet(status Status) (e error) {\n\t_, e = tl.client.Post(\n\t\t\"https://api.twitter.com/1.1/statuses/update.json\",\n\t\tstatus.ToParams(),\n\t)\n\treturn\n}", "func (payload *CreateMessagePayload) Validate() (err error) {\n\n\tif payload.Text == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`raw`, \"text\"))\n\t}\n\treturn\n}", "func (ut *AccountVerificationInputPayload) Validate() (err error) {\n\tif ut.VerificationToken != nil {\n\t\tif utf8.RuneCountInString(*ut.VerificationToken) < 108 {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`response.verification_token`, *ut.VerificationToken, utf8.RuneCountInString(*ut.VerificationToken), 108, true))\n\t\t}\n\t}\n\treturn\n}", "func (o *UtilTestBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateCommand(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateResponse(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := o.validateStatus(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}", "func (m *User) Validate() error {\n\tif m.CreatedAt != \"\" {\n\t\tif _, err := time.Parse(time.RFC3339Nano, m.CreatedAt); err != nil {\n\t\t\treturn errors.Wrap(err, errors.ErrBadRequest, \"invalid time string in field created_at\")\n\t\t}\n\t}\n\n\tif m.UpdatedAt != \"\" {\n\t\tif _, err := time.Parse(time.RFC3339Nano, m.UpdatedAt); err != nil {\n\t\t\treturn errors.Wrap(err, errors.ErrBadRequest, \"invalid time string in field updated_at\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (dao *Dao) IsValidTerm(term time.Time) bool {\n\n\treturn true\n}", "func (mt *Hello) Validate() (err error) {\n\tif mt.Hello == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"hello\"))\n\t}\n\treturn\n}", "func (m *HttpBody) Validate() error {\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\t// no validation rules for Body\n\n\t// no validation rules for EndOfStream\n\n\treturn nil\n}" ]
[ "0.5874286", "0.58268666", "0.57588404", "0.57587236", "0.56676954", "0.5583745", "0.55723965", "0.5527022", "0.5522042", "0.55206895", "0.55169415", "0.5466347", "0.5446972", "0.544323", "0.5401981", "0.5369382", "0.534803", "0.5335379", "0.53225595", "0.5300802", "0.52985215", "0.5276579", "0.52610654", "0.52310514", "0.52115345", "0.5206959", "0.5203935", "0.51818347", "0.5177645", "0.5174364", "0.5158504", "0.5130719", "0.5126731", "0.51132303", "0.51099193", "0.5106619", "0.50765884", "0.5075655", "0.50553167", "0.5051373", "0.5041665", "0.5029235", "0.5025027", "0.50211734", "0.5015323", "0.5012615", "0.50122434", "0.49898374", "0.4988406", "0.49873734", "0.49857256", "0.49843848", "0.4979067", "0.49709916", "0.4968132", "0.49611783", "0.49487394", "0.49473482", "0.4946953", "0.49426895", "0.49392402", "0.49375662", "0.49368745", "0.49368745", "0.49315155", "0.492529", "0.49157035", "0.49153024", "0.4906623", "0.49031955", "0.4901324", "0.49011636", "0.48989624", "0.48966244", "0.4894208", "0.488326", "0.48766944", "0.48729056", "0.4863425", "0.48617697", "0.48581654", "0.48575", "0.4855355", "0.4855299", "0.4854883", "0.4848423", "0.4844684", "0.4844048", "0.48423886", "0.4841425", "0.48382986", "0.48364395", "0.48352122", "0.48286244", "0.48233414", "0.4821532", "0.4815266", "0.4813229", "0.48017117", "0.48008814" ]
0.78896123
0
DeleteVpdGrantRule invokes the eflo.DeleteVpdGrantRule API synchronously
func (client *Client) DeleteVpdGrantRule(request *DeleteVpdGrantRuleRequest) (response *DeleteVpdGrantRuleResponse, err error) { response = CreateDeleteVpdGrantRuleResponse() err = client.DoAction(request, response) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) DeleteVpdGrantRuleWithCallback(request *DeleteVpdGrantRuleRequest, callback func(response *DeleteVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteVpdGrantRuleWithChan(request *DeleteVpdGrantRuleRequest) (<-chan *DeleteVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func CreateDeleteVpdGrantRuleRequest() (request *DeleteVpdGrantRuleRequest) {\n\trequest = &DeleteVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"DeleteVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateDeleteVpdGrantRuleResponse() (response *DeleteVpdGrantRuleResponse) {\n\tresponse = &DeleteVpdGrantRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) {\n\n\tvar attr string\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP {\n\t\tattr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId\n\t} else {\n\t\tattr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tif err = n.RemoveXattr(ctx, attr, acquireLock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func deleteRule(c *cli.Context) error {\n\n\truleid, err := hex.DecodeString(c.String(\"id\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[x] Incorrect ruleid format. \")\n\t}\n\n\terr = mapi.ExecuteMailRuleDelete(ruleid)\n\tif err == nil {\n\t\tfmt.Println(\"[*] Rule deleted. Fetching list of remaining rules...\")\n\t\trules, er := mapi.DisplayRules()\n\t\tif er != nil {\n\t\t\treturn er\n\t\t}\n\t\tfmt.Printf(\"[+] Found %d rules\\n\", len(rules))\n\t\tfor _, v := range rules {\n\t\t\tfmt.Printf(\"Rule: %s RuleID: %x\\n\", string(v.RuleName), v.RuleID)\n\t\t}\n\t\treturn nil\n\t}\n\treturn err\n}", "func (client *Client) CreateVpdGrantRuleWithCallback(request *CreateVpdGrantRuleRequest, callback func(response *CreateVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (s Service) DeleteTransitionRule(ctx context.Context, docID, ruleID []byte) error {\n\treturn s.pendingDocSrv.DeleteTransitionRule(ctx, docID, ruleID)\n}", "func (self *PolicyAgent) DelRule(rule *OfnetPolicyRule, ret *bool) error {\n\tlog.Infof(\"Received DelRule: %+v\", rule)\n\n\t// Gte the rule\n\tself.mutex.Lock()\n\tdefer self.mutex.Unlock()\n\tcache := self.Rules[rule.RuleId]\n\tif cache == nil {\n\t\tlog.Errorf(\"Could not find rule: %+v\", rule)\n\t\treturn errors.New(\"rule not found\")\n\t}\n\n\t// Delete the Flow\n\terr := cache.flow.Delete()\n\tif err != nil {\n\t\tlog.Errorf(\"Error deleting flow: %+v. Err: %v\", rule, err)\n\t}\n\n\t// Delete the rule from cache\n\tdelete(self.Rules, rule.RuleId)\n\n\treturn nil\n}", "func DeleteRule(ctx context.Context, p *Protocol, routeID routing.RouteID) error {\n\tif err := p.WritePacket(PacketDeleteRules, []routing.RouteID{routeID}); err != nil {\n\t\treturn err\n\t}\n\tvar res []routing.RouteID\n\tif err := readAndDecodePacketWithTimeout(ctx, p, &res); err != nil {\n\t\treturn err\n\t}\n\tif len(res) == 0 {\n\t\treturn errors.New(\"empty response\")\n\t}\n\treturn nil\n}", "func (s *Service) DelGrantCase(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {\n\tmr := &model.Case{}\n\tif err = json.Unmarshal(nwMsg, mr); err != nil {\n\t\tlog.Error(\"json.Unmarshal(%s) error(%v)\", string(nwMsg), err)\n\t\treturn\n\t}\n\tif mr.Status == model.CaseStatusDealing && mr.CaseType == model.JudeCaseTypePrivate {\n\t\treturn\n\t}\n\tif mr.Status == model.CaseStatusGranting || mr.Status == model.CaseStatusDealed || mr.Status == model.CaseStatusRestart {\n\t\treturn\n\t}\n\tcids := []int64{mr.ID}\n\t// 删除冻结和停止发放中的cid\n\tif err = s.dao.DelGrantCase(c, cids); err != nil {\n\t\tlog.Error(\"s.dao.SetMIDCaseGrant(%d) error(%v)\", mr.ID, err)\n\t}\n\tlog.Info(\"cid(%d) status(%d) remove hash list on start_time(%s) and end_time(%s)\", mr.ID, mr.Status, mr.Stime, mr.Etime)\n\treturn\n}", "func (_m *ComputeAPI) DeleteFirewallRule(project string, firewall string) {\n\t_m.Called(project, firewall)\n}", "func (probe *BridgeOfProbe) delRule(rule *Rule) {\n\tlogging.GetLogger().Infof(\"Rule %v deleted\", rule.UUID)\n\tg := probe.OvsOfProbe.Graph\n\tg.Lock()\n\tdefer g.Unlock()\n\n\truleNode := g.LookupFirstNode(graph.Metadata{\"UUID\": rule.UUID})\n\tif ruleNode != nil {\n\t\tg.DelNode(ruleNode)\n\t}\n}", "func (_m *FakeScheduleService) DeleteAlertRule(key models.AlertRuleKey) {\n\t_m.Called(key)\n}", "func HandleDeleteEventingTriggerRule(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tvars := mux.Vars(r)\n\t\truleName := vars[\"id\"]\n\t\tprojectID := vars[\"project\"]\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-trigger\", \"modify\", map[string]string{\"project\": projectID, \"id\": ruleName})\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, nil)\n\t\tstatus, err := syncMan.SetDeleteEventingRule(ctx, projectID, ruleName, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, status, w)\n\t}\n}", "func (m *AuthorizationServerPolicyRuleResource) DeleteAuthorizationServerPolicyRule(ctx context.Context, authServerId string, policyId string, ruleId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/authorizationServers/%v/policies/%v/rules/%v\", authServerId, policyId, ruleId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (se *StorageEndpoint) DeleteRule(ruleKey string) error {\n\treturn se.Remove(ruleKeyPath(ruleKey))\n}", "func (s *LocalTests) deleteFwRule(c *gc.C, fwRuleId string) {\n\terr := s.testClient.DeleteFirewallRule(fwRuleId)\n\tc.Assert(err, gc.IsNil)\n}", "func (c *AuditClient) DeleteRule(rule []byte) error {\n\tmsg := syscall.NetlinkMessage{\n\t\tHeader: syscall.NlMsghdr{\n\t\t\tType: uint16(auparse.AUDIT_DEL_RULE),\n\t\t\tFlags: syscall.NLM_F_REQUEST | syscall.NLM_F_ACK,\n\t\t},\n\t\tData: rule,\n\t}\n\n\t// Send AUDIT_DEL_RULE message to the kernel.\n\tseq, err := c.Netlink.Send(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed sending delete rule request: %w\", err)\n\t}\n\n\t_, err = c.getReply(seq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get ACK to rule delete request: %w\", err)\n\t}\n\n\treturn nil\n}", "func (as AccountStorage) DeleteGrantPubKey(ctx sdk.Context, me types.AccountKey, pubKey crypto.PubKey) {\n\tstore := ctx.KVStore(as.key)\n\tstore.Delete(getGrantPubKeyKey(me, pubKey))\n\treturn\n}", "func (nat *NATCloud) ensureDeleteDNATRule(natProvider *NATClient, dnatRule *DNATRule, natGatewayId string) error {\n\tklog.V(4).Infoln(\"Delete the DNAT Rule when the node is not ready\", dnatRule.FloatingIpAddress+\":\"+fmt.Sprint(dnatRule.ExternalServicePort))\n\terr := natProvider.DeleteDNATRule(dnatRule.Id, natGatewayId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.Poll(100*time.Millisecond, 5*time.Second, func() (bool, error) {\n\t\treturn !nat.checkDNATRuleById(natProvider, dnatRule.Id), nil\n\t})\n}", "func (c *TestClient) DeleteForwardingRule(project, region, name string) error {\n\tif c.DeleteForwardingRuleFn != nil {\n\t\treturn c.DeleteForwardingRuleFn(project, region, name)\n\t}\n\treturn c.client.DeleteForwardingRule(project, region, name)\n}", "func (sdk *MockGoSDKClient) DeleteSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) {\n\treturn nil\n}", "func (api *API) TeamsDeleteRule(ctx context.Context, accountID string, ruleId string) error {\n\turi := fmt.Sprintf(\"/accounts/%s/gateway/rules/%s\", accountID, ruleId)\n\n\t_, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteRule(rule AuditRule) error {\n\tclient, err := libaudit.NewAuditClient(nil)\n\tdefer client.Close()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to initialize client\")\n\t}\n\tkr, _, _, err := rule.toKernelAuditRule()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to initialize client\")\n\t}\n\tif err := client.DeleteRule(kr.toWireFormat()); err != nil {\n\t\treturn errors.Wrap(err, \"Failed to delete audit rule\")\n\t}\n\treturn nil\n}", "func (c *restClient) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGuestPolicyRequest, opts ...gax.CallOption) error {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1beta/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\treturn gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"DELETE\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\t// Returns nil if there is no error, otherwise wraps\n\t\t// the response code and body into a non-nil error\n\t\treturn googleapi.CheckResponse(httpRsp)\n\t}, opts...)\n}", "func (c *Client) DeleteRule(args *DeleteRuleArgs) error {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn DeleteRule(c, body)\n}", "func (client *Client) CreateVpdGrantRule(request *CreateVpdGrantRuleRequest) (response *CreateVpdGrantRuleResponse, err error) {\n\tresponse = CreateCreateVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func DeleteRule(rule string) {\n\tdelete(customRuleFuncMap, rule)\n}", "func (client *Client) CreateVpdGrantRuleWithChan(request *CreateVpdGrantRuleRequest) (<-chan *CreateVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteRule(request *DeleteRuleRequest) (_result *DeleteRuleResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &DeleteRuleResponse{}\n\t_body, _err := client.DeleteRuleWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (a *HyperflexApiService) DeleteHyperflexProxySettingPolicy(ctx context.Context, moid string) ApiDeleteHyperflexProxySettingPolicyRequest {\n\treturn ApiDeleteHyperflexProxySettingPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func DeleteRule(id string) int {\n\tvar rule database.Rule\n\tdb.DB.Where(\"id = ? \", id).First(&rule)\n\tdb.DB.Where(\"id = ?\", id).Delete(&database.Rule{})\n\treturn rule.ReleaseID\n}", "func DeleteACLRule(r *http.Request, target ACLTarget, actor ACLActor) (err error) {\n\n\t// get service\n\ts := service.Providers.MustService(r, \"ACLRule\")\n\n\t// delete the rules\n\tconds := service.NewConds()\n\tconds.Add(\"target\", string(target))\n\tconds.Add(\"actor\", string(actor))\n\ts.Delete(conds)\n\n\treturn\n}", "func Delete(c *golangsdk.ServiceClient, policyID, ruleID string) (r DeleteResult) {\n\treqOpt := &golangsdk.RequestOpts{\n\t\tMoreHeaders: RequestOpts.MoreHeaders,\n\t}\n\n\t_, r.Err = c.Delete(resourceURL(c, policyID, ruleID), reqOpt)\n\treturn\n}", "func (client GroupClient) DeleteSecretResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func deleteMulticastAllowPolicy(ovnNBClient goovn.Client, ns string, nsInfo *namespaceInfo) error {\n\tportGroupHash := hashedPortGroup(ns)\n\n\terr := deleteMulticastACLs(ns, portGroupHash, nsInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_ = nsInfo.updateNamespacePortGroup(ovnNBClient, ns)\n\treturn nil\n}", "func (hd *Datapath) DeleteTCPProxyPolicy(tcp *netproto.TCPProxyPolicy, vrf *netproto.Vrf) error {\n\t// This will ensure that only one datapath config will be active at a time. This is a temporary restriction\n\t// to ensure that HAL will use a single config thread , this will be removed prior to FCS to allow parallel configs to go through.\n\t// TODO Remove Global Locking\n\thd.Lock()\n\tdefer hd.Unlock()\n\tvrfKey := &halproto.VrfKeyHandle{\n\t\tKeyOrHandle: &halproto.VrfKeyHandle_VrfId{\n\t\t\tVrfId: vrf.Status.VrfID,\n\t\t},\n\t}\n\n\ttcpProxyPolicyDelReq := &halproto.TcpProxyRuleDeleteRequestMsg{\n\t\tRequest: []*halproto.TcpProxyRuleDeleteRequest{\n\t\t\t{\n\t\t\t\tKeyOrHandle: &halproto.TcpProxyRuleKeyHandle{\n\t\t\t\t\tKeyOrHandle: &halproto.TcpProxyRuleKeyHandle_RuleKey{\n\t\t\t\t\t\tRuleKey: &halproto.TcpProxyRuleKey{\n\t\t\t\t\t\t\tTcpProxyRuleId: tcp.Status.TCPProxyPolicyID,\n\t\t\t\t\t\t\tVrfKeyOrHandle: vrfKey,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif hd.Kind == \"hal\" {\n\t\tresp, err := hd.Hal.TCPProxyPolicyClient.TcpProxyRuleDelete(context.Background(), tcpProxyPolicyDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting TCPProxy Policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tif resp.Response[0].ApiStatus != halproto.ApiStatus_API_STATUS_OK {\n\t\t\tlog.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t\treturn fmt.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t}\n\t} else {\n\t\t_, err := hd.Hal.TCPProxyPolicyClient.TcpProxyRuleDelete(context.Background(), tcpProxyPolicyDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting TCPProxy Policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (r *DeviceComplianceScheduledActionForRuleRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (client WorkloadNetworksClient) DeleteDhcpResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (manager *Manager) onDeleteEgressPolicy(policy *Policy) {\n\tconfigID := ParseCEGPConfigID(policy)\n\n\tmanager.Lock()\n\tdefer manager.Unlock()\n\n\tlogger := log.WithField(logfields.CiliumEgressGatewayPolicyName, configID.Name)\n\n\tif manager.policyConfigs[configID] == nil {\n\t\tlogger.Warn(\"Can't delete CiliumEgressGatewayPolicy: policy not found\")\n\t}\n\n\tlogger.Debug(\"Deleted CiliumEgressGatewayPolicy\")\n\n\tdelete(manager.policyConfigs, configID)\n\n\tmanager.setEventBitmap(eventDeletePolicy)\n\tmanager.reconciliationTrigger.TriggerWithReason(\"policy deleted\")\n}", "func (client FirewallPolicyRuleGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (r *FirewallGlobalRulesStagedPolicyRulesResource) Delete(id string) error {\n\tif err := r.c.ModQuery(\"DELETE\", BasePath+FirewallGlobalRulesStagedPolicyRulesEndpoint+\"/\"+id, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) DeleteAclRule(aclRuleId, clientToken string) error {\n\treturn bce.NewRequestBuilder(c).\n\t\tWithURL(getURLForAclRuleId(aclRuleId)).\n\t\tWithMethod(http.DELETE).\n\t\tWithQueryParamFilter(\"clientToken\", clientToken).\n\t\tDo()\n}", "func (client WorkloadNetworksClient) DeleteVMGroupResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client IdentityClient) deletePolicy(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/policies/{policyId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeletePolicyResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (c *Client) DeleteLoyaltyRule(id int64) error {\n\treturn c.DeleteLoyaltyRules([]int64{id})\n}", "func deleteDenyPolicy(w io.Writer, projectID, policyID string) error {\n\t// projectID := \"your_project_id\"\n\t// policyID := \"your_policy_id\"\n\n\tctx := context.Background()\n\tpoliciesClient, err := iam.NewPoliciesClient(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewPoliciesClient: %w\", err)\n\t}\n\tdefer policiesClient.Close()\n\n\t// Each deny policy is attached to an organization, folder, or project.\n\t// To work with deny policies, specify the attachment point.\n\t//\n\t// Its format can be one of the following:\n\t// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID\n\t// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID\n\t// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID\n\t//\n\t// The attachment point is identified by its URL-encoded resource name. Hence, replace\n\t// the \"/\" with \"%%2F\".\n\tattachmentPoint := fmt.Sprintf(\n\t\t\"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s\",\n\t\tprojectID,\n\t)\n\n\treq := &iampb.DeletePolicyRequest{\n\t\t// Construct the full path of the policy.\n\t\t// Its format is: \"policies/ATTACHMENT_POINT/denypolicies/POLICY_ID\"\n\t\tName: fmt.Sprintf(\"policies/%s/denypolicies/%s\", attachmentPoint, policyID),\n\t}\n\top, err := policiesClient.DeletePolicy(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete policy: %w\", err)\n\t}\n\n\tpolicy, err := op.Wait(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to wait for the operation: %w\", err)\n\t}\n\n\tfmt.Fprintf(w, \"Policy %s deleted\\n\", policy.GetName())\n\n\treturn nil\n}", "func (h *hnsw) deleteEntrypoint(node *vertex, denyList helpers.AllowList) error {\n\tif h.isOnlyNode(node, denyList) {\n\t\t// no point in finding another entrypoint if this is the only node\n\t\treturn nil\n\t}\n\n\tnode.Lock()\n\tlevel := node.level\n\tnode.Unlock()\n\n\tnewEntrypoint, level := h.findNewEntrypoint(denyList, level)\n\n\th.Lock()\n\th.entryPointID = newEntrypoint\n\th.currentMaximumLayer = level\n\th.Unlock()\n\th.commitLog.SetEntryPointWithMaxLayer(newEntrypoint, level)\n\n\treturn nil\n}", "func DeleteRule(table Table, chain Chain, args ...string) error {\n\tfullArgs := makeFullArgs(table, opDeleteRule, chain, args...)\n\tout, err := run(cmd, fullArgs...)\n\tif err != nil {\n\t\treturn trace.Wrap(err, \"failed to delete %v chain %v rule %v: %s\", table, chain, args, out)\n\t}\n\treturn nil\n}", "func (db *Permstore) DelPerm(perm *model.Perm) error {\n\tvar _, err = db.Exec(rebind(permDeleteStmt), perm.ID)\n\treturn err\n}", "func (s *Manager) SetDeleteEventingRule(ctx context.Context, project, ruleName string, params model.RequestParams) (int, error) {\n\t// Check if the request has been hijacked\n\thookResponse := s.integrationMan.InvokeHook(ctx, params)\n\tif hookResponse.CheckResponse() {\n\t\t// Check if an error occurred\n\t\tif err := hookResponse.Error(); err != nil {\n\t\t\treturn hookResponse.Status(), err\n\t\t}\n\n\t\t// Gracefully return\n\t\treturn hookResponse.Status(), nil\n\t}\n\n\t// Acquire a lock\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tprojectConfig, err := s.getConfigWithoutLock(ctx, project)\n\tif err != nil {\n\t\treturn http.StatusBadRequest, err\n\t}\n\n\tresourceID := config.GenerateResourceID(s.clusterID, project, config.ResourceEventingTrigger, ruleName)\n\tdelete(projectConfig.EventingTriggers, resourceID)\n\n\tif err := s.modules.SetEventingTriggerConfig(ctx, project, projectConfig.EventingTriggers); err != nil {\n\t\treturn http.StatusInternalServerError, helpers.Logger.LogError(helpers.GetRequestID(ctx), \"error setting eventing config\", err, nil)\n\t}\n\n\tif err := s.store.DeleteResource(ctx, resourceID); err != nil {\n\t\treturn http.StatusInternalServerError, err\n\t}\n\n\treturn http.StatusOK, nil\n}", "func (psh *psHandle) RecordDelete(dnsserver, domain string, rec *models.RecordConfig) error {\n\n\tvar c string\n\tif rec.Type == \"NAPTR\" {\n\t\tc = generatePSDeleteNaptr(dnsserver, domain, rec)\n\t\t//printer.Printf(\"DEBUG: deleteNAPTR: %s\\n\", c)\n\t} else {\n\t\tc = generatePSDelete(dnsserver, domain, rec)\n\t}\n\n\t//eLog(c)\n\t_, stderr, err := psh.shell.Execute(c)\n\tif err != nil {\n\t\tprinter.Printf(\"PowerShell code was:\\nSTART\\n%s\\nEND\\n\", c)\n\t\treturn err\n\t}\n\tif stderr != \"\" {\n\t\tprinter.Printf(\"STDERROR = %q\\n\", stderr)\n\t\tprinter.Printf(\"PowerShell code was:\\nSTART\\n%s\\nEND\\n\", c)\n\t\treturn fmt.Errorf(\"unexpected stderr from PSDelete: %q\", stderr)\n\t}\n\treturn nil\n}", "func (a *Client) DeleteMsgVpnRestDeliveryPoint(params *DeleteMsgVpnRestDeliveryPointParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteMsgVpnRestDeliveryPointOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteMsgVpnRestDeliveryPointParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteMsgVpnRestDeliveryPoint\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/msgVpns/{msgVpnName}/restDeliveryPoints/{restDeliveryPointName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteMsgVpnRestDeliveryPointReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*DeleteMsgVpnRestDeliveryPointOK), nil\n\n}", "func (c *TestClient) DeleteFirewallRule(project, name string) error {\n\tif c.DeleteFirewallRuleFn != nil {\n\t\treturn c.DeleteFirewallRuleFn(project, name)\n\t}\n\treturn c.client.DeleteFirewallRule(project, name)\n}", "func (s *permStore) Delete(ctx context.Context, perm *core.Perm) error {\n\treturn s.db.Lock(func(execer db.Execer, binder db.Binder) error {\n\t\tparams := toParams(perm)\n\t\tstmt, args, err := binder.BindNamed(stmtDelete, params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = execer.Exec(stmt, args...)\n\t\treturn err\n\t})\n}", "func (a *SyncApiService) DeleteSyncRule(ctx context.Context, syncRuleId string) ( *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/platform/3/sync/rules/{SyncRuleId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"SyncRuleId\"+\"}\", fmt.Sprintf(\"%v\", syncRuleId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\treturn localVarHttpResponse, err\n}", "func (m *MockFirewallServiceIface) DeletePortForwardingRule(p *DeletePortForwardingRuleParams) (*DeletePortForwardingRuleResponse, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeletePortForwardingRule\", p)\n\tret0, _ := ret[0].(*DeletePortForwardingRuleResponse)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *Service) DeleteFirewallRulePort(ruleID string) (string, error) {\n\tbody, err := s.deleteFirewallRulePortResponseBody(ruleID)\n\n\treturn body.Data.TaskID, err\n}", "func (se *StorageEndpoint) DeleteRuleGroup(groupID string) error {\n\treturn se.Remove(ruleGroupIDPath(groupID))\n}", "func (a *HyperflexApiService) DeleteHyperflexVcenterConfigPolicy(ctx context.Context, moid string) ApiDeleteHyperflexVcenterConfigPolicyRequest {\n\treturn ApiDeleteHyperflexVcenterConfigPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (n *Node) DeleteKeygroupTrigger(kgname, triggerNodeID string, expectError bool) {\n\tstatus, err := n.Client.RemoveTrigger(context.Background(), &client.RemoveTriggerRequest{Keygroup: kgname, TriggerId: triggerNodeID})\n\n\tif err != nil && !expectError {\n\t\tlog.Warn().Msgf(\"DeleteKeygroupTrigger: error %s\", err)\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && expectError {\n\t\tlog.Warn().Msg(\"DeleteKeygroupTrigger: Expected Error bot got no error\")\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && status.Status == client.EnumStatus_ERROR && !expectError {\n\t\tlog.Warn().Msgf(\"DeleteKeygroupTrigger: error %s with status %s\", err, status.Status)\n\t\tn.Errors++\n\t}\n}", "func (client DataFlowClient) DeleteDataFlowResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (a *HyperflexApiService) DeleteHyperflexNodeConfigPolicy(ctx context.Context, moid string) ApiDeleteHyperflexNodeConfigPolicyRequest {\n\treturn ApiDeleteHyperflexNodeConfigPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (client *VirtualApplianceSitesClient) delete(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesBeginDeleteOptions) (*azcore.Response, error) {\n\treq, err := client.deleteCreateRequest(ctx, resourceGroupName, networkVirtualApplianceName, siteName, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.con.Pipeline().Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !resp.HasStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent) {\n\t\treturn nil, client.deleteHandleError(resp)\n\t}\n\treturn resp, nil\n}", "func (c *DRMPoliciesClient) Delete(siteID, drmPolicyID string) error {\n\tpath := fmt.Sprintf(\"/v2/sites/%s/drm_policies/%s\", siteID, drmPolicyID)\n\terr := c.v2Client.Request(http.MethodDelete, path, nil, nil, nil)\n\treturn err\n}", "func (s *Manager) SetDeleteEventingRule(ctx context.Context, project, ruleName string, params model.RequestParams) (int, error) {\n\t// Acquire a lock\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tprojectConfig, err := s.getConfigWithoutLock(ctx, project)\n\tif err != nil {\n\t\treturn http.StatusBadRequest, err\n\t}\n\tdelete(projectConfig.Modules.Eventing.Rules, ruleName)\n\n\tif err := s.modules.SetEventingConfig(project, &projectConfig.Modules.Eventing); err != nil {\n\t\treturn http.StatusInternalServerError, helpers.Logger.LogError(helpers.GetRequestID(ctx), \"error setting eventing config\", err, nil)\n\t}\n\n\tif err := s.setProject(ctx, projectConfig); err != nil {\n\t\treturn http.StatusInternalServerError, err\n\t}\n\n\treturn http.StatusOK, nil\n}", "func (r *RedisDL) deleteToken() error {\n\t_, err := r.client.Del(r.opt.Key).Result()\n\treturn err\n}", "func (l *Libvirt) DomainCheckpointDelete(Checkpoint DomainCheckpoint, Flags DomainCheckpointDeleteFlags) (err error) {\n\tvar buf []byte\n\n\targs := DomainCheckpointDeleteArgs {\n\t\tCheckpoint: Checkpoint,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(417, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func podDeleteAllowMulticastPolicy(ovnNBClient goovn.Client, ns, name, uuid string) error {\n\treturn deleteFromPortGroup(ovnNBClient, hashedPortGroup(ns), name, uuid)\n}", "func (m *Manager) DeleteRule(n string) bool {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif _, ok := m.rules[n]; !ok {\n\t\treturn false\n\t}\n\tdelete(m.rules, n)\n\treturn true\n}", "func (c *controller) DeletePolicy(ctx context.Context, id int64) error {\n\ts, err := c.pManager.Get(ctx, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif s.Trigger != nil && s.Trigger.Type == policyModels.TriggerTypeScheduled && len(s.Trigger.Settings.Cron) > 0 {\n\t\terr = c.scheduler.UnScheduleByVendor(ctx, job.P2PPreheatVendorType, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err = c.deleteExecs(ctx, id); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.pManager.Delete(ctx, id)\n}", "func (pa *PermAccess) DeletePerms(opt *dauth.PermFind) <-chan dlib.Result {\n\tch := make(chan dlib.Result, 256)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\trows, err := pa.DBS.Query(\n\t\t\t\"SELECT delete_perms($1, $2, $3) AS num\",\n\t\t\topt.ID,\n\t\t\topt.Service,\n\t\t\topt.Name)\n\t\tif err != nil {\n\t\t\tch <- dlib.Result{Err: err}\n\t\t\treturn\n\t\t}\n\n\t\tdefer rows.Close()\n\t\tn := 0\n\t\tfor rows.Next() {\n\t\t\tr := struct{ Num int }{Num: 0}\n\t\t\tif err := rows.Scan(&r.Num); err != nil {\n\t\t\t\tch <- dlib.Result{Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tn += r.Num\n\t\t}\n\n\t\tch <- dlib.Result{Num: n, Err: nil}\n\t}()\n\n\treturn ch\n}", "func (m *TeamTemplatesItemDefinitionsItemTeamDefinitionPermissionGrantsResourceSpecificPermissionGrantItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *TeamTemplatesItemDefinitionsItemTeamDefinitionPermissionGrantsResourceSpecificPermissionGrantItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (hd *Datapath) DeleteNatPolicy(np *netproto.NatPolicy, vrf *netproto.Vrf) error {\n\t// This will ensure that only one datapath config will be active at a time. This is a temporary restriction\n\t// to ensure that HAL will use a single config thread , this will be removed prior to FCS to allow parallel configs to go through.\n\t// TODO Remove Global Locking\n\thd.Lock()\n\tdefer hd.Unlock()\n\tvrfKey := &halproto.VrfKeyHandle{\n\t\tKeyOrHandle: &halproto.VrfKeyHandle_VrfId{\n\t\t\tVrfId: vrf.Status.VrfID,\n\t\t},\n\t}\n\n\t// Build Nat Policy Key\n\tnatPolicyKey := &halproto.NatPolicyKeyHandle{\n\t\tKeyOrHandle: &halproto.NatPolicyKeyHandle_PolicyKey{\n\t\t\tPolicyKey: &halproto.NATPolicyKey{\n\t\t\t\tVrfKeyOrHandle: vrfKey,\n\t\t\t\tNatPolicyId: np.Status.NatPolicyID,\n\t\t\t},\n\t\t},\n\t}\n\n\tnpDelReq := &halproto.NatPolicyDeleteRequestMsg{\n\t\tRequest: []*halproto.NatPolicyDeleteRequest{\n\t\t\t{\n\t\t\t\tKeyOrHandle: natPolicyKey,\n\t\t\t},\n\t\t},\n\t}\n\n\t// delete hal objects\n\tif hd.Kind == \"hal\" {\n\t\t// delete route\n\t\tresp, err := hd.Hal.Natclient.NatPolicyDelete(context.Background(), npDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting nat policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tif resp.Response[0].ApiStatus != halproto.ApiStatus_API_STATUS_OK {\n\t\t\tlog.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t\treturn fmt.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t}\n\n\t} else {\n\t\t_, err := hd.Hal.Natclient.NatPolicyDelete(context.Background(), npDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting nat policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func HandleDeleteEventingSecurityRule(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tevType := vars[\"id\"]\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-rule\", \"modify\", map[string]string{\"project\": projectID, \"id\": evType})\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to validate token for delete eventing rules\", err, nil)\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, nil)\n\t\tstatus, err := syncMan.SetDeleteEventingSecurityRules(ctx, projectID, evType, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to delete eventing rules\", err, nil)\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, status, w)\n\t}\n}", "func (c *Client) LeafInterfacePolicyGroupDel(group string) error {\n\n\tme := \"LeafInterfacePolicyGroupDel\"\n\n\trn := rnLeafPortGroup(group)\n\n\tapi := \"/api/node/mo/uni/infra/funcprof.json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"infraFuncP\":{\"attributes\":{\"dn\":\"uni/infra/funcprof\",\"status\":\"modified\"},\"children\":[{\"infraAccPortGrp\":{\"attributes\":{\"dn\":\"uni/infra/funcprof/%s\",\"status\":\"deleted\"}}}]}}`,\n\t\trn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}", "func (c *Client) DeleteAccessRule(dirBlindName string, accountName api.AccountName) error {\n\trawURL := fmt.Sprintf(pathDirRule, c.base.String(), dirBlindName, accountName)\n\terr := c.delete(rawURL, true, nil)\n\treturn errio.Error(err)\n}", "func (s *GroupsService) DeleteGroupPushRule(gid interface{}, options ...RequestOptionFunc) (*Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu := fmt.Sprintf(\"groups/%s/push_rule\", PathEscape(group))\n\n\treq, err := s.client.NewRequest(http.MethodDelete, u, nil, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(req, nil)\n}", "func (s *JobTriggerServer) DeleteDlpJobTrigger(ctx context.Context, request *dlppb.DeleteDlpJobTriggerRequest) (*emptypb.Empty, error) {\n\n\tcl, err := createConfigJobTrigger(ctx, request.GetServiceAccountFile())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &emptypb.Empty{}, cl.DeleteJobTrigger(ctx, ProtoToJobTrigger(request.GetResource()))\n\n}", "func checkDeletePolicy(t *testing.T, expError bool, tenant, policy string) {\n\terr := contivClient.PolicyDelete(tenant, policy)\n\tif err != nil && !expError {\n\t\tt.Fatalf(\"Error deleting policy %s/%s. Err: %v\", tenant, policy, err)\n\t} else if err == nil && expError {\n\t\tt.Fatalf(\"Delete policy %s/%s succeded while expecing error\", tenant, policy)\n\t} else if err == nil {\n\t\t// verify policy is gone\n\t\t_, err := contivClient.PolicyGet(tenant, policy)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Policy %s/%s not deleted\", tenant, policy)\n\t\t}\n\t}\n}", "func DeleteL7Rule(t *testing.T, client *gophercloud.ServiceClient, lbID, policyID, ruleID string) {\n\tt.Logf(\"Attempting to delete l7 rule %s\", ruleID)\n\n\tif err := l7policies.DeleteRule(client, policyID, ruleID).ExtractErr(); err != nil {\n\t\tif _, ok := err.(gophercloud.ErrDefault404); !ok {\n\t\t\tt.Fatalf(\"Unable to delete l7 rule: %v\", err)\n\t\t}\n\t}\n\n\tif err := WaitForLoadBalancerState(client, lbID, \"ACTIVE\"); err != nil {\n\t\tt.Fatalf(\"Timed out waiting for loadbalancer to become active: %s\", err)\n\t}\n\n\tt.Logf(\"Successfully deleted l7 rule %s\", ruleID)\n}", "func ExampleAssignmentsVMSSClient_Delete() {\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\tclientFactory, err := armguestconfiguration.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewAssignmentsVMSSClient().Delete(ctx, \"myResourceGroupName\", \"myVMSSName\", \"SecureProtocol\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Assignment = armguestconfiguration.Assignment{\n\t// \tName: to.Ptr(\"AuditSecureProtocol\"),\n\t// \tID: to.Ptr(\"/subscriptions/subscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/myVMSSName/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/AuditSecureProtocol\"),\n\t// \tLocation: to.Ptr(\"centraluseuap\"),\n\t// \tProperties: &armguestconfiguration.AssignmentProperties{\n\t// \t\tAssignmentHash: to.Ptr(\"E0D8941DD713F284284561648C00C18FA76C8602943C7CD38AFD73B56AE4C35F.E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855\"),\n\t// \t\tComplianceStatus: to.Ptr(armguestconfiguration.ComplianceStatusCompliant),\n\t// \t\tGuestConfiguration: &armguestconfiguration.Navigation{\n\t// \t\t\tName: to.Ptr(\"AuditSecureProtocol\"),\n\t// \t\t\tConfigurationParameter: []*armguestconfiguration.ConfigurationParameter{\n\t// \t\t\t},\n\t// \t\t\tContentHash: to.Ptr(\"content hash\"),\n\t// \t\t\tContentURI: to.Ptr(\"https://mystorageaccount.blob.core.windows.net/builtinconfig/AuditSecureProtocol/AuditSecureProtocol_1.0.0.3.zip\"),\n\t// \t\t\tVersion: to.Ptr(\"1.0.0.3\"),\n\t// \t\t},\n\t// \t\tLastComplianceStatusChecked: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-08-29T22:14:13Z\"); return t}()),\n\t// \t\tProvisioningState: to.Ptr(armguestconfiguration.ProvisioningStateSucceeded),\n\t// \t\tResourceType: to.Ptr(\"VMSS\"),\n\t// \t},\n\t// }\n}", "func DeletePrometheusRule(ctx context.Context, client client.Client, ruleName, ns string) error {\n\trule := &prometheusv1.PrometheusRule{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: ns,\n\t\t\tName: ruleName,\n\t\t},\n\t}\n\n\t// call delete on that object\n\tif err := client.Delete(ctx, rule); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *ResourceHandler) DeleteStageResource(project string, stage string, resourceURI string) error {\n\tr.ensureHandlerIsSet()\n\treturn r.resourceHandler.DeleteResourceByURI(context.TODO(), r.Scheme+\"://\"+r.BaseURL+v1ProjectPath+\"/\"+project+pathToStage+\"/\"+stage+pathToResource+\"/\"+url.QueryEscape(resourceURI))\n}", "func DeleteNetworkSecurityGroupRule() {}", "func (client *WCFRelaysClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysClientDeleteAuthorizationRuleOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif authorizationRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter authorizationRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{authorizationRuleName}\", url.PathEscape(authorizationRuleName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (r *DeviceCompliancePolicyGroupAssignmentRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (c *managementServiceClient) DeactivateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/DeactivateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (client FirewallPolicyRuleGroupsClient) Delete(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleGroupName string) (result FirewallPolicyRuleGroupsDeleteFuture, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/FirewallPolicyRuleGroupsClient.Delete\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.FutureAPI != nil && result.FutureAPI.Response() != nil {\n\t\t\t\tsc = result.FutureAPI.Response().StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.DeletePreparer(ctx, resourceGroupName, firewallPolicyName, ruleGroupName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"network.FirewallPolicyRuleGroupsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteSender(req)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"network.FirewallPolicyRuleGroupsClient\", \"Delete\", result.Response(), \"Failure sending request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (lps *LibraryPanelService) deleteLibraryPanel(c *models.ReqContext, uid string) error {\n\torgID := c.SignedInUser.OrgId\n\treturn lps.SQLStore.WithTransactionalDbSession(context.Background(), func(session *sqlstore.DBSession) error {\n\t\tresult, err := session.Exec(\"DELETE FROM library_panel WHERE uid=? and org_id=?\", uid, orgID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif rowsAffected, err := result.RowsAffected(); err != nil {\n\t\t\treturn err\n\t\t} else if rowsAffected != 1 {\n\t\t\treturn errLibraryPanelNotFound\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (r *GroupPolicyMigrationReportRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (a *HyperflexApiService) DeleteHyperflexProxySettingPolicyExecute(r ApiDeleteHyperflexProxySettingPolicyRequest) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.DeleteHyperflexProxySettingPolicy\")\n\tif err != nil {\n\t\treturn nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/ProxySettingPolicies/{Moid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"Moid\"+\"}\", url.PathEscape(parameterToString(r.moid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (a *Client) TravelExpensePassengerDelete(params *TravelExpensePassengerDeleteParams, authInfo runtime.ClientAuthInfoWriter) error {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewTravelExpensePassengerDeleteParams()\n\t}\n\n\t_, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"TravelExpensePassenger_delete\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/travelExpense/passenger/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &TravelExpensePassengerDeleteReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func (gt GtwyMgr) Delete(ctx context.Context, appcontext, remoteAddress string) error {\n\tif EnvDebugOn {\n\t\tlblog.LogEvent(\"GtwyMgr\", \"Delete\", \"info\", \"start\")\n\t}\n\n\t//check the approval list\n\tq := datastore.NewQuery(gt.bc.GetConfigValue(ctx, \"EnvGtwayDsKind\")).\n\t\tNamespace(gt.bc.GetConfigValue(ctx, \"EnvGtwayDsNamespace\")).\n\t\tFilter(\"appcontext =\", appcontext).\n\t\tFilter(\"remoteaddress =\", remoteAddress).\n\t\tKeysOnly()\n\n\tvar arr []Gateway\n\tkeys, err := gt.ds.GetAll(ctx, q, &arr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttx, err := gt.ds.NewTransaction(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tx.DeleteMulti(keys); err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tif _, err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\tif EnvDebugOn {\n\t\tlblog.LogEvent(\"GtwyMgr\", \"Delete\", \"info\", \"end\")\n\t}\n\treturn nil\n}", "func (client IdentityClient) deleteIdpGroupMapping(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/identityProviders/{identityProviderId}/groupMappings/{mappingId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteIdpGroupMappingResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client IdentityClient) deleteDynamicGroup(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/dynamicGroups/{dynamicGroupId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteDynamicGroupResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client *Client) DeleteDegradeControlWithCallback(request *DeleteDegradeControlRequest, callback func(response *DeleteDegradeControlResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteDegradeControlResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteDegradeControl(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (c *Client) AttachableAccessEntityProfileDomainVmmVMWareDel(aep, domainVMWare string) error {\n\n\tme := \"AttachableAccessEntityProfileDomainVmmVMWareDel\"\n\n\trnE := rnAEP(aep)\n\trn := rnVmmDomainVMWare(domainVMWare)\n\n\tapi := \"/api/node/mo/uni/infra/\" + rnE + \".json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"infraAttEntityP\":{\"attributes\":{\"dn\":\"uni/infra/%s\",\"status\":\"modified\"},\"children\":[{\"infraRsDomP\":{\"attributes\":{\"dn\":\"uni/infra/%s/rsdomP-[uni/%s]\",\"status\":\"deleted\"}}}]}}`,\n\t\trnE, rnE, rn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}" ]
[ "0.7489635", "0.70623237", "0.628145", "0.61440516", "0.5646188", "0.55109155", "0.54183745", "0.5369351", "0.5364473", "0.53176093", "0.5313999", "0.5264016", "0.5197791", "0.5184923", "0.5144244", "0.514319", "0.5125727", "0.51196355", "0.5111975", "0.5102731", "0.5095808", "0.5083458", "0.5078314", "0.5074884", "0.5053692", "0.50381756", "0.5032474", "0.5010901", "0.49969655", "0.49849266", "0.49791816", "0.4941062", "0.49328962", "0.4930946", "0.49227843", "0.49036205", "0.48641598", "0.48224443", "0.48213255", "0.48098195", "0.47925857", "0.47786114", "0.47764456", "0.47615576", "0.47481295", "0.47382173", "0.4737539", "0.47294757", "0.47275284", "0.47231126", "0.4718473", "0.47066584", "0.47025487", "0.47011697", "0.46991196", "0.469672", "0.4672963", "0.46691936", "0.4646777", "0.46314165", "0.46304992", "0.4617905", "0.4617358", "0.46155968", "0.4608836", "0.46047664", "0.46039498", "0.45884177", "0.458758", "0.4587299", "0.45845446", "0.458154", "0.4575829", "0.45643246", "0.4562648", "0.45579022", "0.4550994", "0.45477062", "0.45477015", "0.4546677", "0.45447016", "0.4533701", "0.45155627", "0.4501975", "0.44998008", "0.4499513", "0.44983572", "0.44957456", "0.44936296", "0.44874913", "0.44826278", "0.44796172", "0.44757503", "0.44685024", "0.44579694", "0.4455051", "0.44532615", "0.44517446", "0.44512466", "0.44510937" ]
0.71831626
1
DeleteVpdGrantRuleWithChan invokes the eflo.DeleteVpdGrantRule API asynchronously
func (client *Client) DeleteVpdGrantRuleWithChan(request *DeleteVpdGrantRuleRequest) (<-chan *DeleteVpdGrantRuleResponse, <-chan error) { responseChan := make(chan *DeleteVpdGrantRuleResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.DeleteVpdGrantRule(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) DeleteVpdGrantRuleWithCallback(request *DeleteVpdGrantRuleRequest, callback func(response *DeleteVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) CreateVpdGrantRuleWithChan(request *CreateVpdGrantRuleRequest) (<-chan *CreateVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) CreateVpdGrantRuleWithCallback(request *CreateVpdGrantRuleRequest, callback func(response *CreateVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteDegradeControlWithChan(request *DeleteDegradeControlRequest) (<-chan *DeleteDegradeControlResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteDegradeControlResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteDegradeControl(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteVpdGrantRule(request *DeleteVpdGrantRuleRequest) (response *DeleteVpdGrantRuleResponse, err error) {\n\tresponse = CreateDeleteVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (s *Service) DelGrantCase(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {\n\tmr := &model.Case{}\n\tif err = json.Unmarshal(nwMsg, mr); err != nil {\n\t\tlog.Error(\"json.Unmarshal(%s) error(%v)\", string(nwMsg), err)\n\t\treturn\n\t}\n\tif mr.Status == model.CaseStatusDealing && mr.CaseType == model.JudeCaseTypePrivate {\n\t\treturn\n\t}\n\tif mr.Status == model.CaseStatusGranting || mr.Status == model.CaseStatusDealed || mr.Status == model.CaseStatusRestart {\n\t\treturn\n\t}\n\tcids := []int64{mr.ID}\n\t// 删除冻结和停止发放中的cid\n\tif err = s.dao.DelGrantCase(c, cids); err != nil {\n\t\tlog.Error(\"s.dao.SetMIDCaseGrant(%d) error(%v)\", mr.ID, err)\n\t}\n\tlog.Info(\"cid(%d) status(%d) remove hash list on start_time(%s) and end_time(%s)\", mr.ID, mr.Status, mr.Stime, mr.Etime)\n\treturn\n}", "func CreateDeleteVpdGrantRuleRequest() (request *DeleteVpdGrantRuleRequest) {\n\trequest = &DeleteVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"DeleteVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateDeleteVpdGrantRuleResponse() (response *DeleteVpdGrantRuleResponse) {\n\tresponse = &DeleteVpdGrantRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) DeleteDegradeControlWithCallback(request *DeleteDegradeControlRequest, callback func(response *DeleteDegradeControlResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteDegradeControlResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteDegradeControl(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) {\n\n\tvar attr string\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP {\n\t\tattr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId\n\t} else {\n\t\tattr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tif err = n.RemoveXattr(ctx, attr, acquireLock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *Client) DeleteLiveDelayConfigWithChan(request *DeleteLiveDelayConfigRequest) (<-chan *DeleteLiveDelayConfigResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteLiveDelayConfigResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteLiveDelayConfig(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteVccRouteEntryWithChan(request *DeleteVccRouteEntryRequest) (<-chan *DeleteVccRouteEntryResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteVccRouteEntryResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteVccRouteEntry(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (ngw *NatGateways) deleteAsync(wg *sync.WaitGroup, errChan chan error, ngwID *string) {\n\tdefer wg.Done()\n\n\tinput := &ec2.DeleteNatGatewayInput{NatGatewayId: ngwID}\n\t_, err := ngw.Client.DeleteNatGateway(input)\n\n\t// Record status of this resource\n\te := report.Entry{\n\t\tIdentifier: aws.StringValue(ngwID),\n\t\tResourceType: \"NAT Gateway\",\n\t\tError: err,\n\t}\n\treport.Record(e)\n\n\terrChan <- err\n}", "func (client *Client) DeregisterDelegatedAdministratorWithChan(request *DeregisterDelegatedAdministratorRequest) (<-chan *DeregisterDelegatedAdministratorResponse, <-chan error) {\n\tresponseChan := make(chan *DeregisterDelegatedAdministratorResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeregisterDelegatedAdministrator(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteVccRouteEntryWithCallback(request *DeleteVccRouteEntryRequest, callback func(response *DeleteVccRouteEntryResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVccRouteEntryResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVccRouteEntry(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteVideoDnaGroupWithCallback(request *DeleteVideoDnaGroupRequest, callback func(response *DeleteVideoDnaGroupResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVideoDnaGroupResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVideoDnaGroup(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteVideoDnaGroupWithChan(request *DeleteVideoDnaGroupRequest) (<-chan *DeleteVideoDnaGroupResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteVideoDnaGroupResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteVideoDnaGroup(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (as AccountStorage) DeleteGrantPubKey(ctx sdk.Context, me types.AccountKey, pubKey crypto.PubKey) {\n\tstore := ctx.KVStore(as.key)\n\tstore.Delete(getGrantPubKeyKey(me, pubKey))\n\treturn\n}", "func (pa *PermAccess) DeletePerms(opt *dauth.PermFind) <-chan dlib.Result {\n\tch := make(chan dlib.Result, 256)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\trows, err := pa.DBS.Query(\n\t\t\t\"SELECT delete_perms($1, $2, $3) AS num\",\n\t\t\topt.ID,\n\t\t\topt.Service,\n\t\t\topt.Name)\n\t\tif err != nil {\n\t\t\tch <- dlib.Result{Err: err}\n\t\t\treturn\n\t\t}\n\n\t\tdefer rows.Close()\n\t\tn := 0\n\t\tfor rows.Next() {\n\t\t\tr := struct{ Num int }{Num: 0}\n\t\t\tif err := rows.Scan(&r.Num); err != nil {\n\t\t\t\tch <- dlib.Result{Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tn += r.Num\n\t\t}\n\n\t\tch <- dlib.Result{Num: n, Err: nil}\n\t}()\n\n\treturn ch\n}", "func deleteOIDCProviderAsync(wg *sync.WaitGroup, errChan chan error, svc *iam.IAM, providerARN *string) {\n\tdefer wg.Done()\n\n\t_, err := svc.DeleteOpenIDConnectProvider(&iam.DeleteOpenIDConnectProviderInput{OpenIDConnectProviderArn: providerARN})\n\terrChan <- err\n}", "func (client *Client) DeleteLiveDelayConfigWithCallback(request *DeleteLiveDelayConfigRequest, callback func(response *DeleteLiveDelayConfigResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteLiveDelayConfigResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteLiveDelayConfig(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func deleteRule(c *cli.Context) error {\n\n\truleid, err := hex.DecodeString(c.String(\"id\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[x] Incorrect ruleid format. \")\n\t}\n\n\terr = mapi.ExecuteMailRuleDelete(ruleid)\n\tif err == nil {\n\t\tfmt.Println(\"[*] Rule deleted. Fetching list of remaining rules...\")\n\t\trules, er := mapi.DisplayRules()\n\t\tif er != nil {\n\t\t\treturn er\n\t\t}\n\t\tfmt.Printf(\"[+] Found %d rules\\n\", len(rules))\n\t\tfor _, v := range rules {\n\t\t\tfmt.Printf(\"Rule: %s RuleID: %x\\n\", string(v.RuleName), v.RuleID)\n\t\t}\n\t\treturn nil\n\t}\n\treturn err\n}", "func (client WorkloadNetworksClient) DeleteDhcpResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client *Client) DeleteCorpGroupWithChan(request *DeleteCorpGroupRequest) (<-chan *DeleteCorpGroupResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteCorpGroupResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteCorpGroup(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeregisterDelegatedAdministratorWithCallback(request *DeregisterDelegatedAdministratorRequest, callback func(response *DeregisterDelegatedAdministratorResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeregisterDelegatedAdministratorResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeregisterDelegatedAdministrator(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteServiceTimeConfigWithChan(request *DeleteServiceTimeConfigRequest) (<-chan *DeleteServiceTimeConfigResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteServiceTimeConfigResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteServiceTimeConfig(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *Client) DeleteCorpGroupWithCallback(request *DeleteCorpGroupRequest, callback func(response *DeleteCorpGroupResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteCorpGroupResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteCorpGroup(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func HandleDeleteEventingTriggerRule(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tvars := mux.Vars(r)\n\t\truleName := vars[\"id\"]\n\t\tprojectID := vars[\"project\"]\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-trigger\", \"modify\", map[string]string{\"project\": projectID, \"id\": ruleName})\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, nil)\n\t\tstatus, err := syncMan.SetDeleteEventingRule(ctx, projectID, ruleName, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, status, w)\n\t}\n}", "func (client *Client) DeleteApDeviceWithChan(request *DeleteApDeviceRequest) (<-chan *DeleteApDeviceResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteApDeviceResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteApDevice(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func deleteMulticastAllowPolicy(ovnNBClient goovn.Client, ns string, nsInfo *namespaceInfo) error {\n\tportGroupHash := hashedPortGroup(ns)\n\n\terr := deleteMulticastACLs(ns, portGroupHash, nsInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_ = nsInfo.updateNamespacePortGroup(ovnNBClient, ns)\n\treturn nil\n}", "func (c *managementServiceClient) DeactivateProjectGrantUserGrant(ctx context.Context, in *ProjectGrantUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/DeactivateProjectGrantUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (client *Client) DeleteCasterEpisodeGroupWithChan(request *DeleteCasterEpisodeGroupRequest) (<-chan *DeleteCasterEpisodeGroupResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteCasterEpisodeGroupResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteCasterEpisodeGroup(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteCasterEpisodeGroupWithCallback(request *DeleteCasterEpisodeGroupRequest, callback func(response *DeleteCasterEpisodeGroupResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteCasterEpisodeGroupResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteCasterEpisodeGroup(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func handleMsgDeleteAllowance(ctx sdk.Context, k keeper.Keeper, msg types.MsgDeleteAllowance) (*sdk.Result, error) {\n\tif !k.AllowanceExists(ctx, msg.ID) {\n\t\t// replace with ErrKeyNotFound for 0.39+\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, msg.ID)\n\t}\n\tif !msg.Creator.Equals(k.GetAllowanceOwner(ctx, msg.ID)) {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, \"Incorrect Owner\")\n\t}\n\n\tk.DeleteAllowance(ctx, msg.ID)\n\treturn &sdk.Result{}, nil\n}", "func (hd *Datapath) DeleteTCPProxyPolicy(tcp *netproto.TCPProxyPolicy, vrf *netproto.Vrf) error {\n\t// This will ensure that only one datapath config will be active at a time. This is a temporary restriction\n\t// to ensure that HAL will use a single config thread , this will be removed prior to FCS to allow parallel configs to go through.\n\t// TODO Remove Global Locking\n\thd.Lock()\n\tdefer hd.Unlock()\n\tvrfKey := &halproto.VrfKeyHandle{\n\t\tKeyOrHandle: &halproto.VrfKeyHandle_VrfId{\n\t\t\tVrfId: vrf.Status.VrfID,\n\t\t},\n\t}\n\n\ttcpProxyPolicyDelReq := &halproto.TcpProxyRuleDeleteRequestMsg{\n\t\tRequest: []*halproto.TcpProxyRuleDeleteRequest{\n\t\t\t{\n\t\t\t\tKeyOrHandle: &halproto.TcpProxyRuleKeyHandle{\n\t\t\t\t\tKeyOrHandle: &halproto.TcpProxyRuleKeyHandle_RuleKey{\n\t\t\t\t\t\tRuleKey: &halproto.TcpProxyRuleKey{\n\t\t\t\t\t\t\tTcpProxyRuleId: tcp.Status.TCPProxyPolicyID,\n\t\t\t\t\t\t\tVrfKeyOrHandle: vrfKey,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif hd.Kind == \"hal\" {\n\t\tresp, err := hd.Hal.TCPProxyPolicyClient.TcpProxyRuleDelete(context.Background(), tcpProxyPolicyDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting TCPProxy Policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tif resp.Response[0].ApiStatus != halproto.ApiStatus_API_STATUS_OK {\n\t\t\tlog.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t\treturn fmt.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t}\n\t} else {\n\t\t_, err := hd.Hal.TCPProxyPolicyClient.TcpProxyRuleDelete(context.Background(), tcpProxyPolicyDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting TCPProxy Policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (client *Client) RemoveUserAnalyzerWithChan(request *RemoveUserAnalyzerRequest) (<-chan *RemoveUserAnalyzerResponse, <-chan error) {\n\tresponseChan := make(chan *RemoveUserAnalyzerResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.RemoveUserAnalyzer(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *managementServiceClient) DeactivateProjectUserGrant(ctx context.Context, in *ProjectUserGrantID, opts ...grpc.CallOption) (*UserGrant, error) {\n\tout := new(UserGrant)\n\terr := c.cc.Invoke(ctx, \"/caos.zitadel.management.api.v1.ManagementService/DeactivateProjectUserGrant\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}", "func (client FirewallPolicyRuleGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client *Client) RevokeOperatorWithChan(request *RevokeOperatorRequest) (<-chan *RevokeOperatorResponse, <-chan error) {\n\tresponseChan := make(chan *RevokeOperatorResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.RevokeOperator(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func deleteDenyPolicy(w io.Writer, projectID, policyID string) error {\n\t// projectID := \"your_project_id\"\n\t// policyID := \"your_policy_id\"\n\n\tctx := context.Background()\n\tpoliciesClient, err := iam.NewPoliciesClient(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewPoliciesClient: %w\", err)\n\t}\n\tdefer policiesClient.Close()\n\n\t// Each deny policy is attached to an organization, folder, or project.\n\t// To work with deny policies, specify the attachment point.\n\t//\n\t// Its format can be one of the following:\n\t// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID\n\t// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID\n\t// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID\n\t//\n\t// The attachment point is identified by its URL-encoded resource name. Hence, replace\n\t// the \"/\" with \"%%2F\".\n\tattachmentPoint := fmt.Sprintf(\n\t\t\"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s\",\n\t\tprojectID,\n\t)\n\n\treq := &iampb.DeletePolicyRequest{\n\t\t// Construct the full path of the policy.\n\t\t// Its format is: \"policies/ATTACHMENT_POINT/denypolicies/POLICY_ID\"\n\t\tName: fmt.Sprintf(\"policies/%s/denypolicies/%s\", attachmentPoint, policyID),\n\t}\n\top, err := policiesClient.DeletePolicy(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to delete policy: %w\", err)\n\t}\n\n\tpolicy, err := op.Wait(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to wait for the operation: %w\", err)\n\t}\n\n\tfmt.Fprintf(w, \"Policy %s deleted\\n\", policy.GetName())\n\n\treturn nil\n}", "func (plugin *Plugin) Del(args *cniSkel.CmdArgs) error {\n\t// Parse network configuration.\n\tnetConfig, err := config.New(args, false)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to parse netconfig from args: %v.\", err)\n\t\treturn err\n\t}\n\n\tlog.Infof(\"Executing DEL with netconfig: %+v.\", netConfig)\n\n\t// Derive names from CNI network config.\n\tpatNetNSName := fmt.Sprintf(patNetNSNameFormat, netConfig.BranchVlanID)\n\ttapBridgeName := fmt.Sprintf(tapBridgeNameFormat, netConfig.BranchVlanID)\n\ttapLinkName := args.IfName\n\ttargetNetNSName := args.Netns\n\n\t// Delete the tap link and veth pair from the target netns.\n\tplugin.deleteTapVethLinks(targetNetNSName, tapLinkName, tapBridgeName)\n\n\t// Search for the PAT network namespace.\n\tpatNetNS, err := netns.GetNetNSByName(patNetNSName)\n\tif err != nil {\n\t\t// Log and ignore the failure. DEL can be called multiple times and thus must be idempotent.\n\t\tlog.Errorf(\"Failed to find netns %s, ignoring: %v.\", patNetNSName, err)\n\t\treturn nil\n\t}\n\tlastVethLinkDeleted := false\n\n\t// In PAT network namespace...\n\terr = patNetNS.Run(func() error {\n\t\t// Check whether there are any remaining veth links connected to this bridge.\n\t\tifaces, _ := net.Interfaces()\n\t\tlog.Infof(\"Number of remaining links: %v.\", len(ifaces))\n\t\tif len(ifaces) == 4 {\n\t\t\t// Only VLAN link, bridge, dummy and loopback remain.\n\t\t\tlastVethLinkDeleted = true\n\t\t}\n\n\t\treturn nil\n\t})\n\n\t// If all veth links connected to this PAT bridge are deleted, clean up the PAT network\n\t// namespace and all virtual interfaces in it. Otherwise, leave it running.\n\tif lastVethLinkDeleted && netConfig.CleanupPATNetNS {\n\t\tlog.Infof(\"Deleting PAT network namespace: %v.\", patNetNSName)\n\t\terr = patNetNS.Close()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to delete netns: %v.\", err)\n\t\t}\n\t} else {\n\t\tlog.Infof(\"Skipping PAT netns deletion. Last veth link deleted: %t, cleanup PAT netns: %t.\",\n\t\t\tlastVethLinkDeleted, netConfig.CleanupPATNetNS)\n\t}\n\n\treturn nil\n}", "func (client GroupClient) DeleteSecretResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (rc RpcCmd) DoDel() error {\n\tcfg := config.GetConfigure()\n\trpcAddr := fmt.Sprintf(\"%s:%s\", cfg.LeaderRpcC.Addr, cfg.LeaderRpcC.Port)\n\topRequest := pb.OpRequest{\n\t\tOp: rc.Op,\n\t\tBucket: rc.Bucket,\n\t\tKey: rc.Key,\n\t\tValue: rc.Value,\n\t}\n\treply, err := NewRiotRPCClient().RPCRequest(rpcAddr, &opRequest)\n\tif reply.Status != 1 {\n\t\terr = fmt.Errorf(\"%s\", reply.Msg)\n\t}\n\treturn err\n}", "func (client WorkloadNetworksClient) DeletePortMirroringResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (oo *OmciCC) SendDeleteGemNCTP(ctx context.Context, timeout int, highPrio bool,\n\trxChan chan Message, aInstID uint16) (*me.ManagedEntity, error) {\n\ttid := oo.GetNextTid(highPrio)\n\tlogger.Debugw(ctx, \"send GemNCtp-Delete-msg:\", log.Fields{\"device-id\": oo.deviceID,\n\t\t\"SequNo\": strconv.FormatInt(int64(tid), 16),\n\t\t\"InstId\": strconv.FormatInt(int64(aInstID), 16)})\n\n\tmeParams := me.ParamData{EntityID: aInstID}\n\tmeInstance, omciErr := me.NewGemPortNetworkCtp(meParams)\n\tif omciErr.GetError() == nil {\n\t\tomciLayer, msgLayer, err := oframe.EncodeFrame(meInstance, omci.DeleteRequestType,\n\t\t\toframe.TransactionID(tid))\n\t\tif err != nil {\n\t\t\tlogger.Errorw(ctx, \"Cannot encode GemNCtp for delete\", log.Fields{\n\t\t\t\t\"Err\": err, \"device-id\": oo.deviceID})\n\t\t\t//TODO!!: refactoring improvement requested, here as an example for [VOL-3457]:\n\t\t\t// return (dual format) error code that can be used at caller for immediate error treatment\n\t\t\t// (relevant to all used sendXX() methods and their error conditions)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpkt, err := SerializeOmciLayer(ctx, omciLayer, msgLayer)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(ctx, \"Cannot serialize GemNCtp delete\", log.Fields{\n\t\t\t\t\"Err\": err, \"device-id\": oo.deviceID})\n\t\t\treturn nil, err\n\t\t}\n\n\t\tomciRxCallbackPair := CallbackPair{\n\t\t\tCbKey: tid,\n\t\t\tCbEntry: CallbackPairEntry{rxChan, oo.receiveOmciResponse, true},\n\t\t}\n\t\terr = oo.Send(ctx, pkt, timeout, CDefaultRetries, highPrio, omciRxCallbackPair)\n\t\tif err != nil {\n\t\t\tlogger.Errorw(ctx, \"Cannot send GemNCtp delete\", log.Fields{\n\t\t\t\t\"Err\": err, \"device-id\": oo.deviceID})\n\t\t\treturn nil, err\n\t\t}\n\t\tlogger.Debug(ctx, \"send GemNCtp-Delete-msg done\")\n\t\treturn meInstance, nil\n\t}\n\tlogger.Errorw(ctx, \"Cannot generate GemNCtp Instance for delete\", log.Fields{\n\t\t\"Err\": omciErr.GetError(), \"device-id\": oo.deviceID})\n\treturn nil, omciErr.GetError()\n}", "func handleMsgDeleteProfile(ctx sdk.Context, keeper Keeper, msg types.MsgDeleteProfile) (*sdk.Result, error) {\n\tprofile, found := keeper.GetProfile(ctx, msg.Creator)\n\n\tif !found {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest,\n\t\t\tfmt.Sprintf(\"No profile associated with this address: %s\", msg.Creator))\n\t}\n\n\tkeeper.DeleteProfile(ctx, profile.Creator, profile.Moniker)\n\n\tcreateEvent := sdk.NewEvent(\n\t\ttypes.EventTypeProfileDeleted,\n\t\tsdk.NewAttribute(types.AttributeProfileMoniker, profile.Moniker),\n\t\tsdk.NewAttribute(types.AttributeProfileCreator, profile.Creator.String()),\n\t)\n\n\tctx.EventManager().EmitEvent(createEvent)\n\n\tresult := sdk.Result{\n\t\tData: keeper.Cdc.MustMarshalBinaryLengthPrefixed(profile.Moniker),\n\t\tEvents: ctx.EventManager().Events(),\n\t}\n\n\treturn &result, nil\n}", "func (l KustoPoolDatabasePrincipalAssignmentsClientDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (KustoPoolDatabasePrincipalAssignmentsClientDeleteResponse, error) {\n\trespType := KustoPoolDatabasePrincipalAssignmentsClientDeleteResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (manager *Manager) onDeleteEgressPolicy(policy *Policy) {\n\tconfigID := ParseCEGPConfigID(policy)\n\n\tmanager.Lock()\n\tdefer manager.Unlock()\n\n\tlogger := log.WithField(logfields.CiliumEgressGatewayPolicyName, configID.Name)\n\n\tif manager.policyConfigs[configID] == nil {\n\t\tlogger.Warn(\"Can't delete CiliumEgressGatewayPolicy: policy not found\")\n\t}\n\n\tlogger.Debug(\"Deleted CiliumEgressGatewayPolicy\")\n\n\tdelete(manager.policyConfigs, configID)\n\n\tmanager.setEventBitmap(eventDeletePolicy)\n\tmanager.reconciliationTrigger.TriggerWithReason(\"policy deleted\")\n}", "func (client *Client) DeleteApDeviceWithCallback(request *DeleteApDeviceRequest, callback func(response *DeleteApDeviceResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteApDeviceResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteApDevice(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (self *PolicyAgent) DelRule(rule *OfnetPolicyRule, ret *bool) error {\n\tlog.Infof(\"Received DelRule: %+v\", rule)\n\n\t// Gte the rule\n\tself.mutex.Lock()\n\tdefer self.mutex.Unlock()\n\tcache := self.Rules[rule.RuleId]\n\tif cache == nil {\n\t\tlog.Errorf(\"Could not find rule: %+v\", rule)\n\t\treturn errors.New(\"rule not found\")\n\t}\n\n\t// Delete the Flow\n\terr := cache.flow.Delete()\n\tif err != nil {\n\t\tlog.Errorf(\"Error deleting flow: %+v. Err: %v\", rule, err)\n\t}\n\n\t// Delete the rule from cache\n\tdelete(self.Rules, rule.RuleId)\n\n\treturn nil\n}", "func ExecProjectWebhookDeleteMutation(client graphql.Client, id string) error {\n\tvariables := make(graphql.Variables)\n\tvariables[\"id\"] = id\n\tvar sb strings.Builder\n\tsb.WriteString(\"mutation GoProjectWebhookDeleteMutation($id: String!) {\\n\")\n\tsb.WriteString(\"\\twork {\\n\")\n\tsb.WriteString(\"\\t\\tdeleteProjectWebhook(_id: $id)\\n\")\n\tsb.WriteString(\"\\t}\\n\")\n\tsb.WriteString(\"}\\n\")\n\tvar res interface{}\n\tif err := client.Mutate(sb.String(), variables, &res); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *StanServer) handleChannelDelete(c *channel) {\n\tdelete := false\n\tcs := s.channels\n\tcs.Lock()\n\ta := c.activity\n\tif a.preventDelete || a.deleteInProgress || c.ss.hasActiveSubs() {\n\t\tif s.debug {\n\t\t\ts.log.Debugf(\"Channel %q cannot be deleted: preventDelete=%v inProgress=%v hasActiveSubs=%v\",\n\t\t\t\tc.name, a.preventDelete, a.deleteInProgress, c.ss.hasActiveSubs())\n\t\t}\n\t\tc.stopDeleteTimer()\n\t} else {\n\t\telapsed := time.Since(a.last)\n\t\tif elapsed >= a.maxInactivity {\n\t\t\tif s.debug {\n\t\t\t\ts.log.Debugf(\"Channel %q is being deleted\", c.name)\n\t\t\t}\n\t\t\tc.stopDeleteTimer()\n\t\t\t// Leave in map for now, but mark as deleted. If we removed before\n\t\t\t// completion of the removal, a new lookup could re-create while\n\t\t\t// in the process of deleting it.\n\t\t\ta.deleteInProgress = true\n\t\t\tdelete = true\n\t\t} else {\n\t\t\tvar next time.Duration\n\t\t\tif elapsed < 0 {\n\t\t\t\tnext = a.maxInactivity\n\t\t\t} else {\n\t\t\t\t// elapsed < a.maxInactivity\n\t\t\t\tnext = a.maxInactivity - elapsed\n\t\t\t}\n\t\t\tif s.debug {\n\t\t\t\ts.log.Debugf(\"Channel %q cannot be deleted now, reset timer to fire in %v\",\n\t\t\t\t\tc.name, next)\n\t\t\t}\n\t\t\tc.resetDeleteTimer(next)\n\t\t}\n\t}\n\tcs.Unlock()\n\tif delete {\n\t\tif testDeleteChannel {\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t\tif s.isClustered {\n\t\t\ts.replicateDeleteChannel(c)\n\t\t} else {\n\t\t\ts.processDeleteChannel(c.name)\n\t\t}\n\t}\n}", "func DelNat44AddressPool(first, last []byte, vrf uint32, twiceNat bool, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\treturn handleNat44AddressPool(first, last, vrf, twiceNat, false, vppChan, stopwatch)\n}", "func (client *WANPPPConnection1) DeletePortMappingCtx(\n\tctx context.Context,\n\tNewRemoteHost string,\n\tNewExternalPort uint16,\n\tNewProtocol string,\n) (err error) {\n\t// Request structure.\n\trequest := &struct {\n\t\tNewRemoteHost string\n\t\tNewExternalPort string\n\t\tNewProtocol string\n\t}{}\n\t// BEGIN Marshal arguments into request.\n\n\tif request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {\n\t\treturn\n\t}\n\tif request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {\n\t\treturn\n\t}\n\tif request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {\n\t\treturn\n\t}\n\t// END Marshal arguments into request.\n\n\t// Response structure.\n\tresponse := interface{}(nil)\n\n\t// Perform the SOAP call.\n\tif err = client.SOAPClient.PerformActionCtx(ctx, URN_WANPPPConnection_1, \"DeletePortMapping\", request, response); err != nil {\n\t\treturn\n\t}\n\n\t// BEGIN Unmarshal arguments from response.\n\n\t// END Unmarshal arguments from response.\n\treturn\n}", "func (client WorkloadNetworksClient) DeleteVMGroupResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client *Client) RedeployDedicatedHostWithCallback(request *RedeployDedicatedHostRequest, callback func(response *RedeployDedicatedHostResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RedeployDedicatedHostResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RedeployDedicatedHost(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (am *AutogitManager) Delete(\n\tctx context.Context, dstTLF *libkbfs.TlfHandle, dstDir string,\n\trepo, branchName string) (doneCh <-chan struct{}, err error) {\n\tam.log.CDebugf(ctx, \"Autogit delete request for %s/%s:%s\",\n\t\tdstTLF.GetCanonicalPath(), dstDir, repo, branchName)\n\tdefer func() {\n\t\tam.deferLog.CDebugf(ctx, \"Delete request processed: %+v\", err)\n\t}()\n\n\treq := deleteReq{\n\t\tdstTLF, dstDir, repo, branchName, make(chan struct{}),\n\t}\n\n\tselect {\n\tcase am.deleteQueue.In() <- req:\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n\treturn req.doneCh, nil\n}", "func (client *Client) RedeployDedicatedHostWithChan(request *RedeployDedicatedHostRequest) (<-chan *RedeployDedicatedHostResponse, <-chan error) {\n\tresponseChan := make(chan *RedeployDedicatedHostResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.RedeployDedicatedHost(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func SyncDeletePassCCCluster(taskID string, cluster *proto.Cluster) {\n\terr := passcc.GetCCClient().DeletePassCCCluster(cluster.ProjectID, cluster.ClusterID)\n\tif err != nil {\n\t\tblog.Errorf(\"CleanClusterDBInfoTask[%s]: DeletePassCCCluster[%s] failed: %v\", taskID, cluster.ClusterID, err)\n\t} else {\n\t\tblog.Infof(\"CleanClusterDBInfoTask[%s]: DeletePassCCCluster[%s] successful\", taskID, cluster.ClusterID)\n\t}\n}", "func deleteChannel(t *testing.T, kafkaClient kafkaclientset.KafkaChannelInterface, name string) {\n\tt.Helper()\n\n\terr := kafkaClient.Delete(name, &v1.DeleteOptions{})\n\tswitch {\n\tcase errors.IsGone(err):\n\tcase errors.IsNotFound(err):\n\t\tt.Logf(\"tried to delete Kafka channel: %s but it was already deleted\", name)\n\tcase err != nil:\n\t\tt.Fatalf(\"cannot delete Kafka channel %v, Error: %v\", name, err)\n\tdefault:\n\t\tt.Logf(\"deleted Kafka channel: %s\", name)\n\t}\n}", "func (n *Node) DeleteKeygroupTrigger(kgname, triggerNodeID string, expectError bool) {\n\tstatus, err := n.Client.RemoveTrigger(context.Background(), &client.RemoveTriggerRequest{Keygroup: kgname, TriggerId: triggerNodeID})\n\n\tif err != nil && !expectError {\n\t\tlog.Warn().Msgf(\"DeleteKeygroupTrigger: error %s\", err)\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && expectError {\n\t\tlog.Warn().Msg(\"DeleteKeygroupTrigger: Expected Error bot got no error\")\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && status.Status == client.EnumStatus_ERROR && !expectError {\n\t\tlog.Warn().Msgf(\"DeleteKeygroupTrigger: error %s with status %s\", err, status.Status)\n\t\tn.Errors++\n\t}\n}", "func (nat *NATCloud) ensureDeleteDNATRule(natProvider *NATClient, dnatRule *DNATRule, natGatewayId string) error {\n\tklog.V(4).Infoln(\"Delete the DNAT Rule when the node is not ready\", dnatRule.FloatingIpAddress+\":\"+fmt.Sprint(dnatRule.ExternalServicePort))\n\terr := natProvider.DeleteDNATRule(dnatRule.Id, natGatewayId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.Poll(100*time.Millisecond, 5*time.Second, func() (bool, error) {\n\t\treturn !nat.checkDNATRuleById(natProvider, dnatRule.Id), nil\n\t})\n}", "func (db *Permstore) DelPerm(perm *model.Perm) error {\n\tvar _, err = db.Exec(rebind(permDeleteStmt), perm.ID)\n\treturn err\n}", "func (client WorkloadNetworksClient) DeleteDhcpSender(req *http.Request) (future WorkloadNetworksDeleteDhcpFuture, err error) {\n\tvar resp *http.Response\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = func(client WorkloadNetworksClient) (ar autorest.Response, err error) {\n\t\tvar done bool\n\t\tdone, err = future.DoneWithContext(context.Background(), client)\n\t\tif err != nil {\n\t\t\terr = autorest.NewErrorWithError(err, \"avs.WorkloadNetworksDeleteDhcpFuture\", \"Result\", future.Response(), \"Polling failure\")\n\t\t\treturn\n\t\t}\n\t\tif !done {\n\t\t\terr = azure.NewAsyncOpIncompleteError(\"avs.WorkloadNetworksDeleteDhcpFuture\")\n\t\t\treturn\n\t\t}\n\t\tar.Response = future.Response()\n\t\treturn\n\t}\n\treturn\n}", "func (client WorkloadNetworksClient) DeletePortMirroringSender(req *http.Request) (future WorkloadNetworksDeletePortMirroringFuture, err error) {\n\tvar resp *http.Response\n\tresp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))\n\tif err != nil {\n\t\treturn\n\t}\n\tvar azf azure.Future\n\tazf, err = azure.NewFutureFromResponse(resp)\n\tfuture.FutureAPI = &azf\n\tfuture.Result = func(client WorkloadNetworksClient) (ar autorest.Response, err error) {\n\t\tvar done bool\n\t\tdone, err = future.DoneWithContext(context.Background(), client)\n\t\tif err != nil {\n\t\t\terr = autorest.NewErrorWithError(err, \"avs.WorkloadNetworksDeletePortMirroringFuture\", \"Result\", future.Response(), \"Polling failure\")\n\t\t\treturn\n\t\t}\n\t\tif !done {\n\t\t\terr = azure.NewAsyncOpIncompleteError(\"avs.WorkloadNetworksDeletePortMirroringFuture\")\n\t\t\treturn\n\t\t}\n\t\tar.Response = future.Response()\n\t\treturn\n\t}\n\treturn\n}", "func (client *RoleAssignmentsClient) deleteByBillingAccountHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingAccountResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingAccountResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingAccountResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingAccountHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingAccountResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingAccountResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingAccountResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s *ClusterAgentsService) RevokeAgentToken(pid interface{}, aid int, id int, options ...RequestOptionFunc) (*Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi := fmt.Sprintf(\"projects/%s/cluster_agents/%d/tokens/%d\", PathEscape(project), aid, id)\n\n\treq, err := s.client.NewRequest(http.MethodDelete, uri, nil, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(req, nil)\n}", "func DelNat44IdentityMapping(ctx *IdentityMappingContext, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\treturn handleNat44IdentityMapping(ctx, false, vppChan, stopwatch)\n}", "func (w *ServerInterfaceWrapper) DeleteSecretChannel(ctx echo.Context) error {\n\tvar err error\n\t// ------------- Path parameter \"id\" -------------\n\tvar id int\n\n\terr = runtime.BindStyledParameter(\"simple\", false, \"id\", ctx.Param(\"id\"), &id)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf(\"Invalid format for parameter id: %s\", err))\n\t}\n\n\tctx.Set(\"OAuth.Scopes\", []string{\"\"})\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.DeleteSecretChannel(ctx, id)\n\treturn err\n}", "func (l VirtualNetworkGatewayNatRulesClientDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (VirtualNetworkGatewayNatRulesClientDeleteResponse, error) {\n\trespType := VirtualNetworkGatewayNatRulesClientDeleteResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (api *API) TeamsDeleteRule(ctx context.Context, accountID string, ruleId string) error {\n\turi := fmt.Sprintf(\"/accounts/%s/gateway/rules/%s\", accountID, ruleId)\n\n\t_, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *RedisDL) deleteToken() error {\n\t_, err := r.client.Del(r.opt.Key).Result()\n\treturn err\n}", "func (a *HyperflexApiService) DeleteHyperflexProxySettingPolicy(ctx context.Context, moid string) ApiDeleteHyperflexProxySettingPolicyRequest {\n\treturn ApiDeleteHyperflexProxySettingPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func podDeleteAllowMulticastPolicy(ovnNBClient goovn.Client, ns, name, uuid string) error {\n\treturn deleteFromPortGroup(ovnNBClient, hashedPortGroup(ns), name, uuid)\n}", "func (l KustoPoolPrincipalAssignmentsClientDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (KustoPoolPrincipalAssignmentsClientDeleteResponse, error) {\n\trespType := KustoPoolPrincipalAssignmentsClientDeleteResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (client *Client) SetDcdnDomainCSRCertificateWithChan(request *SetDcdnDomainCSRCertificateRequest) (<-chan *SetDcdnDomainCSRCertificateResponse, <-chan error) {\n\tresponseChan := make(chan *SetDcdnDomainCSRCertificateResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.SetDcdnDomainCSRCertificate(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func deleteOp(ctx context.Context, c *messaging.Client, fb wasabee.FirebaseCmd) error {\n\tdata := map[string]string{\n\t\t\"gid\": string(fb.Gid),\n\t\t\"msg\": fb.Msg,\n\t\t\"cmd\": fb.Cmd.String(),\n\t}\n\n\ttokens, err := fb.Gid.FirebaseTokens()\n\tif err != nil {\n\t\twasabee.Log.Error(err)\n\t\treturn err\n\t}\n\tgenericMulticast(ctx, c, data, tokens)\n\treturn nil\n}", "func (*MemberRuleSettingDeleteResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{98}\n}", "func deleteConfigKey(deployConfig *gctsDeployOptions, httpClient piperhttp.Sender, configToDelete string) error {\n\tlog.Entry().Infof(\"gCTS Deploy : Delete configuration key %v\", configToDelete)\n\trequestURL := deployConfig.Host +\n\t\t\"/sap/bc/cts_abapvcs/repository/\" + deployConfig.Repository +\n\t\t\"/config/\" + configToDelete + \"?sap-client=\" + deployConfig.Client\n\n\trequestURL, urlErr := addQueryToURL(requestURL, deployConfig.QueryParameters)\n\n\tif urlErr != nil {\n\n\t\treturn urlErr\n\t}\n\n\theader := make(http.Header)\n\theader.Set(\"Content-Type\", \"application/json\")\n\theader.Add(\"Accept\", \"application/json\")\n\tresp, httpErr := httpClient.SendRequest(\"DELETE\", requestURL, nil, header, nil)\n\tdefer func() {\n\t\tif resp != nil && resp.Body != nil {\n\t\t\tresp.Body.Close()\n\t\t}\n\t}()\n\tif httpErr != nil {\n\t\t_, errorDumpParseErr := parseErrorDumpFromResponseBody(resp)\n\t\tif errorDumpParseErr != nil {\n\t\t\treturn errorDumpParseErr\n\t\t}\n\t\tlog.Entry().Error(\"Failure during deletion of configuration value\")\n\t\treturn httpErr\n\t}\n\tlog.Entry().Infof(\"gCTS Deploy : Delete configuration key %v successful\", configToDelete)\n\treturn nil\n}", "func (probe *BridgeOfProbe) delRule(rule *Rule) {\n\tlogging.GetLogger().Infof(\"Rule %v deleted\", rule.UUID)\n\tg := probe.OvsOfProbe.Graph\n\tg.Lock()\n\tdefer g.Unlock()\n\n\truleNode := g.LookupFirstNode(graph.Metadata{\"UUID\": rule.UUID})\n\tif ruleNode != nil {\n\t\tg.DelNode(ruleNode)\n\t}\n}", "func (c *Client) LeafInterfacePolicyGroupDel(group string) error {\n\n\tme := \"LeafInterfacePolicyGroupDel\"\n\n\trn := rnLeafPortGroup(group)\n\n\tapi := \"/api/node/mo/uni/infra/funcprof.json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"infraFuncP\":{\"attributes\":{\"dn\":\"uni/infra/funcprof\",\"status\":\"modified\"},\"children\":[{\"infraAccPortGrp\":{\"attributes\":{\"dn\":\"uni/infra/funcprof/%s\",\"status\":\"deleted\"}}}]}}`,\n\t\trn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}", "func (_m *ComputeAPI) DeleteFirewallRule(project string, firewall string) {\n\t_m.Called(project, firewall)\n}", "func NSSAIAvailabilityDelete(responseChan chan message.HandlerResponseMessage, nfId string) {\n\n\tlogger.Nssaiavailability.Infof(\"Request received - NSSAIAvailabilityDelete\")\n\n\tvar (\n\t\tstatus int\n\t\tproblemDetails ProblemDetails\n\t)\n\n\tstatus = nssaiavailabilityDelete(nfId, &problemDetails)\n\n\tif status == http.StatusNoContent {\n\t\tresponseChan <- message.HandlerResponseMessage{\n\t\t\tHttpResponse: &http_wrapper.Response{\n\t\t\t\tHeader: nil,\n\t\t\t\tStatus: status,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tresponseChan <- message.HandlerResponseMessage{\n\t\t\tHttpResponse: &http_wrapper.Response{\n\t\t\t\tHeader: nil,\n\t\t\t\tStatus: status,\n\t\t\t\tBody: problemDetails,\n\t\t\t},\n\t\t}\n\t}\n}", "func (a *HyperflexApiService) DeleteHyperflexVcenterConfigPolicy(ctx context.Context, moid string) ApiDeleteHyperflexVcenterConfigPolicyRequest {\n\treturn ApiDeleteHyperflexVcenterConfigPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func deleteMuteRule(w io.Writer, parent string, muteConfigId string) error {\n\t// parent: Use any one of the following options:\n\t// - organizations/{organization_id}\n\t// - folders/{folder_id}\n\t// - projects/{project_id}\n\t// parent := fmt.Sprintf(\"projects/%s\", \"your-google-cloud-project-id\")\n\t//\n\t// muteConfigId: Specify the name of the mute config to delete.\n\t// muteConfigId := \"mute-config-id\"\n\tctx := context.Background()\n\tclient, err := securitycenter.NewClient(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"securitycenter.NewClient: %w\", err)\n\t}\n\tdefer client.Close()\n\n\treq := &securitycenterpb.DeleteMuteConfigRequest{\n\t\tName: fmt.Sprintf(\"%s/muteConfigs/%s\", parent, muteConfigId),\n\t}\n\n\tif err := client.DeleteMuteConfig(ctx, req); err != nil {\n\t\treturn fmt.Errorf(\"failed to delete Muteconfig: %w\", err)\n\t}\n\tfmt.Fprintf(w, \"Mute rule deleted successfully: %s\", muteConfigId)\n\treturn nil\n}", "func (c *OVClient) SubmitDeleteProfile(p ServerProfile) (t *Task, err error) {\n\tvar (\n\t\turi = p.URI.String()\n\t)\n\n\tt = t.NewProfileTask(c)\n\tt.ResetTask()\n\tlog.Debugf(\"REST : %s \\n %+v\\n\", uri, p)\n\tlog.Debugf(\"task -> %+v\", t)\n\tif uri == \"\" {\n\t\tlog.Warn(\"Unable to post delete, no uri found.\")\n\t\tt.TaskIsDone = true\n\t\treturn t, err\n\t}\n\tdata, err := c.RestAPICall(rest.DELETE, uri, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error submitting new profile request: %s\", err)\n\t\tt.TaskIsDone = true\n\t\treturn t, err\n\t}\n\n\tlog.Debugf(\"Response delete profile %s\", data)\n\tif err := json.Unmarshal(data, &t); err != nil {\n\t\tt.TaskIsDone = true\n\t\tlog.Errorf(\"Error with task un-marshal: %s\", err)\n\t\treturn t, err\n\t}\n\n\treturn t, err\n}", "func (p *plugin) cmdDeauthorize(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {\n\tp.profile.WhitelistRemove(params.String(0))\n\tproto.PrivMsg(w, r.SenderName, TextDeauthorizeDisplay, params.String(0))\n}", "func (y *YeeLight) releaseAnswerChan(id int, a *Answer) {\n\ty.idMutex.Lock()\n\tdefer y.idMutex.Unlock()\n\tc, ok := y.pendingCmds[id] // retrieving the chan of the open \"transaction\"\n\tif !ok {\n\t\ty.errs <- errors.Wrapf(ErrUnknownCommand, \"unknown %d command\", id)\n\t\treturn\n\t}\n\tif a != nil {\n\t\tc <- *a\n\t}\n\tclose(c) // transaction is successfully ended, so close its chan and delete it from pendingCmds map\n\tdelete(y.pendingCmds, id)\n}", "func (s Service) DeleteTransitionRule(ctx context.Context, docID, ruleID []byte) error {\n\treturn s.pendingDocSrv.DeleteTransitionRule(ctx, docID, ruleID)\n}", "func (client *WANIPConnection1) DeletePortMappingCtx(\n\tctx context.Context,\n\tNewRemoteHost string,\n\tNewExternalPort uint16,\n\tNewProtocol string,\n) (err error) {\n\t// Request structure.\n\trequest := &struct {\n\t\tNewRemoteHost string\n\t\tNewExternalPort string\n\t\tNewProtocol string\n\t}{}\n\t// BEGIN Marshal arguments into request.\n\n\tif request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {\n\t\treturn\n\t}\n\tif request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {\n\t\treturn\n\t}\n\tif request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {\n\t\treturn\n\t}\n\t// END Marshal arguments into request.\n\n\t// Response structure.\n\tresponse := interface{}(nil)\n\n\t// Perform the SOAP call.\n\tif err = client.SOAPClient.PerformActionCtx(ctx, URN_WANIPConnection_1, \"DeletePortMapping\", request, response); err != nil {\n\t\treturn\n\t}\n\n\t// BEGIN Unmarshal arguments from response.\n\n\t// END Unmarshal arguments from response.\n\treturn\n}", "func (a *Client) DeleteMsgVpnRestDeliveryPointRestConsumerTLSTrustedCommonName(params *DeleteMsgVpnRestDeliveryPointRestConsumerTLSTrustedCommonNameParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteMsgVpnRestDeliveryPointRestConsumerTLSTrustedCommonNameOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteMsgVpnRestDeliveryPointRestConsumerTLSTrustedCommonNameParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"deleteMsgVpnRestDeliveryPointRestConsumerTlsTrustedCommonName\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/msgVpns/{msgVpnName}/restDeliveryPoints/{restDeliveryPointName}/restConsumers/{restConsumerName}/tlsTrustedCommonNames/{tlsTrustedCommonName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteMsgVpnRestDeliveryPointRestConsumerTLSTrustedCommonNameReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*DeleteMsgVpnRestDeliveryPointRestConsumerTLSTrustedCommonNameOK), nil\n\n}", "func (c *TestClient) DeleteForwardingRule(project, region, name string) error {\n\tif c.DeleteForwardingRuleFn != nil {\n\t\treturn c.DeleteForwardingRuleFn(project, region, name)\n\t}\n\treturn c.client.DeleteForwardingRule(project, region, name)\n}", "func DeleteRule(ctx context.Context, p *Protocol, routeID routing.RouteID) error {\n\tif err := p.WritePacket(PacketDeleteRules, []routing.RouteID{routeID}); err != nil {\n\t\treturn err\n\t}\n\tvar res []routing.RouteID\n\tif err := readAndDecodePacketWithTimeout(ctx, p, &res); err != nil {\n\t\treturn err\n\t}\n\tif len(res) == 0 {\n\t\treturn errors.New(\"empty response\")\n\t}\n\treturn nil\n}", "func delPatricia(ptr patricia, bucket string, cb db.CachedBatch) {\n\tkey := ptr.hash()\n\tlogger.Debug().Hex(\"key\", key[:8]).Msg(\"del\")\n\tcb.Delete(bucket, key[:], \"failed to delete key = %x\", key)\n}", "func (client *Client) UnAssignPrivateIpAddressWithChan(request *UnAssignPrivateIpAddressRequest) (<-chan *UnAssignPrivateIpAddressResponse, <-chan error) {\n\tresponseChan := make(chan *UnAssignPrivateIpAddressResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.UnAssignPrivateIpAddress(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (n *noopRules) Grant(rule *Rule) error {\n\treturn nil\n}", "func (h *distroIDDeleteHandler) Run(ctx context.Context) gimlet.Responder {\n\t_, err := h.sc.FindDistroById(h.distroID)\n\tif err != nil {\n\t\treturn gimlet.MakeJSONErrorResponder(errors.Wrapf(err, \"Database error for find() by distro id '%s'\", h.distroID))\n\t}\n\n\terr = h.sc.DeleteDistroById(h.distroID)\n\tif err != nil {\n\t\treturn gimlet.MakeJSONErrorResponder(errors.Wrapf(err, \"Database error for remove() by distro id '%s'\", h.distroID))\n\t}\n\n\treturn gimlet.NewJSONResponse(struct{}{})\n}" ]
[ "0.7585028", "0.63448346", "0.5797064", "0.5475028", "0.54170793", "0.53912616", "0.5266579", "0.5227858", "0.5227255", "0.5184082", "0.49702325", "0.4959252", "0.48021874", "0.47766876", "0.47660303", "0.4763217", "0.4746066", "0.47404018", "0.47138152", "0.46389297", "0.46302208", "0.46208656", "0.46004236", "0.45952728", "0.45857286", "0.45485792", "0.453198", "0.4531599", "0.45163885", "0.45161146", "0.45086628", "0.44982213", "0.44782412", "0.44774768", "0.44652444", "0.4464058", "0.44377485", "0.43988606", "0.4376063", "0.43638083", "0.43598336", "0.43455356", "0.43396294", "0.43253106", "0.43163583", "0.42911476", "0.42821074", "0.4274701", "0.42677358", "0.42473835", "0.42404324", "0.42339846", "0.42120025", "0.42012995", "0.42009664", "0.419985", "0.419882", "0.41909754", "0.41866252", "0.4176861", "0.4174301", "0.4172707", "0.4154687", "0.41545832", "0.41515356", "0.4150736", "0.41498753", "0.41465825", "0.41311464", "0.41217044", "0.41202137", "0.41187024", "0.41078582", "0.41021794", "0.4092408", "0.4086493", "0.40823036", "0.40733203", "0.40720674", "0.40716788", "0.407079", "0.40696973", "0.40679738", "0.4067792", "0.40621227", "0.40543818", "0.4048754", "0.403789", "0.40362617", "0.40351352", "0.40321696", "0.40236112", "0.40088168", "0.40038168", "0.40029827", "0.3999157", "0.3996123", "0.39934108", "0.39928997", "0.39919174" ]
0.8069158
0
DeleteVpdGrantRuleWithCallback invokes the eflo.DeleteVpdGrantRule API asynchronously
func (client *Client) DeleteVpdGrantRuleWithCallback(request *DeleteVpdGrantRuleRequest, callback func(response *DeleteVpdGrantRuleResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DeleteVpdGrantRuleResponse var err error defer close(result) response, err = client.DeleteVpdGrantRule(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *Client) DeleteVpdGrantRuleWithChan(request *DeleteVpdGrantRuleRequest) (<-chan *DeleteVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) CreateVpdGrantRuleWithCallback(request *CreateVpdGrantRuleRequest, callback func(response *CreateVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteVpdGrantRule(request *DeleteVpdGrantRuleRequest) (response *DeleteVpdGrantRuleResponse, err error) {\n\tresponse = CreateDeleteVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateDeleteVpdGrantRuleResponse() (response *DeleteVpdGrantRuleResponse) {\n\tresponse = &DeleteVpdGrantRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteVpdGrantRuleRequest() (request *DeleteVpdGrantRuleRequest) {\n\trequest = &DeleteVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"DeleteVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *Client) DeleteVccRouteEntryWithCallback(request *DeleteVccRouteEntryRequest, callback func(response *DeleteVccRouteEntryResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVccRouteEntryResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVccRouteEntry(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteDegradeControlWithCallback(request *DeleteDegradeControlRequest, callback func(response *DeleteDegradeControlResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteDegradeControlResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteDegradeControl(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) CreateVpdGrantRuleWithChan(request *CreateVpdGrantRuleRequest) (<-chan *CreateVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteVideoDnaGroupWithCallback(request *DeleteVideoDnaGroupRequest, callback func(response *DeleteVideoDnaGroupResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVideoDnaGroupResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVideoDnaGroup(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteLiveDelayConfigWithCallback(request *DeleteLiveDelayConfigRequest, callback func(response *DeleteLiveDelayConfigResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteLiveDelayConfigResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteLiveDelayConfig(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func HandleDeleteEventingTriggerRule(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\n\t\tvars := mux.Vars(r)\n\t\truleName := vars[\"id\"]\n\t\tprojectID := vars[\"project\"]\n\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-trigger\", \"modify\", map[string]string{\"project\": projectID, \"id\": ruleName})\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, nil)\n\t\tstatus, err := syncMan.SetDeleteEventingRule(ctx, projectID, ruleName, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, status, w)\n\t}\n}", "func (client *Client) DeleteApDeviceWithCallback(request *DeleteApDeviceRequest, callback func(response *DeleteApDeviceResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteApDeviceResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteApDevice(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) DeleteCorpGroupWithCallback(request *DeleteCorpGroupRequest, callback func(response *DeleteCorpGroupResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteCorpGroupResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteCorpGroup(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client GroupClient) DeleteSecretResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client *Client) DeregisterDelegatedAdministratorWithCallback(request *DeregisterDelegatedAdministratorRequest, callback func(response *DeregisterDelegatedAdministratorResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeregisterDelegatedAdministratorResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeregisterDelegatedAdministrator(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func deleteCallback(scope *gorm.Scope) {\n\tif !scope.HasError() {\n\t\tuserID, ok := scope.Get(\"user_id\")\n\t\tif !ok {\n\t\t\tuserID = nil\n\t\t}\n\t\tvar extraOption string\n\t\tif str, ok := scope.Get(\"gorm:delete_option\"); ok {\n\t\t\textraOption = fmt.Sprint(str)\n\t\t}\n\t\tdeletedAtField, hasDeletedAtField := scope.FieldByName(\"deleted_time\")\n\t\tdeleteUserIDField, hasDeleteUserIDField := scope.FieldByName(\"DeleteUserID\")\n\t\tdVersionField, hasDVersionField := scope.FieldByName(\"d_version\")\n\n\t\tif !scope.Search.Unscoped && hasDeletedAtField && hasDVersionField && hasDeleteUserIDField {\n\t\t\tscope.Raw(fmt.Sprintf(\n\t\t\t\t\"UPDATE %v SET %v=%v,%v=%v,%v=%v%v%v\",\n\t\t\t\tscope.QuotedTableName(),\n\t\t\t\tscope.Quote(deletedAtField.DBName),\n\t\t\t\tscope.AddToVars(util.GetCurrentTime()),\n\t\t\t\tscope.Quote(deleteUserIDField.DBName),\n\t\t\t\tscope.AddToVars(userID),\n\t\t\t\tscope.Quote(dVersionField.DBName),\n\t\t\t\tscope.AddToVars(uuid.NewV4().String()),\n\t\t\t\tutil.AddExtraSpaceIfExist(scope.CombinedConditionSql()),\n\t\t\t\tutil.AddExtraSpaceIfExist(extraOption),\n\t\t\t)).Exec()\n\t\t} else {\n\t\t\tscope.Raw(fmt.Sprintf(\n\t\t\t\t\"DELETE FROM %v%v%v\",\n\t\t\t\tscope.QuotedTableName(),\n\t\t\t\tutil.AddExtraSpaceIfExist(scope.CombinedConditionSql()),\n\t\t\t\tutil.AddExtraSpaceIfExist(extraOption),\n\t\t\t)).Exec()\n\t\t}\n\t}\n}", "func (s *Service) DelGrantCase(c context.Context, nwMsg []byte, oldMsg []byte) (err error) {\n\tmr := &model.Case{}\n\tif err = json.Unmarshal(nwMsg, mr); err != nil {\n\t\tlog.Error(\"json.Unmarshal(%s) error(%v)\", string(nwMsg), err)\n\t\treturn\n\t}\n\tif mr.Status == model.CaseStatusDealing && mr.CaseType == model.JudeCaseTypePrivate {\n\t\treturn\n\t}\n\tif mr.Status == model.CaseStatusGranting || mr.Status == model.CaseStatusDealed || mr.Status == model.CaseStatusRestart {\n\t\treturn\n\t}\n\tcids := []int64{mr.ID}\n\t// 删除冻结和停止发放中的cid\n\tif err = s.dao.DelGrantCase(c, cids); err != nil {\n\t\tlog.Error(\"s.dao.SetMIDCaseGrant(%d) error(%v)\", mr.ID, err)\n\t}\n\tlog.Info(\"cid(%d) status(%d) remove hash list on start_time(%s) and end_time(%s)\", mr.ID, mr.Status, mr.Stime, mr.Etime)\n\treturn\n}", "func (nat *NATCloud) ensureDeleteDNATRule(natProvider *NATClient, dnatRule *DNATRule, natGatewayId string) error {\n\tklog.V(4).Infoln(\"Delete the DNAT Rule when the node is not ready\", dnatRule.FloatingIpAddress+\":\"+fmt.Sprint(dnatRule.ExternalServicePort))\n\terr := natProvider.DeleteDNATRule(dnatRule.Id, natGatewayId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn wait.Poll(100*time.Millisecond, 5*time.Second, func() (bool, error) {\n\t\treturn !nat.checkDNATRuleById(natProvider, dnatRule.Id), nil\n\t})\n}", "func (n *Node) DeleteGrant(ctx context.Context, g *provider.Grant, acquireLock bool) (err error) {\n\n\tvar attr string\n\tif g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_GROUP {\n\t\tattr = prefixes.GrantGroupAcePrefix + g.Grantee.GetGroupId().OpaqueId\n\t} else {\n\t\tattr = prefixes.GrantUserAcePrefix + g.Grantee.GetUserId().OpaqueId\n\t}\n\n\tif err = n.RemoveXattr(ctx, attr, acquireLock); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (_m *ComputeAPI) DeleteFirewallRule(project string, firewall string) {\n\t_m.Called(project, firewall)\n}", "func deleteRule(c *cli.Context) error {\n\n\truleid, err := hex.DecodeString(c.String(\"id\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[x] Incorrect ruleid format. \")\n\t}\n\n\terr = mapi.ExecuteMailRuleDelete(ruleid)\n\tif err == nil {\n\t\tfmt.Println(\"[*] Rule deleted. Fetching list of remaining rules...\")\n\t\trules, er := mapi.DisplayRules()\n\t\tif er != nil {\n\t\t\treturn er\n\t\t}\n\t\tfmt.Printf(\"[+] Found %d rules\\n\", len(rules))\n\t\tfor _, v := range rules {\n\t\t\tfmt.Printf(\"Rule: %s RuleID: %x\\n\", string(v.RuleName), v.RuleID)\n\t\t}\n\t\treturn nil\n\t}\n\treturn err\n}", "func (client *Client) DeleteCasterEpisodeGroupWithCallback(request *DeleteCasterEpisodeGroupRequest, callback func(response *DeleteCasterEpisodeGroupResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteCasterEpisodeGroupResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteCasterEpisodeGroup(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func DeleteRule(rule string) {\n\tdelete(customRuleFuncMap, rule)\n}", "func (manager *Manager) onDeleteEgressPolicy(policy *Policy) {\n\tconfigID := ParseCEGPConfigID(policy)\n\n\tmanager.Lock()\n\tdefer manager.Unlock()\n\n\tlogger := log.WithField(logfields.CiliumEgressGatewayPolicyName, configID.Name)\n\n\tif manager.policyConfigs[configID] == nil {\n\t\tlogger.Warn(\"Can't delete CiliumEgressGatewayPolicy: policy not found\")\n\t}\n\n\tlogger.Debug(\"Deleted CiliumEgressGatewayPolicy\")\n\n\tdelete(manager.policyConfigs, configID)\n\n\tmanager.setEventBitmap(eventDeletePolicy)\n\tmanager.reconciliationTrigger.TriggerWithReason(\"policy deleted\")\n}", "func (client FirewallPolicyRuleGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (client WorkloadNetworksClient) DeleteDhcpResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func DeleteRule(ctx context.Context, p *Protocol, routeID routing.RouteID) error {\n\tif err := p.WritePacket(PacketDeleteRules, []routing.RouteID{routeID}); err != nil {\n\t\treturn err\n\t}\n\tvar res []routing.RouteID\n\tif err := readAndDecodePacketWithTimeout(ctx, p, &res); err != nil {\n\t\treturn err\n\t}\n\tif len(res) == 0 {\n\t\treturn errors.New(\"empty response\")\n\t}\n\treturn nil\n}", "func (_m *FakeScheduleService) DeleteAlertRule(key models.AlertRuleKey) {\n\t_m.Called(key)\n}", "func (s *CertificatesService) DeleteCallback(id string) error {\n\t_, err := s.client.Delete(\"/v1/certificates/\"+id+\"/callback\", nil)\n\n\treturn err\n}", "func (s Service) DeleteTransitionRule(ctx context.Context, docID, ruleID []byte) error {\n\treturn s.pendingDocSrv.DeleteTransitionRule(ctx, docID, ruleID)\n}", "func (c *Client) LeafInterfacePolicyGroupDel(group string) error {\n\n\tme := \"LeafInterfacePolicyGroupDel\"\n\n\trn := rnLeafPortGroup(group)\n\n\tapi := \"/api/node/mo/uni/infra/funcprof.json\"\n\n\turl := c.getURL(api)\n\n\tj := fmt.Sprintf(`{\"infraFuncP\":{\"attributes\":{\"dn\":\"uni/infra/funcprof\",\"status\":\"modified\"},\"children\":[{\"infraAccPortGrp\":{\"attributes\":{\"dn\":\"uni/infra/funcprof/%s\",\"status\":\"deleted\"}}}]}}`,\n\t\trn)\n\n\tc.debugf(\"%s: url=%s json=%s\", me, url, j)\n\n\tbody, errPost := c.post(url, contentTypeJSON, bytes.NewBufferString(j))\n\tif errPost != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", me, errPost)\n\t}\n\n\tc.debugf(\"%s: reply: %s\", me, string(body))\n\n\treturn parseJSONError(body)\n}", "func (client WorkloadNetworksClient) DeleteVMGroupResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func deleteCallback(db *gorm.DB) {\n\tif db.Error != nil || db.Statement.Schema == nil {\n\t\treturn\n\t}\n\tvar extraOption string\n\tif str, ok := db.Statement.Get(\"gorm:delete_option\"); ok {\n\t\textraOption = fmt.Sprint(str)\n\t}\n\tdeletedStateField := db.Statement.Schema.LookUpField(\"DeletedState\")\n\t// hard delete\n\tif db.Statement.Unscoped || deletedStateField == nil {\n\t\tdb.Statement.AddClause(clause.Delete{})\n\t\tdb.Statement.AddClause(clause.From{Tables: []clause.Table{{Name: db.Statement.Table}}})\n\t\tdb.Statement.Build(db.Callback().Delete().Clauses...)\n\t\tdb.Exec(fmt.Sprintf(\"%v%v\", db.Statement.SQL.String(), addExtraSpaceIfExist(extraOption)))\n\t\treturn\n\t}\n\t// soft delete\n\tuserName := username(db)\n\tsets := clause.Set{clause.Assignment{Column: clause.Column{Name: deletedStateField.DBName}, Value: 1}}\n\tnow := time.Now()\n\tcols := columns{\n\t\t{Name: \"DeletedOn\", Value: now}, {Name: \"DeletedBy\", Value: userName},\n\t\t{Name: \"ModifiedOn\", Value: now}, {Name: \"ModifiedBy\", Value: userName},\n\t}\n\tfor _, col := range cols {\n\t\tif field := db.Statement.Schema.LookUpField(col.Name); field != nil {\n\t\t\tsets = append(sets, clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: col.Value})\n\t\t}\n\t}\n\tdb.Statement.AddClause(sets)\n\tdb.Statement.AddClause(clause.Update{Table: clause.Table{Name: db.Statement.Table}})\n\tdb.Statement.Build(db.Callback().Update().Clauses...)\n\tdb.Exec(fmt.Sprintf(\"%v%v\", db.Statement.SQL.String(), addExtraSpaceIfExist(extraOption)))\n}", "func (s *BasePlSqlParserListener) ExitOn_delete_clause(ctx *On_delete_clauseContext) {}", "func (self *PolicyAgent) DelRule(rule *OfnetPolicyRule, ret *bool) error {\n\tlog.Infof(\"Received DelRule: %+v\", rule)\n\n\t// Gte the rule\n\tself.mutex.Lock()\n\tdefer self.mutex.Unlock()\n\tcache := self.Rules[rule.RuleId]\n\tif cache == nil {\n\t\tlog.Errorf(\"Could not find rule: %+v\", rule)\n\t\treturn errors.New(\"rule not found\")\n\t}\n\n\t// Delete the Flow\n\terr := cache.flow.Delete()\n\tif err != nil {\n\t\tlog.Errorf(\"Error deleting flow: %+v. Err: %v\", rule, err)\n\t}\n\n\t// Delete the rule from cache\n\tdelete(self.Rules, rule.RuleId)\n\n\treturn nil\n}", "func (c *TestClient) DeleteForwardingRule(project, region, name string) error {\n\tif c.DeleteForwardingRuleFn != nil {\n\t\treturn c.DeleteForwardingRuleFn(project, region, name)\n\t}\n\treturn c.client.DeleteForwardingRule(project, region, name)\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func (api *API) TeamsDeleteRule(ctx context.Context, accountID string, ruleId string) error {\n\turi := fmt.Sprintf(\"/accounts/%s/gateway/rules/%s\", accountID, ruleId)\n\n\t_, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (as AccountStorage) DeleteGrantPubKey(ctx sdk.Context, me types.AccountKey, pubKey crypto.PubKey) {\n\tstore := ctx.KVStore(as.key)\n\tstore.Delete(getGrantPubKeyKey(me, pubKey))\n\treturn\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *Client) CreateVpdGrantRule(request *CreateVpdGrantRuleRequest) (response *CreateVpdGrantRuleResponse, err error) {\n\tresponse = CreateCreateVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (probe *BridgeOfProbe) delRule(rule *Rule) {\n\tlogging.GetLogger().Infof(\"Rule %v deleted\", rule.UUID)\n\tg := probe.OvsOfProbe.Graph\n\tg.Lock()\n\tdefer g.Unlock()\n\n\truleNode := g.LookupFirstNode(graph.Metadata{\"UUID\": rule.UUID})\n\tif ruleNode != nil {\n\t\tg.DelNode(ruleNode)\n\t}\n}", "func deleteOIDCProviderAsync(wg *sync.WaitGroup, errChan chan error, svc *iam.IAM, providerARN *string) {\n\tdefer wg.Done()\n\n\t_, err := svc.DeleteOpenIDConnectProvider(&iam.DeleteOpenIDConnectProviderInput{OpenIDConnectProviderArn: providerARN})\n\terrChan <- err\n}", "func (l *Libvirt) DomainCheckpointDelete(Checkpoint DomainCheckpoint, Flags DomainCheckpointDeleteFlags) (err error) {\n\tvar buf []byte\n\n\targs := DomainCheckpointDeleteArgs {\n\t\tCheckpoint: Checkpoint,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\n\t_, err = l.requestStream(417, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (client WorkloadNetworksClient) DeletePortMirroringResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (l VirtualNetworkGatewayNatRulesClientDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (VirtualNetworkGatewayNatRulesClientDeleteResponse, error) {\n\trespType := VirtualNetworkGatewayNatRulesClientDeleteResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (sdk *MockGoSDKClient) DeleteSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) {\n\treturn nil\n}", "func (client *Client) ReleaseEipSegmentAddressWithCallback(request *ReleaseEipSegmentAddressRequest, callback func(response *ReleaseEipSegmentAddressResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *ReleaseEipSegmentAddressResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.ReleaseEipSegmentAddress(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func DeleteRule(rule AuditRule) error {\n\tclient, err := libaudit.NewAuditClient(nil)\n\tdefer client.Close()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to initialize client\")\n\t}\n\tkr, _, _, err := rule.toKernelAuditRule()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to initialize client\")\n\t}\n\tif err := client.DeleteRule(kr.toWireFormat()); err != nil {\n\t\treturn errors.Wrap(err, \"Failed to delete audit rule\")\n\t}\n\treturn nil\n}", "func (s *BasejossListener) ExitDeleteValCMD(ctx *DeleteValCMDContext) {}", "func (s *LocalTests) deleteFwRule(c *gc.C, fwRuleId string) {\n\terr := s.testClient.DeleteFirewallRule(fwRuleId)\n\tc.Assert(err, gc.IsNil)\n}", "func (client DataFlowClient) DeleteDataFlowResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (c *Client) DeleteRule(args *DeleteRuleArgs) error {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn DeleteRule(c, body)\n}", "func (ngw *NatGateways) deleteAsync(wg *sync.WaitGroup, errChan chan error, ngwID *string) {\n\tdefer wg.Done()\n\n\tinput := &ec2.DeleteNatGatewayInput{NatGatewayId: ngwID}\n\t_, err := ngw.Client.DeleteNatGateway(input)\n\n\t// Record status of this resource\n\te := report.Entry{\n\t\tIdentifier: aws.StringValue(ngwID),\n\t\tResourceType: \"NAT Gateway\",\n\t\tError: err,\n\t}\n\treport.Record(e)\n\n\terrChan <- err\n}", "func DeleteACLRule(r *http.Request, target ACLTarget, actor ACLActor) (err error) {\n\n\t// get service\n\ts := service.Providers.MustService(r, \"ACLRule\")\n\n\t// delete the rules\n\tconds := service.NewConds()\n\tconds.Add(\"target\", string(target))\n\tconds.Add(\"actor\", string(actor))\n\ts.Delete(conds)\n\n\treturn\n}", "func (l KustoPoolDatabasePrincipalAssignmentsClientDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (KustoPoolDatabasePrincipalAssignmentsClientDeleteResponse, error) {\n\trespType := KustoPoolDatabasePrincipalAssignmentsClientDeleteResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func (s *SmartContract) DeleteVerificationPolicy(ctx contractapi.TransactionContextInterface, verificationPolicyID string) error {\n\t// Check if the caller has network admin privileges\n\tif isAdmin, err := wutils.IsClientNetworkAdmin(ctx); err != nil {\n\t\treturn fmt.Errorf(\"Admin client check error: %s\", err)\n\t} else if !isAdmin {\n\t\treturn fmt.Errorf(\"Caller not a network admin; access denied\")\n\t}\n\n\tverificationPolicyKey, err := ctx.GetStub().CreateCompositeKey(verificationPolicyObjectType, []string{verificationPolicyID})\n\tbytes, err := ctx.GetStub().GetState(verificationPolicyKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif bytes == nil {\n\t\treturn fmt.Errorf(\"VerificationPolicy with id: %s does not exist\", verificationPolicyID)\n\t}\n\terr = ctx.GetStub().DelState(verificationPolicyKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to delete asset %s: %v\", verificationPolicyKey, err)\n\t}\n\n\treturn nil\n}", "func (c *AuditClient) DeleteRule(rule []byte) error {\n\tmsg := syscall.NetlinkMessage{\n\t\tHeader: syscall.NlMsghdr{\n\t\t\tType: uint16(auparse.AUDIT_DEL_RULE),\n\t\t\tFlags: syscall.NLM_F_REQUEST | syscall.NLM_F_ACK,\n\t\t},\n\t\tData: rule,\n\t}\n\n\t// Send AUDIT_DEL_RULE message to the kernel.\n\tseq, err := c.Netlink.Send(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed sending delete rule request: %w\", err)\n\t}\n\n\t_, err = c.getReply(seq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get ACK to rule delete request: %w\", err)\n\t}\n\n\treturn nil\n}", "func (se *StorageEndpoint) DeleteRule(ruleKey string) error {\n\treturn se.Remove(ruleKeyPath(ruleKey))\n}", "func (m *AuthorizationServerPolicyRuleResource) DeleteAuthorizationServerPolicyRule(ctx context.Context, authServerId string, policyId string, ruleId string) (*Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/authorizationServers/%v/policies/%v/rules/%v\", authServerId, policyId, ruleId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := m.client.requestExecutor.Do(ctx, req, nil)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\treturn resp, nil\n}", "func (p *metadataService) deleteMessageWithValidator(clientID string, validator func(*base.Message) bool) {\n}", "func deleteMulticastAllowPolicy(ovnNBClient goovn.Client, ns string, nsInfo *namespaceInfo) error {\n\tportGroupHash := hashedPortGroup(ns)\n\n\terr := deleteMulticastACLs(ns, portGroupHash, nsInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_ = nsInfo.updateNamespacePortGroup(ovnNBClient, ns)\n\treturn nil\n}", "func (client *Client) DeleteServiceTimeConfigWithCallback(request *DeleteServiceTimeConfigRequest, callback func(response *DeleteServiceTimeConfigResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteServiceTimeConfigResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteServiceTimeConfig(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (s *BasejossListener) ExitFuncDp(ctx *FuncDpContext) {}", "func (client *FirewallRulesClient) ResumeDelete(ctx context.Context, token string) (FirewallRulesDeletePollerResponse, error) {\n\tpt, err := armcore.NewLROPollerFromResumeToken(\"FirewallRulesClient.Delete\", token, client.con.Pipeline(), client.deleteHandleError)\n\tif err != nil {\n\t\treturn FirewallRulesDeletePollerResponse{}, err\n\t}\n\tpoller := &firewallRulesDeletePoller{\n\t\tpt: pt,\n\t}\n\tresp, err := poller.Poll(ctx)\n\tif err != nil {\n\t\treturn FirewallRulesDeletePollerResponse{}, err\n\t}\n\tresult := FirewallRulesDeletePollerResponse{\n\t\tRawResponse: resp,\n\t}\n\tresult.Poller = poller\n\tresult.PollUntilDone = func(ctx context.Context, frequency time.Duration) (FirewallRulesDeleteResponse, error) {\n\t\treturn poller.pollUntilDone(ctx, frequency)\n\t}\n\treturn result, nil\n}", "func DelNat44AddressPool(first, last []byte, vrf uint32, twiceNat bool, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\treturn handleNat44AddressPool(first, last, vrf, twiceNat, false, vppChan, stopwatch)\n}", "func (client WorkloadNetworksClient) DeleteSegmentResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (s *BasePlSqlParserListener) ExitGrant_statement(ctx *Grant_statementContext) {}", "func DeleteRule(table Table, chain Chain, args ...string) error {\n\tfullArgs := makeFullArgs(table, opDeleteRule, chain, args...)\n\tout, err := run(cmd, fullArgs...)\n\tif err != nil {\n\t\treturn trace.Wrap(err, \"failed to delete %v chain %v rule %v: %s\", table, chain, args, out)\n\t}\n\treturn nil\n}", "func (s *BasePlSqlParserListener) ExitDelete_statement(ctx *Delete_statementContext) {}", "func (l *Libvirt) DomainEventCallbackDeviceRemoved() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(333, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (a *HyperflexApiService) DeleteHyperflexProxySettingPolicy(ctx context.Context, moid string) ApiDeleteHyperflexProxySettingPolicyRequest {\n\treturn ApiDeleteHyperflexProxySettingPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (c *restClient) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGuestPolicyRequest, opts ...gax.CallOption) error {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1beta/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\treturn gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"DELETE\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\t// Returns nil if there is no error, otherwise wraps\n\t\t// the response code and body into a non-nil error\n\t\treturn googleapi.CheckResponse(httpRsp)\n\t}, opts...)\n}", "func (client PatternClient) DeletePatternResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (rule *NamespacesEventhubsAuthorizationRule) ValidateDelete() (admission.Warnings, error) {\n\tvalidations := rule.deleteValidations()\n\tvar temp any = rule\n\tif runtimeValidator, ok := temp.(genruntime.Validator); ok {\n\t\tvalidations = append(validations, runtimeValidator.DeleteValidations()...)\n\t}\n\treturn genruntime.ValidateDelete(validations)\n}", "func (l VirtualNetworkRulesDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (VirtualNetworkRulesDeleteResponse, error) {\n\trespType := VirtualNetworkRulesDeleteResponse{}\n\tresp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil)\n\tif err != nil {\n\t\treturn respType, err\n\t}\n\trespType.RawResponse = resp\n\treturn respType, nil\n}", "func DelNat44StaticMappingLb(ctx *StaticMappingLbContext, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\treturn handleNat44StaticMappingLb(ctx, false, vppChan, stopwatch)\n}", "func (hd *Datapath) DeleteTCPProxyPolicy(tcp *netproto.TCPProxyPolicy, vrf *netproto.Vrf) error {\n\t// This will ensure that only one datapath config will be active at a time. This is a temporary restriction\n\t// to ensure that HAL will use a single config thread , this will be removed prior to FCS to allow parallel configs to go through.\n\t// TODO Remove Global Locking\n\thd.Lock()\n\tdefer hd.Unlock()\n\tvrfKey := &halproto.VrfKeyHandle{\n\t\tKeyOrHandle: &halproto.VrfKeyHandle_VrfId{\n\t\t\tVrfId: vrf.Status.VrfID,\n\t\t},\n\t}\n\n\ttcpProxyPolicyDelReq := &halproto.TcpProxyRuleDeleteRequestMsg{\n\t\tRequest: []*halproto.TcpProxyRuleDeleteRequest{\n\t\t\t{\n\t\t\t\tKeyOrHandle: &halproto.TcpProxyRuleKeyHandle{\n\t\t\t\t\tKeyOrHandle: &halproto.TcpProxyRuleKeyHandle_RuleKey{\n\t\t\t\t\t\tRuleKey: &halproto.TcpProxyRuleKey{\n\t\t\t\t\t\t\tTcpProxyRuleId: tcp.Status.TCPProxyPolicyID,\n\t\t\t\t\t\t\tVrfKeyOrHandle: vrfKey,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif hd.Kind == \"hal\" {\n\t\tresp, err := hd.Hal.TCPProxyPolicyClient.TcpProxyRuleDelete(context.Background(), tcpProxyPolicyDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting TCPProxy Policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\tif resp.Response[0].ApiStatus != halproto.ApiStatus_API_STATUS_OK {\n\t\t\tlog.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t\treturn fmt.Errorf(\"HAL returned non OK status. %v\", resp.Response[0].ApiStatus.String())\n\t\t}\n\t} else {\n\t\t_, err := hd.Hal.TCPProxyPolicyClient.TcpProxyRuleDelete(context.Background(), tcpProxyPolicyDelReq)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error deleting TCPProxy Policy. Err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func DeleteRule(id string) int {\n\tvar rule database.Rule\n\tdb.DB.Where(\"id = ? \", id).First(&rule)\n\tdb.DB.Where(\"id = ?\", id).Delete(&database.Rule{})\n\treturn rule.ReleaseID\n}", "func DelNat44StaticMapping(ctx *StaticMappingContext, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\tif ctx.AddressOnly {\n\t\treturn handleNat44StaticMapping(ctx, false, true, vppChan, stopwatch)\n\t}\n\treturn handleNat44StaticMapping(ctx, false, false, vppChan, stopwatch)\n}", "func (a *SyncApiService) DeleteSyncRule(ctx context.Context, syncRuleId string) ( *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/platform/3/sync/rules/{SyncRuleId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"SyncRuleId\"+\"}\", fmt.Sprintf(\"%v\", syncRuleId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\treturn localVarHttpResponse, err\n}", "func handleMsgDeleteProfile(ctx sdk.Context, keeper Keeper, msg types.MsgDeleteProfile) (*sdk.Result, error) {\n\tprofile, found := keeper.GetProfile(ctx, msg.Creator)\n\n\tif !found {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest,\n\t\t\tfmt.Sprintf(\"No profile associated with this address: %s\", msg.Creator))\n\t}\n\n\tkeeper.DeleteProfile(ctx, profile.Creator, profile.Moniker)\n\n\tcreateEvent := sdk.NewEvent(\n\t\ttypes.EventTypeProfileDeleted,\n\t\tsdk.NewAttribute(types.AttributeProfileMoniker, profile.Moniker),\n\t\tsdk.NewAttribute(types.AttributeProfileCreator, profile.Creator.String()),\n\t)\n\n\tctx.EventManager().EmitEvent(createEvent)\n\n\tresult := sdk.Result{\n\t\tData: keeper.Cdc.MustMarshalBinaryLengthPrefixed(profile.Moniker),\n\t\tEvents: ctx.EventManager().Events(),\n\t}\n\n\treturn &result, nil\n}", "func (client *Client) DeleteResourceInstancesWithCallback(request *DeleteResourceInstancesRequest, callback func(response *DeleteResourceInstancesResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteResourceInstancesResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteResourceInstances(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) RemoveUserAnalyzerWithCallback(request *RemoveUserAnalyzerRequest, callback func(response *RemoveUserAnalyzerResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *RemoveUserAnalyzerResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.RemoveUserAnalyzer(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (a *HyperflexApiService) DeleteHyperflexVcenterConfigPolicy(ctx context.Context, moid string) ApiDeleteHyperflexVcenterConfigPolicyRequest {\n\treturn ApiDeleteHyperflexVcenterConfigPolicyRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (client *Client) DescribeDispatchRuleWithCallback(request *DescribeDispatchRuleRequest, callback func(response *DescribeDispatchRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DescribeDispatchRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DescribeDispatchRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client GroupClient) DeleteSecretPreparer(accountName string, databaseName string, secretName string) (*http.Request, error) {\n\turlParameters := map[string]interface{}{\n\t\t\"accountName\": accountName,\n\t\t\"adlaCatalogDnsSuffix\": client.AdlaCatalogDNSSuffix,\n\t}\n\n\tpathParameters := map[string]interface{}{\n\t\t\"databaseName\": autorest.Encode(\"path\", databaseName),\n\t\t\"secretName\": autorest.Encode(\"path\", secretName),\n\t}\n\n\tconst APIVersion = \"2015-10-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithCustomBaseURL(\"https://{accountName}.{adlaCatalogDnsSuffix}\", urlParameters),\n\t\tautorest.WithPathParameters(\"/catalog/usql/databases/{databaseName}/secrets/{secretName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare(&http.Request{})\n}", "func (c *OVClient) SubmitDeleteProfile(p ServerProfile) (t *Task, err error) {\n\tvar (\n\t\turi = p.URI.String()\n\t)\n\n\tt = t.NewProfileTask(c)\n\tt.ResetTask()\n\tlog.Debugf(\"REST : %s \\n %+v\\n\", uri, p)\n\tlog.Debugf(\"task -> %+v\", t)\n\tif uri == \"\" {\n\t\tlog.Warn(\"Unable to post delete, no uri found.\")\n\t\tt.TaskIsDone = true\n\t\treturn t, err\n\t}\n\tdata, err := c.RestAPICall(rest.DELETE, uri, nil)\n\tif err != nil {\n\t\tlog.Errorf(\"Error submitting new profile request: %s\", err)\n\t\tt.TaskIsDone = true\n\t\treturn t, err\n\t}\n\n\tlog.Debugf(\"Response delete profile %s\", data)\n\tif err := json.Unmarshal(data, &t); err != nil {\n\t\tt.TaskIsDone = true\n\t\tlog.Errorf(\"Error with task un-marshal: %s\", err)\n\t\treturn t, err\n\t}\n\n\treturn t, err\n}", "func Delete(c *golangsdk.ServiceClient, policyID, ruleID string) (r DeleteResult) {\n\treqOpt := &golangsdk.RequestOpts{\n\t\tMoreHeaders: RequestOpts.MoreHeaders,\n\t}\n\n\t_, r.Err = c.Delete(resourceURL(c, policyID, ruleID), reqOpt)\n\treturn\n}", "func HandleDeleteEventingSecurityRule(adminMan *admin.Manager, syncMan *syncman.Manager) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\t// Get the JWT token from header\n\t\ttoken := utils.GetTokenFromHeader(r)\n\t\tdefer utils.CloseTheCloser(r.Body)\n\n\t\tvars := mux.Vars(r)\n\t\tprojectID := vars[\"project\"]\n\t\tevType := vars[\"id\"]\n\n\t\tctx, cancel := context.WithTimeout(r.Context(), time.Duration(utils.DefaultContextTime)*time.Second)\n\t\tdefer cancel()\n\n\t\t// Check if the request is authorised\n\t\treqParams, err := adminMan.IsTokenValid(ctx, token, \"eventing-rule\", \"modify\", map[string]string{\"project\": projectID, \"id\": evType})\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to validate token for delete eventing rules\", err, nil)\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, http.StatusUnauthorized, err)\n\t\t\treturn\n\t\t}\n\n\t\treqParams = utils.ExtractRequestParams(r, reqParams, nil)\n\t\tstatus, err := syncMan.SetDeleteEventingSecurityRules(ctx, projectID, evType, reqParams)\n\t\tif err != nil {\n\t\t\t_ = helpers.Logger.LogError(helpers.GetRequestID(ctx), \"Failed to delete eventing rules\", err, nil)\n\t\t\t_ = helpers.Response.SendErrorResponse(ctx, w, status, err)\n\t\t\treturn\n\t\t}\n\n\t\t_ = helpers.Response.SendOkayResponse(ctx, status, w)\n\t}\n}", "func checkDeletePolicy(t *testing.T, expError bool, tenant, policy string) {\n\terr := contivClient.PolicyDelete(tenant, policy)\n\tif err != nil && !expError {\n\t\tt.Fatalf(\"Error deleting policy %s/%s. Err: %v\", tenant, policy, err)\n\t} else if err == nil && expError {\n\t\tt.Fatalf(\"Delete policy %s/%s succeded while expecing error\", tenant, policy)\n\t} else if err == nil {\n\t\t// verify policy is gone\n\t\t_, err := contivClient.PolicyGet(tenant, policy)\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Policy %s/%s not deleted\", tenant, policy)\n\t\t}\n\t}\n}", "func (ruleset *DnsForwardingRuleset) ValidateDelete() (admission.Warnings, error) {\n\tvalidations := ruleset.deleteValidations()\n\tvar temp any = ruleset\n\tif runtimeValidator, ok := temp.(genruntime.Validator); ok {\n\t\tvalidations = append(validations, runtimeValidator.DeleteValidations()...)\n\t}\n\treturn genruntime.ValidateDelete(validations)\n}", "func (client *WANPPPConnection1) DeletePortMappingCtx(\n\tctx context.Context,\n\tNewRemoteHost string,\n\tNewExternalPort uint16,\n\tNewProtocol string,\n) (err error) {\n\t// Request structure.\n\trequest := &struct {\n\t\tNewRemoteHost string\n\t\tNewExternalPort string\n\t\tNewProtocol string\n\t}{}\n\t// BEGIN Marshal arguments into request.\n\n\tif request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {\n\t\treturn\n\t}\n\tif request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {\n\t\treturn\n\t}\n\tif request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {\n\t\treturn\n\t}\n\t// END Marshal arguments into request.\n\n\t// Response structure.\n\tresponse := interface{}(nil)\n\n\t// Perform the SOAP call.\n\tif err = client.SOAPClient.PerformActionCtx(ctx, URN_WANPPPConnection_1, \"DeletePortMapping\", request, response); err != nil {\n\t\treturn\n\t}\n\n\t// BEGIN Unmarshal arguments from response.\n\n\t// END Unmarshal arguments from response.\n\treturn\n}", "func (n *Node) DeleteKeygroupTrigger(kgname, triggerNodeID string, expectError bool) {\n\tstatus, err := n.Client.RemoveTrigger(context.Background(), &client.RemoveTriggerRequest{Keygroup: kgname, TriggerId: triggerNodeID})\n\n\tif err != nil && !expectError {\n\t\tlog.Warn().Msgf(\"DeleteKeygroupTrigger: error %s\", err)\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && expectError {\n\t\tlog.Warn().Msg(\"DeleteKeygroupTrigger: Expected Error bot got no error\")\n\t\tn.Errors++\n\t\treturn\n\t}\n\n\tif err == nil && status.Status == client.EnumStatus_ERROR && !expectError {\n\t\tlog.Warn().Msgf(\"DeleteKeygroupTrigger: error %s with status %s\", err, status.Status)\n\t\tn.Errors++\n\t}\n}", "func (client *Client) DeleteTransitRouterCidrWithCallback(request *DeleteTransitRouterCidrRequest, callback func(response *DeleteTransitRouterCidrResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteTransitRouterCidrResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteTransitRouterCidr(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (h *hnsw) deleteEntrypoint(node *vertex, denyList helpers.AllowList) error {\n\tif h.isOnlyNode(node, denyList) {\n\t\t// no point in finding another entrypoint if this is the only node\n\t\treturn nil\n\t}\n\n\tnode.Lock()\n\tlevel := node.level\n\tnode.Unlock()\n\n\tnewEntrypoint, level := h.findNewEntrypoint(denyList, level)\n\n\th.Lock()\n\th.entryPointID = newEntrypoint\n\th.currentMaximumLayer = level\n\th.Unlock()\n\th.commitLog.SetEntryPointWithMaxLayer(newEntrypoint, level)\n\n\treturn nil\n}", "func (client RosettaNetProcessConfigurationsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func (c *SiteReplicationSys) PeerBucketDeleteHandler(ctx context.Context, bucket string, forceDelete bool) error {\n\tc.RLock()\n\tdefer c.RUnlock()\n\tif !c.enabled {\n\t\treturn errSRNotEnabled\n\t}\n\n\tobjAPI := newObjectLayerFn()\n\tif objAPI == nil {\n\t\treturn errServerNotInitialized\n\t}\n\n\tif globalDNSConfig != nil {\n\t\tif err := globalDNSConfig.Delete(bucket); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr := objAPI.DeleteBucket(ctx, bucket, DeleteBucketOptions{Force: forceDelete})\n\tif err != nil {\n\t\tif globalDNSConfig != nil {\n\t\t\tif err2 := globalDNSConfig.Put(bucket); err2 != nil {\n\t\t\t\tlogger.LogIf(ctx, fmt.Errorf(\"Unable to restore bucket DNS entry %w, please fix it manually\", err2))\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tglobalNotificationSys.DeleteBucketMetadata(ctx, bucket)\n\n\treturn nil\n}", "func (c *Client) DeleteAccessRule(dirBlindName string, accountName api.AccountName) error {\n\trawURL := fmt.Sprintf(pathDirRule, c.base.String(), dirBlindName, accountName)\n\terr := c.delete(rawURL, true, nil)\n\treturn errio.Error(err)\n}", "func (appPortProfile *NsxtAppPortProfile) Delete() error {\n\tendpoint := types.OpenApiPathVersion1_0_0 + types.OpenApiEndpointAppPortProfiles\n\tminimumApiVersion, err := appPortProfile.client.checkOpenApiEndpointCompatibility(endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif appPortProfile.NsxtAppPortProfile.ID == \"\" {\n\t\treturn fmt.Errorf(\"cannot delete NSX-T Application Port Profile without ID\")\n\t}\n\n\turlRef, err := appPortProfile.client.OpenApiBuildEndpoint(endpoint, appPortProfile.NsxtAppPortProfile.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = appPortProfile.client.OpenApiDeleteItem(minimumApiVersion, urlRef, nil, nil)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error deleting NSX-T Application Port Profile: %s\", err)\n\t}\n\n\treturn nil\n}" ]
[ "0.68763554", "0.6586179", "0.6053671", "0.5836633", "0.5591262", "0.5553131", "0.55327445", "0.51898825", "0.5092163", "0.49991354", "0.49571776", "0.48992956", "0.48691872", "0.48664564", "0.48612252", "0.48151034", "0.48070365", "0.47596213", "0.47545245", "0.4747927", "0.47479016", "0.4743675", "0.47414544", "0.4732655", "0.47174415", "0.471191", "0.47040746", "0.47016197", "0.46818027", "0.4628311", "0.46097013", "0.4591214", "0.45826766", "0.45661473", "0.45504", "0.4542457", "0.4525603", "0.4525277", "0.45183817", "0.44948325", "0.44844973", "0.44537684", "0.4440415", "0.44399273", "0.4429964", "0.4414776", "0.43950343", "0.439226", "0.43785307", "0.43751273", "0.43595314", "0.43444103", "0.4342478", "0.43315554", "0.43282896", "0.43200138", "0.4315451", "0.4313713", "0.43088296", "0.42899764", "0.4285126", "0.42826045", "0.42764544", "0.42725703", "0.42699915", "0.42561683", "0.42545792", "0.42450815", "0.42424354", "0.42408487", "0.42369503", "0.42358673", "0.42310306", "0.4230028", "0.42259097", "0.42227298", "0.4220041", "0.42062676", "0.41984633", "0.4196721", "0.41953367", "0.41871628", "0.41822052", "0.41712672", "0.41696078", "0.41689575", "0.41668388", "0.41658878", "0.41644794", "0.41633916", "0.41572487", "0.41533747", "0.41512176", "0.41499555", "0.41475105", "0.41435137", "0.41427907", "0.4139142", "0.41338283", "0.41310453" ]
0.8300928
0
CreateDeleteVpdGrantRuleRequest creates a request to invoke DeleteVpdGrantRule API
func CreateDeleteVpdGrantRuleRequest() (request *DeleteVpdGrantRuleRequest) { request = &DeleteVpdGrantRuleRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("eflo", "2022-05-30", "DeleteVpdGrantRule", "eflo", "openAPI") request.Method = requests.POST return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateDeleteVpdGrantRuleResponse() (response *DeleteVpdGrantRuleResponse) {\n\tresponse = &DeleteVpdGrantRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateCreateVpdGrantRuleRequest() (request *CreateVpdGrantRuleRequest) {\n\trequest = &CreateVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"CreateVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *Client) DeleteVpdGrantRule(request *DeleteVpdGrantRuleRequest) (response *DeleteVpdGrantRuleResponse, err error) {\n\tresponse = CreateDeleteVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (client *Client) DeleteVpdGrantRuleWithCallback(request *DeleteVpdGrantRuleRequest, callback func(response *DeleteVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *WCFRelaysClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysClientDeleteAuthorizationRuleOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif authorizationRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter authorizationRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{authorizationRuleName}\", url.PathEscape(authorizationRuleName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, firewallRuleName string, options *FirewallRulesBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serverName == \"\" {\n\t\treturn nil, errors.New(\"parameter serverName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serverName}\", url.PathEscape(serverName))\n\tif firewallRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter firewallRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{firewallRuleName}\", url.PathEscape(firewallRuleName))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2017-12-01\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *Client) DeleteVpdGrantRuleWithChan(request *DeleteVpdGrantRuleRequest) (<-chan *DeleteVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (c *IPSecVPNClient) NewDeleteVPNTunnelRequest() *DeleteVPNTunnelRequest {\n\treq := &DeleteVPNTunnelRequest{}\n\n\t// setup request with client config\n\tc.Client.SetupRequest(req)\n\n\t// setup retryable with default retry policy (retry for non-create action and common error)\n\treq.SetRetryable(true)\n\treturn req\n}", "func (client *TagRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, monitorName string, ruleSetName string, options *TagRulesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Dynatrace.Observability/monitors/{monitorName}/tagRules/{ruleSetName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif monitorName == \"\" {\n\t\treturn nil, errors.New(\"parameter monitorName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{monitorName}\", url.PathEscape(monitorName))\n\tif ruleSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleSetName}\", url.PathEscape(ruleSetName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-27\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func CreateDeleteDegradeControlRequest() (request *DeleteDegradeControlRequest) {\n\trequest = &DeleteDegradeControlRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Edas\", \"2017-08-01\", \"DeleteDegradeControl\", \"/pop/v5/degradeControl\", \"Edas\", \"openAPI\")\n\trequest.Method = requests.DELETE\n\treturn\n}", "func (client *AlertProcessingRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, alertProcessingRuleName string, options *AlertProcessingRulesClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{alertProcessingRuleName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif alertProcessingRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter alertProcessingRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{alertProcessingRuleName}\", url.PathEscape(alertProcessingRuleName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-08-08\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *RoleAssignmentsClient) deleteCreateRequest(ctx context.Context, vaultBaseURL string, scope string, roleAssignmentName string, options *RoleAssignmentsDeleteOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}\"\n\tif scope == \"\" {\n\t\treturn nil, errors.New(\"parameter scope cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\tif roleAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter roleAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleAssignmentName}\", url.PathEscape(roleAssignmentName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.3-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func NewNatRuleDeleteCommand(authenticatingCommand *GenericCommand) *AuthenticationRequiringCommand {\n\treturn &AuthenticationRequiringCommand{\n\t\tGenericCommand: GenericCommand{\n\t\t\tName: \"NatRuleDelete\",\n\t\t\tDescription: \"Deletes an IPV4 NAT rule configured for the specified ID\",\n\t\t\tArgNames: []string{\"id\"},\n\t\t\tArgTypes: []string{\"int\"},\n\t\t\tExec: func(context *CommandContext) {\n\t\t\t\tid, err := context.GetIntArg(0)\n\t\t\t\tif err != nil {\n\t\t\t\t\tparseErr := errors.New(\"ID must be a numeric value\")\n\t\t\t\t\tcontext.SetResult(nil, parseErr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontext.SetResult(nil, service.GetHub().NatRuleDelete(id))\n\t\t\t},\n\t\t\tPostExec: func(context *CommandContext) {\n\t\t\t\tif !context.IsError() {\n\t\t\t\t\tfmt.Printf(\"NAT rule successfully deleted\\n\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tAuthenticatingCommand: authenticatingCommand,\n\t}\n}", "func (client *PolicyDefinitionsClient) deleteCreateRequest(ctx context.Context, policyDefinitionName string, options *PolicyDefinitionsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}\"\n\tif policyDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter policyDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{policyDefinitionName}\", url.PathEscape(policyDefinitionName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *RoleDefinitionsClient) deleteCreateRequest(ctx context.Context, scope string, roleDefinitionID string, options *RoleDefinitionsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\tif roleDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter roleDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleDefinitionId}\", url.PathEscape(roleDefinitionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (c *CloudWatchEvents) DeleteRuleRequest(input *DeleteRuleInput) (req *request.Request, output *DeleteRuleOutput) {\n\top := &request.Operation{\n\t\tName: opDeleteRule,\n\t\tHTTPMethod: \"POST\",\n\t\tHTTPPath: \"/\",\n\t}\n\n\tif input == nil {\n\t\tinput = &DeleteRuleInput{}\n\t}\n\n\treq = c.newRequest(op, input, output)\n\treq.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler)\n\treq.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)\n\toutput = &DeleteRuleOutput{}\n\treq.Data = output\n\treturn\n}", "func (client *Client) CreateVpdGrantRule(request *CreateVpdGrantRuleRequest) (response *CreateVpdGrantRuleResponse, err error) {\n\tresponse = CreateCreateVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func (client *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cacheName string, ruleName string, options *FirewallRulesClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cache/redis/{cacheName}/firewallRules/{ruleName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif cacheName == \"\" {\n\t\treturn nil, errors.New(\"parameter cacheName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{cacheName}\", url.PathEscape(cacheName))\n\tif ruleName == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleName}\", url.PathEscape(ruleName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *RegistrationDefinitionsClient) deleteCreateRequest(ctx context.Context, registrationDefinitionID string, scope string, options *RegistrationDefinitionsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}\"\n\tif registrationDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter registrationDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registrationDefinitionId}\", url.PathEscape(registrationDefinitionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *SQLResourcesClient) deleteSQLRoleAssignmentCreateRequest(ctx context.Context, roleAssignmentID string, resourceGroupName string, accountName string, options *SQLResourcesClientBeginDeleteSQLRoleAssignmentOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleAssignments/{roleAssignmentId}\"\n\tif roleAssignmentID == \"\" {\n\t\treturn nil, errors.New(\"parameter roleAssignmentID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleAssignmentId}\", url.PathEscape(roleAssignmentID))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func CreateDeleteVideoDnaGroupRequest() (request *DeleteVideoDnaGroupRequest) {\n\trequest = &DeleteVideoDnaGroupRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Green\", \"2018-05-09\", \"DeleteVideoDnaGroup\", \"/green/video/dna/group/delete\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *HCRPAssignmentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, guestConfigurationAssignmentName string, machineName string, options *HCRPAssignmentsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/machines/{machineName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif guestConfigurationAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter guestConfigurationAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{guestConfigurationAssignmentName}\", url.PathEscape(guestConfigurationAssignmentName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif machineName == \"\" {\n\t\treturn nil, errors.New(\"parameter machineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{machineName}\", url.PathEscape(machineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-25\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *MetricAlertsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ruleName string, options *MetricAlertsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/metricAlerts/{ruleName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif ruleName == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleName}\", url.PathEscape(ruleName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-03-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *KeyVaultClient) purgeDeletedCertificateCreateRequest(ctx context.Context, vaultBaseURL string, certificateName string, options *KeyVaultClientPurgeDeletedCertificateOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/deletedcertificates/{certificate-name}\"\n\tif certificateName == \"\" {\n\t\treturn nil, errors.New(\"parameter certificateName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{certificate-name}\", url.PathEscape(certificateName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *Client) CreateVpdGrantRuleWithCallback(request *CreateVpdGrantRuleRequest, callback func(response *CreateVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *ActionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, ruleID string, actionID string, options *ActionsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/alertRules/{ruleId}/actions/{actionId}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif workspaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter workspaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{workspaceName}\", url.PathEscape(workspaceName))\n\tif ruleID == \"\" {\n\t\treturn nil, errors.New(\"parameter ruleID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ruleId}\", url.PathEscape(ruleID))\n\tif actionID == \"\" {\n\t\treturn nil, errors.New(\"parameter actionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{actionId}\", url.PathEscape(actionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-10-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func NewDeleteaspecificPeeringRuleRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/peeringrules/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func CreateDeleteCorpGroupRequest() (request *DeleteCorpGroupRequest) {\n\trequest = &DeleteCorpGroupRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Vcs\", \"2020-05-15\", \"DeleteCorpGroup\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *KeyVaultClient) deleteCertificateCreateRequest(ctx context.Context, vaultBaseURL string, certificateName string, options *KeyVaultClientDeleteCertificateOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/certificates/{certificate-name}\"\n\tif certificateName == \"\" {\n\t\treturn nil, errors.New(\"parameter certificateName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{certificate-name}\", url.PathEscape(certificateName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (r *DeviceComplianceScheduledActionForRuleRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (client *LocalRulestacksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, localRulestackName string, options *LocalRulestacksClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/PaloAltoNetworks.Cloudngfw/localRulestacks/{localRulestackName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif localRulestackName == \"\" {\n\t\treturn nil, errors.New(\"parameter localRulestackName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{localRulestackName}\", url.PathEscape(localRulestackName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-29\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *KeyVaultClient) deleteSecretCreateRequest(ctx context.Context, vaultBaseURL string, secretName string, options *KeyVaultClientDeleteSecretOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/secrets/{secret-name}\"\n\tif secretName == \"\" {\n\t\treturn nil, errors.New(\"parameter secretName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{secret-name}\", url.PathEscape(secretName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *PermissionBindingsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, permissionBindingName string, options *PermissionBindingsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/namespaces/{namespaceName}/permissionBindings/{permissionBindingName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif permissionBindingName == \"\" {\n\t\treturn nil, errors.New(\"parameter permissionBindingName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{permissionBindingName}\", url.PathEscape(permissionBindingName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-06-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *WebAppsClient) deleteDeploymentCreateRequest(ctx context.Context, resourceGroupName string, name string, id string, options *WebAppsDeleteDeploymentOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/deployments/{id}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif id == \"\" {\n\t\treturn nil, errors.New(\"parameter id cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{id}\", url.PathEscape(id))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *AvailabilityGroupListenersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, sqlVirtualMachineGroupName string, availabilityGroupListenerName string, options *AvailabilityGroupListenersClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachineGroups/{sqlVirtualMachineGroupName}/availabilityGroupListeners/{availabilityGroupListenerName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif sqlVirtualMachineGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter sqlVirtualMachineGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sqlVirtualMachineGroupName}\", url.PathEscape(sqlVirtualMachineGroupName))\n\tif availabilityGroupListenerName == \"\" {\n\t\treturn nil, errors.New(\"parameter availabilityGroupListenerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{availabilityGroupListenerName}\", url.PathEscape(availabilityGroupListenerName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *SQLResourcesClient) deleteSQLRoleDefinitionCreateRequest(ctx context.Context, roleDefinitionID string, resourceGroupName string, accountName string, options *SQLResourcesClientBeginDeleteSQLRoleDefinitionOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}\"\n\tif roleDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter roleDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleDefinitionId}\", url.PathEscape(roleDefinitionID))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func DeleteRule(ctx context.Context, p *Protocol, routeID routing.RouteID) error {\n\tif err := p.WritePacket(PacketDeleteRules, []routing.RouteID{routeID}); err != nil {\n\t\treturn err\n\t}\n\tvar res []routing.RouteID\n\tif err := readAndDecodePacketWithTimeout(ctx, p, &res); err != nil {\n\t\treturn err\n\t}\n\tif len(res) == 0 {\n\t\treturn errors.New(\"empty response\")\n\t}\n\treturn nil\n}", "func (client *PrivateDNSZoneGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif privateEndpointName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateEndpointName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateEndpointName}\", url.PathEscape(privateEndpointName))\n\tif privateDNSZoneGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateDNSZoneGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateDnsZoneGroupName}\", url.PathEscape(privateDNSZoneGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *WebAppsClient) deleteHostNameBindingCreateRequest(ctx context.Context, resourceGroupName string, name string, hostName string, options *WebAppsDeleteHostNameBindingOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hostNameBindings/{hostName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif hostName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *KeyVaultClient) purgeDeletedSecretCreateRequest(ctx context.Context, vaultBaseURL string, secretName string, options *KeyVaultClientPurgeDeletedSecretOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/deletedsecrets/{secret-name}\"\n\tif secretName == \"\" {\n\t\treturn nil, errors.New(\"parameter secretName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{secret-name}\", url.PathEscape(secretName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *DefenderSettingsClient) deleteCreateRequest(ctx context.Context, options *DefenderSettingsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/defenderSettings/default\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *PolicyDefinitionsClient) deleteAtManagementGroupCreateRequest(ctx context.Context, policyDefinitionName string, managementGroupID string, options *PolicyDefinitionsDeleteAtManagementGroupOptions) (*policy.Request, error) {\n\turlPath := \"/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}\"\n\tif policyDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter policyDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{policyDefinitionName}\", url.PathEscape(policyDefinitionName))\n\tif managementGroupID == \"\" {\n\t\treturn nil, errors.New(\"parameter managementGroupID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{managementGroupId}\", url.PathEscape(managementGroupID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif hostGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\tif hostName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (client *VirtualApplianceSitesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkVirtualApplianceName string, siteName string, options *VirtualApplianceSitesBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkVirtualAppliances/{networkVirtualApplianceName}/virtualApplianceSites/{siteName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{networkVirtualApplianceName}\", url.PathEscape(networkVirtualApplianceName))\n\turlPath = strings.ReplaceAll(urlPath, \"{siteName}\", url.PathEscape(siteName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-07-01\")\n\treq.URL.RawQuery = query.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *WebAppsClient) deleteHostSecretCreateRequest(ctx context.Context, resourceGroupName string, name string, keyType string, keyName string, options *WebAppsDeleteHostSecretOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/host/default/{keyType}/{keyName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif keyType == \"\" {\n\t\treturn nil, errors.New(\"parameter keyType cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{keyType}\", url.PathEscape(keyType))\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{keyName}\", url.PathEscape(keyName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (c *Client) DeleteRule(args *DeleteRuleArgs) error {\n\tjsonBytes, jsonErr := json.Marshal(args)\n\tif jsonErr != nil {\n\t\treturn jsonErr\n\t}\n\tbody, err := bce.NewBodyFromBytes(jsonBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn DeleteRule(c, body)\n}", "func (client *Client) CreateVpdGrantRuleWithChan(request *CreateVpdGrantRuleRequest) (<-chan *CreateVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func NewDeleteaspecificPeeringInboundRuleRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/peeringinboundrules/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (client *DataFlowDebugSessionClient) deleteDataFlowDebugSessionCreateRequest(ctx context.Context, request DeleteDataFlowDebugSessionRequest, options *DataFlowDebugSessionClientDeleteDataFlowDebugSessionOptions) (*policy.Request, error) {\n\turlPath := \"/deleteDataFlowDebugSession\"\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-12-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\tif err := runtime.MarshalAsJSON(req, request); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func Delete(c *golangsdk.ServiceClient, policyID, ruleID string) (r DeleteResult) {\n\treqOpt := &golangsdk.RequestOpts{\n\t\tMoreHeaders: RequestOpts.MoreHeaders,\n\t}\n\n\t_, r.Err = c.Delete(resourceURL(c, policyID, ruleID), reqOpt)\n\treturn\n}", "func (client *Client) DeleteRule(request *DeleteRuleRequest) (_result *DeleteRuleResponse, _err error) {\n\truntime := &util.RuntimeOptions{}\n\t_result = &DeleteRuleResponse{}\n\t_body, _err := client.DeleteRuleWithOptions(request, runtime)\n\tif _err != nil {\n\t\treturn _result, _err\n\t}\n\t_result = _body\n\treturn _result, _err\n}", "func (client *AgentPoolsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, kubernetesClusterName string, agentPoolName string, options *AgentPoolsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkCloud/kubernetesClusters/{kubernetesClusterName}/agentPools/{agentPoolName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif kubernetesClusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter kubernetesClusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{kubernetesClusterName}\", url.PathEscape(kubernetesClusterName))\n\tif agentPoolName == \"\" {\n\t\treturn nil, errors.New(\"parameter agentPoolName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{agentPoolName}\", url.PathEscape(agentPoolName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func CreateCreateVpdGrantRuleResponse() (response *CreateVpdGrantRuleResponse) {\n\tresponse = &CreateVpdGrantRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteVccRouteEntryRequest() (request *DeleteVccRouteEntryRequest) {\n\trequest = &DeleteVccRouteEntryRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"DeleteVccRouteEntry\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *KeyVaultClient) deleteCertificateOperationCreateRequest(ctx context.Context, vaultBaseURL string, certificateName string, options *KeyVaultClientDeleteCertificateOperationOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/certificates/{certificate-name}/pending\"\n\tif certificateName == \"\" {\n\t\treturn nil, errors.New(\"parameter certificateName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{certificate-name}\", url.PathEscape(certificateName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *IPAllocationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ipAllocationName string, options *IPAllocationsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/IpAllocations/{ipAllocationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif ipAllocationName == \"\" {\n\t\treturn nil, errors.New(\"parameter ipAllocationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{ipAllocationName}\", url.PathEscape(ipAllocationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func NewDeleteRuleFromSecurityGroupRequest(server string, id string, ruleId string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar pathParam1 string\n\n\tpathParam1, err = runtime.StyleParam(\"simple\", false, \"rule-id\", ruleId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/security-group/%s/rules/%s\", pathParam0, pathParam1)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (connection *Connection) CreateDeleteRequest(fnr Fnr) (*DeleteRequest, error) {\n\treturn NewDeleteRequestAdabas(connection.adabasToData, fnr), nil\n}", "func (client *TaskRunsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, taskRunName string, options *TaskRunsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/taskRuns/{taskRunName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif taskRunName == \"\" {\n\t\treturn nil, errors.New(\"parameter taskRunName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{taskRunName}\", url.PathEscape(taskRunName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-06-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *SchemaRegistryClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, schemaGroupName string, options *SchemaRegistryClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/schemagroups/{schemaGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif schemaGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter schemaGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{schemaGroupName}\", url.PathEscape(schemaGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-10-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *WorkspacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *WorkspacesBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif workspaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter workspaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{workspaceName}\", url.PathEscape(workspaceName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-04-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func CreateDeleteCasterEpisodeGroupRequest() (request *DeleteCasterEpisodeGroupRequest) {\n\trequest = &DeleteCasterEpisodeGroupRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"live\", \"2016-11-01\", \"DeleteCasterEpisodeGroup\", \"live\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *SourceControlConfigurationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, clusterRp string, clusterResourceName string, clusterName string, sourceControlConfigurationName string, options *SourceControlConfigurationsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif clusterRp == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterRp cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterRp}\", url.PathEscape(clusterRp))\n\tif clusterResourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterResourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterResourceName}\", url.PathEscape(clusterResourceName))\n\tif clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\tif sourceControlConfigurationName == \"\" {\n\t\treturn nil, errors.New(\"parameter sourceControlConfigurationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sourceControlConfigurationName}\", url.PathEscape(sourceControlConfigurationName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func DeleteRule(rule AuditRule) error {\n\tclient, err := libaudit.NewAuditClient(nil)\n\tdefer client.Close()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to initialize client\")\n\t}\n\tkr, _, _, err := rule.toKernelAuditRule()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to initialize client\")\n\t}\n\tif err := client.DeleteRule(kr.toWireFormat()); err != nil {\n\t\treturn errors.Wrap(err, \"Failed to delete audit rule\")\n\t}\n\treturn nil\n}", "func (client *PeeringPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, managedNetworkName string, managedNetworkPeeringPolicyName string, options *PeeringPoliciesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedNetwork/managedNetworks/{managedNetworkName}/managedNetworkPeeringPolicies/{managedNetworkPeeringPolicyName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif managedNetworkName == \"\" {\n\t\treturn nil, errors.New(\"parameter managedNetworkName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{managedNetworkName}\", url.PathEscape(managedNetworkName))\n\tif managedNetworkPeeringPolicyName == \"\" {\n\t\treturn nil, errors.New(\"parameter managedNetworkPeeringPolicyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{managedNetworkPeeringPolicyName}\", url.PathEscape(managedNetworkPeeringPolicyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-06-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileCreateRequest(ctx context.Context, billingAccountName string, billingProfileName string, billingRoleAssignmentName string, options *RoleAssignmentsClientDeleteByBillingProfileOptions) (*policy.Request, error) {\n\turlPath := \"/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}\"\n\tif billingAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingAccountName}\", url.PathEscape(billingAccountName))\n\tif billingProfileName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingProfileName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingProfileName}\", url.PathEscape(billingProfileName))\n\tif billingRoleAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingRoleAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingRoleAssignmentName}\", url.PathEscape(billingRoleAssignmentName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *SpatialAnchorsAccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *SpatialAnchorsAccountsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MixedReality/spatialAnchorsAccounts/{accountName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-03-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *ConnectedEnvironmentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, connectedEnvironmentName string, options *ConnectedEnvironmentsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.App/connectedEnvironments/{connectedEnvironmentName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif connectedEnvironmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter connectedEnvironmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{connectedEnvironmentName}\", url.PathEscape(connectedEnvironmentName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-06-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *SQLResourcesClient) deleteSQLTriggerCreateRequest(ctx context.Context, resourceGroupName string, accountName string, databaseName string, containerName string, triggerName string, options *SQLResourcesClientBeginDeleteSQLTriggerOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\tif databaseName == \"\" {\n\t\treturn nil, errors.New(\"parameter databaseName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{databaseName}\", url.PathEscape(databaseName))\n\tif containerName == \"\" {\n\t\treturn nil, errors.New(\"parameter containerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{containerName}\", url.PathEscape(containerName))\n\tif triggerName == \"\" {\n\t\treturn nil, errors.New(\"parameter triggerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{triggerName}\", url.PathEscape(triggerName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileCreateRequest(ctx context.Context, billingAccountName string, billingProfileName string, billingRoleAssignmentName string, options *RoleAssignmentsClientDeleteByBillingProfileOptions) (*policy.Request, error) {\n\turlPath := \"/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingRoleAssignments/{billingRoleAssignmentName}\"\n\tif billingAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingAccountName}\", url.PathEscape(billingAccountName))\n\tif billingProfileName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingProfileName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingProfileName}\", url.PathEscape(billingProfileName))\n\tif billingRoleAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingRoleAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingRoleAssignmentName}\", url.PathEscape(billingRoleAssignmentName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func CreateDeleteLiveDelayConfigRequest() (request *DeleteLiveDelayConfigRequest) {\n\trequest = &DeleteLiveDelayConfigRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"live\", \"2016-11-01\", \"DeleteLiveDelayConfig\", \"live\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *CustomAssessmentAutomationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, customAssessmentAutomationName string, options *CustomAssessmentAutomationsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Security/customAssessmentAutomations/{customAssessmentAutomationName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif customAssessmentAutomationName == \"\" {\n\t\treturn nil, errors.New(\"parameter customAssessmentAutomationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{customAssessmentAutomationName}\", url.PathEscape(customAssessmentAutomationName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *AFDOriginsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, profileName string, originGroupName string, originName string, options *AFDOriginsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif profileName == \"\" {\n\t\treturn nil, errors.New(\"parameter profileName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{profileName}\", url.PathEscape(profileName))\n\tif originGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter originGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{originGroupName}\", url.PathEscape(originGroupName))\n\tif originName == \"\" {\n\t\treturn nil, errors.New(\"parameter originName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{originName}\", url.PathEscape(originName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *ServersClient) deleteCreateRequest(ctx context.Context, resourceGroup string, fluidRelayServerName string, options *ServersClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.FluidRelay/fluidRelayServers/{fluidRelayServerName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroup == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroup cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroup}\", url.PathEscape(resourceGroup))\n\tif fluidRelayServerName == \"\" {\n\t\treturn nil, errors.New(\"parameter fluidRelayServerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{fluidRelayServerName}\", url.PathEscape(fluidRelayServerName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *DedicatedHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, hostGroupName string, hostName string, options *DedicatedHostsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/hostGroups/{hostGroupName}/hosts/{hostName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostGroupName}\", url.PathEscape(hostGroupName))\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\tquery := req.URL.Query()\n\tquery.Set(\"api-version\", \"2020-06-01\")\n\treq.URL.RawQuery = query.Encode()\n\treturn req, nil\n}", "func (client *ServerVulnerabilityAssessmentClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, resourceNamespace string, resourceType string, resourceName string, options *ServerVulnerabilityAssessmentClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceNamespace}/{resourceType}/{resourceName}/providers/Microsoft.Security/serverVulnerabilityAssessments/{serverVulnerabilityAssessment}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif resourceNamespace == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceNamespace cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceNamespace}\", url.PathEscape(resourceNamespace))\n\tif resourceType == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceType cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceType}\", url.PathEscape(resourceType))\n\tif resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(resourceName))\n\turlPath = strings.ReplaceAll(urlPath, \"{serverVulnerabilityAssessment}\", url.PathEscape(\"default\"))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-01-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *PacketCoreDataPlanesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, packetCoreControlPlaneName string, packetCoreDataPlaneName string, options *PacketCoreDataPlanesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MobileNetwork/packetCoreControlPlanes/{packetCoreControlPlaneName}/packetCoreDataPlanes/{packetCoreDataPlaneName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif packetCoreControlPlaneName == \"\" {\n\t\treturn nil, errors.New(\"parameter packetCoreControlPlaneName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{packetCoreControlPlaneName}\", url.PathEscape(packetCoreControlPlaneName))\n\tif packetCoreDataPlaneName == \"\" {\n\t\treturn nil, errors.New(\"parameter packetCoreDataPlaneName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{packetCoreDataPlaneName}\", url.PathEscape(packetCoreDataPlaneName))\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *CertificateOrdersClient) deleteCertificateCreateRequest(ctx context.Context, resourceGroupName string, certificateOrderName string, name string, options *CertificateOrdersClientDeleteCertificateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{certificateOrderName}/certificates/{name}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif certificateOrderName == \"\" {\n\t\treturn nil, errors.New(\"parameter certificateOrderName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{certificateOrderName}\", url.PathEscape(certificateOrderName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-09-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *VirtualMachineScaleSetVMRunCommandsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, vmScaleSetName string, instanceID string, runCommandName string, options *VirtualMachineScaleSetVMRunCommandsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/virtualMachines/{instanceId}/runCommands/{runCommandName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif vmScaleSetName == \"\" {\n\t\treturn nil, errors.New(\"parameter vmScaleSetName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{vmScaleSetName}\", url.PathEscape(vmScaleSetName))\n\tif instanceID == \"\" {\n\t\treturn nil, errors.New(\"parameter instanceID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{instanceId}\", url.PathEscape(instanceID))\n\tif runCommandName == \"\" {\n\t\treturn nil, errors.New(\"parameter runCommandName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{runCommandName}\", url.PathEscape(runCommandName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json, text/json\")\n\treturn req, nil\n}", "func CreateDeleteApDeviceRequest() (request *DeleteApDeviceRequest) {\n\trequest = &DeleteApDeviceRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"cloudesl\", \"2020-02-01\", \"DeleteApDevice\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *ClustersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/serverGroupsv2/{clusterName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-11-08\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func NewDeleteaspecificRewriteRuleRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/rewriterules/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, billingRoleAssignmentName string, options *RoleAssignmentsClientDeleteByBillingAccountOptions) (*policy.Request, error) {\n\turlPath := \"/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}\"\n\tif billingAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingAccountName}\", url.PathEscape(billingAccountName))\n\tif billingRoleAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingRoleAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingRoleAssignmentName}\", url.PathEscape(billingRoleAssignmentName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingAccountCreateRequest(ctx context.Context, billingAccountName string, billingRoleAssignmentName string, options *RoleAssignmentsClientDeleteByBillingAccountOptions) (*policy.Request, error) {\n\turlPath := \"/providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingRoleAssignments/{billingRoleAssignmentName}\"\n\tif billingAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingAccountName}\", url.PathEscape(billingAccountName))\n\tif billingRoleAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter billingRoleAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{billingRoleAssignmentName}\", url.PathEscape(billingRoleAssignmentName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (c *AuditClient) DeleteRule(rule []byte) error {\n\tmsg := syscall.NetlinkMessage{\n\t\tHeader: syscall.NlMsghdr{\n\t\t\tType: uint16(auparse.AUDIT_DEL_RULE),\n\t\t\tFlags: syscall.NLM_F_REQUEST | syscall.NLM_F_ACK,\n\t\t},\n\t\tData: rule,\n\t}\n\n\t// Send AUDIT_DEL_RULE message to the kernel.\n\tseq, err := c.Netlink.Send(msg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed sending delete rule request: %w\", err)\n\t}\n\n\t_, err = c.getReply(seq)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get ACK to rule delete request: %w\", err)\n\t}\n\n\treturn nil\n}", "func (client *CapacityReservationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, capacityReservationGroupName string, capacityReservationName string, options *CapacityReservationsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/capacityReservationGroups/{capacityReservationGroupName}/capacityReservations/{capacityReservationName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif capacityReservationGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationGroupName}\", url.PathEscape(capacityReservationGroupName))\n\tif capacityReservationName == \"\" {\n\t\treturn nil, errors.New(\"parameter capacityReservationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{capacityReservationName}\", url.PathEscape(capacityReservationName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-07-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func CreateDeleteSurveyResourcesRequest() (request *DeleteSurveyResourcesRequest) {\n\trequest = &DeleteSurveyResourcesRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"apds\", \"2022-03-31\", \"DeleteSurveyResources\", \"/okss-services/confirm-resource/destroy\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func (client *DataCollectionEndpointsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dataCollectionEndpointName string, options *DataCollectionEndpointsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif dataCollectionEndpointName == \"\" {\n\t\treturn nil, errors.New(\"parameter dataCollectionEndpointName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{dataCollectionEndpointName}\", url.PathEscape(dataCollectionEndpointName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *FactoriesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, factoryName string, options *FactoriesClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif factoryName == \"\" {\n\t\treturn nil, errors.New(\"parameter factoryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{factoryName}\", url.PathEscape(factoryName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *KeyVaultClient) deleteKeyCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, options *KeyVaultClientDeleteKeyOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}\"\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-name}\", url.PathEscape(keyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *PipelinesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, factoryName string, pipelineName string, options *PipelinesClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/pipelines/{pipelineName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif factoryName == \"\" {\n\t\treturn nil, errors.New(\"parameter factoryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{factoryName}\", url.PathEscape(factoryName))\n\tif pipelineName == \"\" {\n\t\treturn nil, errors.New(\"parameter pipelineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{pipelineName}\", url.PathEscape(pipelineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (r *DeviceCompliancePolicyGroupAssignmentRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (client *WebAppsClient) deleteSourceControlCreateRequest(ctx context.Context, resourceGroupName string, name string, options *WebAppsDeleteSourceControlOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/sourcecontrols/web\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\tif options != nil && options.AdditionalFlags != nil {\n\t\treqQP.Set(\"additionalFlags\", *options.AdditionalFlags)\n\t}\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *KeyVaultClient) deleteKeyCreateRequest(ctx context.Context, vaultBaseURL string, keyName string, options *KeyVaultClientDeleteKeyOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/keys/{key-name}\"\n\tif keyName == \"\" {\n\t\treturn nil, errors.New(\"parameter keyName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{key-name}\", url.PathEscape(keyName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.3\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *CertificateOrdersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, certificateOrderName string, options *CertificateOrdersClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CertificateRegistration/certificateOrders/{certificateOrderName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif certificateOrderName == \"\" {\n\t\treturn nil, errors.New(\"parameter certificateOrderName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{certificateOrderName}\", url.PathEscape(certificateOrderName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-09-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (rm *resourceManager) newDeleteRequestPayload(\n\tr *resource,\n) (*svcsdk.DeleteVpnConnectionInput, error) {\n\tres := &svcsdk.DeleteVpnConnectionInput{}\n\n\tif r.ko.Spec.DryRun != nil {\n\t\tres.SetDryRun(*r.ko.Spec.DryRun)\n\t}\n\tif r.ko.Status.VPNConnectionID != nil {\n\t\tres.SetVpnConnectionId(*r.ko.Status.VPNConnectionID)\n\t}\n\n\treturn res, nil\n}", "func (client *IotSecuritySolutionClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, solutionName string, options *IotSecuritySolutionClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/iotSecuritySolutions/{solutionName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif solutionName == \"\" {\n\t\treturn nil, errors.New(\"parameter solutionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{solutionName}\", url.PathEscape(solutionName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-08-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client FirewallPolicyRuleGroupsClient) DeletePreparer(ctx context.Context, resourceGroupName string, firewallPolicyName string, ruleGroupName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"firewallPolicyName\": autorest.Encode(\"path\", firewallPolicyName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"ruleGroupName\": autorest.Encode(\"path\", ruleGroupName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-06-01\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsDelete(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/firewallPolicies/{firewallPolicyName}/ruleGroups/{ruleGroupName}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client *RouteTablesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, routeTableName string, options *RouteTablesBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif routeTableName == \"\" {\n\t\treturn nil, errors.New(\"parameter routeTableName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{routeTableName}\", url.PathEscape(routeTableName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (sdk *MockGoSDKClient) DeleteSQLFirewallRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) {\n\treturn nil\n}" ]
[ "0.6789691", "0.6448388", "0.6266018", "0.61834526", "0.6073148", "0.60366744", "0.6007101", "0.57567215", "0.5755069", "0.57518935", "0.5743048", "0.5707084", "0.5651492", "0.5617365", "0.55842", "0.55457777", "0.5540249", "0.5528424", "0.5467309", "0.54369605", "0.53962755", "0.53943396", "0.5385631", "0.53482354", "0.5261095", "0.5252315", "0.52454", "0.52410257", "0.52307224", "0.52227294", "0.5215934", "0.52131057", "0.5199212", "0.5191767", "0.5176676", "0.51673234", "0.51643056", "0.5158666", "0.5133167", "0.5127771", "0.5120852", "0.511815", "0.51104367", "0.51004946", "0.50948834", "0.5091526", "0.5083529", "0.50715363", "0.5067379", "0.50594", "0.5059171", "0.504299", "0.5034767", "0.5030432", "0.5013114", "0.4995079", "0.498553", "0.49813747", "0.49730197", "0.4970959", "0.4952519", "0.49523965", "0.49463287", "0.49368224", "0.49346676", "0.4933071", "0.49287376", "0.49253783", "0.49177113", "0.49138525", "0.4904199", "0.49017695", "0.48981607", "0.48864943", "0.48792222", "0.48708013", "0.48692337", "0.4863544", "0.4859486", "0.4854782", "0.4852505", "0.4848411", "0.48374632", "0.4832347", "0.48302668", "0.4827768", "0.4824917", "0.48238277", "0.48235875", "0.48081034", "0.48078397", "0.4805831", "0.48054498", "0.4804638", "0.4802893", "0.48006105", "0.47968504", "0.47914705", "0.47893515", "0.4783017" ]
0.8559896
0
CreateDeleteVpdGrantRuleResponse creates a response to parse from DeleteVpdGrantRule response
func CreateDeleteVpdGrantRuleResponse() (response *DeleteVpdGrantRuleResponse) { response = &DeleteVpdGrantRuleResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CreateDeleteVpdGrantRuleRequest() (request *DeleteVpdGrantRuleRequest) {\n\trequest = &DeleteVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"DeleteVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func CreateCreateVpdGrantRuleResponse() (response *CreateVpdGrantRuleResponse) {\n\tresponse = &CreateVpdGrantRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) DeleteVpdGrantRuleWithChan(request *DeleteVpdGrantRuleRequest) (<-chan *DeleteVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *DeleteVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.DeleteVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) DeleteVpdGrantRuleWithCallback(request *DeleteVpdGrantRuleRequest, callback func(response *DeleteVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *DeleteVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.DeleteVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func CreateDeleteDegradeControlResponse() (response *DeleteDegradeControlResponse) {\n\tresponse = &DeleteDegradeControlResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteVideoDnaGroupResponse() (response *DeleteVideoDnaGroupResponse) {\n\tresponse = &DeleteVideoDnaGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteCorpGroupResponse() (response *DeleteCorpGroupResponse) {\n\tresponse = &DeleteCorpGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteCasterEpisodeGroupResponse() (response *DeleteCasterEpisodeGroupResponse) {\n\tresponse = &DeleteCasterEpisodeGroupResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *Client) DeleteVpdGrantRule(request *DeleteVpdGrantRuleRequest) (response *DeleteVpdGrantRuleResponse, err error) {\n\tresponse = CreateDeleteVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func CreateDeleteLiveDelayConfigResponse() (response *DeleteLiveDelayConfigResponse) {\n\tresponse = &DeleteLiveDelayConfigResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteVccRouteEntryResponse() (response *DeleteVccRouteEntryResponse) {\n\tresponse = &DeleteVccRouteEntryResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func ParseDeleteaspecificRewriteRuleResponse(rsp *http.Response) (*DeleteaspecificRewriteRuleResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificRewriteRuleResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func NewCheckCanDeleteMonitorResponse(data CheckCanDeleteMonitorResponseData) *CheckCanDeleteMonitorResponse {\n\tthis := CheckCanDeleteMonitorResponse{}\n\tthis.Data = data\n\treturn &this\n}", "func CreateCreateVpdGrantRuleRequest() (request *CreateVpdGrantRuleRequest) {\n\trequest = &CreateVpdGrantRuleRequest{\n\t\tRpcRequest: &requests.RpcRequest{},\n\t}\n\trequest.InitWithApiInfo(\"eflo\", \"2022-05-30\", \"CreateVpdGrantRule\", \"eflo\", \"openAPI\")\n\trequest.Method = requests.POST\n\treturn\n}", "func ParseDeleteaspecificPeeringRuleResponse(rsp *http.Response) (*DeleteaspecificPeeringRuleResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificPeeringRuleResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func CreateDeleteApDeviceResponse() (response *DeleteApDeviceResponse) {\n\tresponse = &DeleteApDeviceResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *WCFRelaysClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysClientDeleteAuthorizationRuleOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif authorizationRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter authorizationRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{authorizationRuleName}\", url.PathEscape(authorizationRuleName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *Client) CreateVpdGrantRuleWithChan(request *CreateVpdGrantRuleRequest) (<-chan *CreateVpdGrantRuleResponse, <-chan error) {\n\tresponseChan := make(chan *CreateVpdGrantRuleResponse, 1)\n\terrChan := make(chan error, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tdefer close(responseChan)\n\t\tdefer close(errChan)\n\t\tresponse, err := client.CreateVpdGrantRule(request)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t} else {\n\t\t\tresponseChan <- response\n\t\t}\n\t})\n\tif err != nil {\n\t\terrChan <- err\n\t\tclose(responseChan)\n\t\tclose(errChan)\n\t}\n\treturn responseChan, errChan\n}", "func (client *Client) CreateVpdGrantRuleWithCallback(request *CreateVpdGrantRuleRequest, callback func(response *CreateVpdGrantRuleResponse, err error)) <-chan int {\n\tresult := make(chan int, 1)\n\terr := client.AddAsyncTask(func() {\n\t\tvar response *CreateVpdGrantRuleResponse\n\t\tvar err error\n\t\tdefer close(result)\n\t\tresponse, err = client.CreateVpdGrantRule(request)\n\t\tcallback(response, err)\n\t\tresult <- 1\n\t})\n\tif err != nil {\n\t\tdefer close(result)\n\t\tcallback(nil, err)\n\t\tresult <- 0\n\t}\n\treturn result\n}", "func (client *Client) CreateVpdGrantRule(request *CreateVpdGrantRuleRequest) (response *CreateVpdGrantRuleResponse, err error) {\n\tresponse = CreateCreateVpdGrantRuleResponse()\n\terr = client.DoAction(request, response)\n\treturn\n}", "func ParseDeleteaspecificRewriteRuleSetResponse(rsp *http.Response) (*DeleteaspecificRewriteRuleSetResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificRewriteRuleSetResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func UnmarshalPageRulesDeleteResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(PageRulesDeleteResponse)\n\terr = core.UnmarshalPrimitive(m, \"success\", &obj.Success)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"errors\", &obj.Errors)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"messages\", &obj.Messages)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"result\", &obj.Result, UnmarshalPageRulesDeleteResponseResult)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func NewExportPolicyCreateResponse() *ExportPolicyCreateResponse { return &ExportPolicyCreateResponse{} }", "func ParseDeleteaspecificPeeringInboundRuleResponse(rsp *http.Response) (*DeleteaspecificPeeringInboundRuleResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificPeeringInboundRuleResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func (client FirewallPolicyRuleGroupsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func ParseDeleteRuleFromSecurityGroupResponse(rsp *http.Response) (*DeleteRuleFromSecurityGroupResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteRuleFromSecurityGroupResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func CreateRevokeOperatorResponse() (response *RevokeOperatorResponse) {\n\tresponse = &RevokeOperatorResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func UnmarshalPageRulesDeleteResponseResult(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(PageRulesDeleteResponseResult)\n\terr = core.UnmarshalPrimitive(m, \"id\", &obj.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (o HttpRuleResponseOutput) Delete() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HttpRuleResponse) string { return v.Delete }).(pulumi.StringOutput)\n}", "func (*MemberRuleSettingDeleteResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{98}\n}", "func NewNatRuleDeleteCommand(authenticatingCommand *GenericCommand) *AuthenticationRequiringCommand {\n\treturn &AuthenticationRequiringCommand{\n\t\tGenericCommand: GenericCommand{\n\t\t\tName: \"NatRuleDelete\",\n\t\t\tDescription: \"Deletes an IPV4 NAT rule configured for the specified ID\",\n\t\t\tArgNames: []string{\"id\"},\n\t\t\tArgTypes: []string{\"int\"},\n\t\t\tExec: func(context *CommandContext) {\n\t\t\t\tid, err := context.GetIntArg(0)\n\t\t\t\tif err != nil {\n\t\t\t\t\tparseErr := errors.New(\"ID must be a numeric value\")\n\t\t\t\t\tcontext.SetResult(nil, parseErr)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontext.SetResult(nil, service.GetHub().NatRuleDelete(id))\n\t\t\t},\n\t\t\tPostExec: func(context *CommandContext) {\n\t\t\t\tif !context.IsError() {\n\t\t\t\t\tfmt.Printf(\"NAT rule successfully deleted\\n\")\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tAuthenticatingCommand: authenticatingCommand,\n\t}\n}", "func CreateDeleteBucketResponse() (response *DeleteBucketResponse) {\n\tresponse = &DeleteBucketResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func ParseDeleteaspecificProfilePackageResponse(rsp *http.Response) (*DeleteaspecificProfilePackageResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificProfilePackageResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func CreateDeleteServiceTimeConfigResponse() (response *DeleteServiceTimeConfigResponse) {\n\tresponse = &DeleteServiceTimeConfigResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (o HttpRuleOutput) Delete() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HttpRule) *string { return v.Delete }).(pulumi.StringPtrOutput)\n}", "func ParseDeleteDNSZoneResponse(rsp *http.Response) (*DeleteDNSZoneResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteDNSZoneResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest ScalewayDomainV2alpha2DeleteDNSZoneResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func ParseDeletePatientPermissionResponse(rsp *http.Response) (*DeletePatientPermissionResponse, error) {\n\tbodyBytes, err := io.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeletePatientPermissionResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\treturn response, nil\n}", "func ParseDeleteTemplateResponse(rsp *http.Response) (*DeleteTemplateResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteTemplateResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func ParsedeleteDomainResponse(rsp *http.Response) (*deleteDomainResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &deleteDomainResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func ParseDeleteSSLCertificateResponse(rsp *http.Response) (*DeleteSSLCertificateResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteSSLCertificateResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest ScalewayDomainV2alpha2DeleteSSLCertificateResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func (a *BackendOptionsApiService) DeleteHTTPResponseRule(ctx _context.Context, id int32, parentName string, parentType string, localVarOptionals *DeleteHTTPResponseRuleOpts) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/services/haproxy/configuration/http_response_rules/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", id)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tlocalVarQueryParams.Add(\"parent_name\", parameterToString(parentName, \"\"))\n\tlocalVarQueryParams.Add(\"parent_type\", parameterToString(parentType, \"\"))\n\tif localVarOptionals != nil && localVarOptionals.TransactionId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"transaction_id\", parameterToString(localVarOptionals.TransactionId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Version.IsSet() {\n\t\tlocalVarQueryParams.Add(\"version\", parameterToString(localVarOptionals.Version.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.ForceReload.IsSet() {\n\t\tlocalVarQueryParams.Add(\"force_reload\", parameterToString(localVarOptionals.ForceReload.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v ModelError\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func Delete(c *golangsdk.ServiceClient, policyID, ruleID string) (r DeleteResult) {\n\treqOpt := &golangsdk.RequestOpts{\n\t\tMoreHeaders: RequestOpts.MoreHeaders,\n\t}\n\n\t_, r.Err = c.Delete(resourceURL(c, policyID, ruleID), reqOpt)\n\treturn\n}", "func ParseDeleteInstancePoolResponse(rsp *http.Response) (*DeleteInstancePoolResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteInstancePoolResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func NewDeleteResponseBody(res *warehouseviews.SuccessResultView) *DeleteResponseBody {\n\tbody := &DeleteResponseBody{\n\t\tOK: *res.OK,\n\t}\n\treturn body\n}", "func (client WorkloadNetworksClient) DeleteVMGroupResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func CreateDeregisterDelegatedAdministratorResponse() (response *DeregisterDelegatedAdministratorResponse) {\n\tresponse = &DeregisterDelegatedAdministratorResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (c *IPSecVPNClient) NewDeleteVPNTunnelRequest() *DeleteVPNTunnelRequest {\n\treq := &DeleteVPNTunnelRequest{}\n\n\t// setup request with client config\n\tc.Client.SetupRequest(req)\n\n\t// setup retryable with default retry policy (retry for non-create action and common error)\n\treq.SetRetryable(true)\n\treturn req\n}", "func DecodeVMDeleteResponse(decoder func(*http.Response) goahttp.Decoder, restoreBody bool) func(*http.Response) (interface{}, error) {\n\treturn func(resp *http.Response) (interface{}, error) {\n\t\tif restoreBody {\n\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\tdefer func() {\n\t\t\t\tresp.Body = ioutil.NopCloser(bytes.NewBuffer(b))\n\t\t\t}()\n\t\t} else {\n\t\t\tdefer resp.Body.Close()\n\t\t}\n\t\tswitch resp.StatusCode {\n\t\tcase http.StatusOK:\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\treturn nil, goahttp.ErrInvalidResponse(\"spin-registry\", \"vm_delete\", resp.StatusCode, string(body))\n\t\t}\n\t}\n}", "func (client *RoleAssignmentsClient) deleteHandleResponse(resp *http.Response) (RoleAssignmentsDeleteResponse, error) {\n\tresult := RoleAssignmentsDeleteResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsDeleteResponse{}, err\n\t}\n\treturn result, nil\n}", "func CreateGrantInstanceToVbrResponse() (response *GrantInstanceToVbrResponse) {\n\tresponse = &GrantInstanceToVbrResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteSurveyResourcesResponse() (response *DeleteSurveyResourcesResponse) {\n\tresponse = &DeleteSurveyResourcesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func CreateDeleteVideoDnaGroupRequest() (request *DeleteVideoDnaGroupRequest) {\n\trequest = &DeleteVideoDnaGroupRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Green\", \"2018-05-09\", \"DeleteVideoDnaGroup\", \"/green/video/dna/group/delete\", \"\", \"\")\n\trequest.Method = requests.POST\n\treturn\n}", "func ParseDeleteSecurityGroupResponse(rsp *http.Response) (*DeleteSecurityGroupResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteSecurityGroupResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func DeleteRule(ctx context.Context, p *Protocol, routeID routing.RouteID) error {\n\tif err := p.WritePacket(PacketDeleteRules, []routing.RouteID{routeID}); err != nil {\n\t\treturn err\n\t}\n\tvar res []routing.RouteID\n\tif err := readAndDecodePacketWithTimeout(ctx, p, &res); err != nil {\n\t\treturn err\n\t}\n\tif len(res) == 0 {\n\t\treturn errors.New(\"empty response\")\n\t}\n\treturn nil\n}", "func (o *ReplacePolicyV1beta1NamespacedPodDisruptionBudgetUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses\n\n\trw.WriteHeader(401)\n}", "func (a *BackendOptionsApiService) DeleteTCPResponseRule(ctx _context.Context, id int32, backend string, localVarOptionals *DeleteTCPResponseRuleOpts) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/services/haproxy/configuration/tcp_response_rules/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", id)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tlocalVarQueryParams.Add(\"backend\", parameterToString(backend, \"\"))\n\tif localVarOptionals != nil && localVarOptionals.TransactionId.IsSet() {\n\t\tlocalVarQueryParams.Add(\"transaction_id\", parameterToString(localVarOptionals.TransactionId.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Version.IsSet() {\n\t\tlocalVarQueryParams.Add(\"version\", parameterToString(localVarOptionals.Version.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.ForceReload.IsSet() {\n\t\tlocalVarQueryParams.Add(\"force_reload\", parameterToString(localVarOptionals.ForceReload.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v ModelError\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func ParseDeleteClinicResponse(rsp *http.Response) (*DeleteClinicResponse, error) {\n\tbodyBytes, err := io.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteClinicResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\treturn response, nil\n}", "func (c *ClientWithResponses) DeleteaspecificPeeringRuleWithResponse(ctx context.Context, id string) (*DeleteaspecificPeeringRuleResponse, error) {\n\trsp, err := c.DeleteaspecificPeeringRule(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseDeleteaspecificPeeringRuleResponse(rsp)\n}", "func ParseDeleteaspecificPeeringGroupResponse(rsp *http.Response) (*DeleteaspecificPeeringGroupResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificPeeringGroupResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func (client *PolicyDefinitionsClient) deleteCreateRequest(ctx context.Context, policyDefinitionName string, options *PolicyDefinitionsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}\"\n\tif policyDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter policyDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{policyDefinitionName}\", url.PathEscape(policyDefinitionName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func ParseDeleteSksNodepoolResponse(rsp *http.Response) (*DeleteSksNodepoolResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteSksNodepoolResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func ParseDeleteClinicianResponse(rsp *http.Response) (*DeleteClinicianResponse, error) {\n\tbodyBytes, err := io.ReadAll(rsp.Body)\n\tdefer func() { _ = rsp.Body.Close() }()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteClinicianResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\treturn response, nil\n}", "func (o *ReplacePolicyV1beta1NamespacedPodDisruptionBudgetCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {\n\n\trw.WriteHeader(201)\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) // let the recovery middleware deal with this\n\t\t}\n\t}\n}", "func ParseDeleteDNSZoneTsigKeyResponse(rsp *http.Response) (*DeleteDNSZoneTsigKeyResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteDNSZoneTsigKeyResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func ParseDeleteaspecificTrustedSourceResponse(rsp *http.Response) (*DeleteaspecificTrustedSourceResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificTrustedSourceResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func CreateDeleteDegradeControlRequest() (request *DeleteDegradeControlRequest) {\n\trequest = &DeleteDegradeControlRequest{\n\t\tRoaRequest: &requests.RoaRequest{},\n\t}\n\trequest.InitWithApiInfo(\"Edas\", \"2017-08-01\", \"DeleteDegradeControl\", \"/pop/v5/degradeControl\", \"Edas\", \"openAPI\")\n\trequest.Method = requests.DELETE\n\treturn\n}", "func (client GroupClient) DeleteSecretResponder(resp *http.Response) (result autorest.Response, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByClosing())\n\tresult.Response = resp\n\treturn\n}", "func CreateBatchCreateDcdnWafRulesResponse() (response *BatchCreateDcdnWafRulesResponse) {\n\tresponse = &BatchCreateDcdnWafRulesResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, firewallRuleName string, options *FirewallRulesBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serverName == \"\" {\n\t\treturn nil, errors.New(\"parameter serverName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serverName}\", url.PathEscape(serverName))\n\tif firewallRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter firewallRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{firewallRuleName}\", url.PathEscape(firewallRuleName))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2017-12-01\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func ParseDeleteProjectsIdResponse(rsp *http.Response) (*DeleteProjectsIdResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteProjectsIdResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func NewDeleteResponse(num int64) *DeleteResponse {\n\tresp := &DeleteResponse{NumRows: num}\n\n\treturn resp\n}", "func (client IdentityClient) DeleteDynamicGroup(ctx context.Context, request DeleteDynamicGroupRequest) (response DeleteDynamicGroupResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.deleteDynamicGroup, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = DeleteDynamicGroupResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = DeleteDynamicGroupResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteDynamicGroupResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteDynamicGroupResponse\")\n\t}\n\treturn\n}", "func ParseDeleteExternalDomainResponse(rsp *http.Response) (*DeleteExternalDomainResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteExternalDomainResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest ScalewayDomainV2alpha2DeleteExternalDomainResponse\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func ParsedeleteZoneResponse(rsp *http.Response) (*deleteZoneResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &deleteZoneResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func ParseDeleteaspecificBillingZoneResponse(rsp *http.Response) (*DeleteaspecificBillingZoneResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificBillingZoneResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func (client *RoleAssignmentsClient) deleteByBillingProfileHandleResponse(resp *http.Response) (RoleAssignmentsClientDeleteByBillingProfileResponse, error) {\n\tresult := RoleAssignmentsClientDeleteByBillingProfileResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignment); err != nil {\n\t\treturn RoleAssignmentsClientDeleteByBillingProfileResponse{}, err\n\t}\n\treturn result, nil\n}", "func ParseDeleteaspecificManagerSecretaryResponse(rsp *http.Response) (*DeleteaspecificManagerSecretaryResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificManagerSecretaryResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func CreateSetDcdnDomainCSRCertificateResponse() (response *SetDcdnDomainCSRCertificateResponse) {\n\tresponse = &SetDcdnDomainCSRCertificateResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *RoleDefinitionsClient) deleteHandleResponse(resp *http.Response) (RoleDefinitionsDeleteResponse, error) {\n\tresult := RoleDefinitionsDeleteResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.RoleDefinition); err != nil {\n\t\treturn RoleDefinitionsDeleteResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (a *SyncApiService) DeleteSyncRule(ctx context.Context, syncRuleId string) ( *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/platform/3/sync/rules/{SyncRuleId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"SyncRuleId\"+\"}\", fmt.Sprintf(\"%v\", syncRuleId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\treturn localVarHttpResponse, err\n}", "func (client IdentityClient) deleteDynamicGroup(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/dynamicGroups/{dynamicGroupId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteDynamicGroupResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func ParseDeleteAntiAffinityGroupResponse(rsp *http.Response) (*DeleteAntiAffinityGroupResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteAntiAffinityGroupResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\tcase strings.Contains(rsp.Header.Get(\"Content-Type\"), \"json\") && rsp.StatusCode == 200:\n\t\tvar dest Operation\n\t\tif err := json.Unmarshal(bodyBytes, &dest); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresponse.JSON200 = &dest\n\n\t}\n\n\treturn response, nil\n}", "func (client *HCRPAssignmentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, guestConfigurationAssignmentName string, machineName string, options *HCRPAssignmentsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/machines/{machineName}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{guestConfigurationAssignmentName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif guestConfigurationAssignmentName == \"\" {\n\t\treturn nil, errors.New(\"parameter guestConfigurationAssignmentName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{guestConfigurationAssignmentName}\", url.PathEscape(guestConfigurationAssignmentName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif machineName == \"\" {\n\t\treturn nil, errors.New(\"parameter machineName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{machineName}\", url.PathEscape(machineName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-25\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *ClientWithResponses) DeleteaspecificRewriteRuleWithResponse(ctx context.Context, id string) (*DeleteaspecificRewriteRuleResponse, error) {\n\trsp, err := c.DeleteaspecificRewriteRule(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseDeleteaspecificRewriteRuleResponse(rsp)\n}", "func (client *RegistrationDefinitionsClient) deleteCreateRequest(ctx context.Context, registrationDefinitionID string, scope string, options *RegistrationDefinitionsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}\"\n\tif registrationDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter registrationDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registrationDefinitionId}\", url.PathEscape(registrationDefinitionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func ParseDeleteaspecificCFDestinationSetResponse(rsp *http.Response) (*DeleteaspecificCFDestinationSetResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificCFDestinationSetResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func ParseDeleteExpensesIdResponse(rsp *http.Response) (*DeleteExpensesIdResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteExpensesIdResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func (c *ClientWithResponses) DeleteaspecificPeeringInboundRuleWithResponse(ctx context.Context, id string) (*DeleteaspecificPeeringInboundRuleResponse, error) {\n\trsp, err := c.DeleteaspecificPeeringInboundRule(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseDeleteaspecificPeeringInboundRuleResponse(rsp)\n}", "func (c *client) DeleteHTTPResponseRule(id int64, parentType string, parentName string, transactionID string, version int64) error {\n\tp, t, err := c.loadDataForChange(transactionID, version)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar section parser.Section\n\tif parentType == \"backend\" {\n\t\tsection = parser.Backends\n\t} else if parentType == \"frontend\" {\n\t\tsection = parser.Frontends\n\t}\n\n\tif err := p.Delete(section, parentName, \"http-response\", int(id)); err != nil {\n\t\treturn c.HandleError(strconv.FormatInt(id, 10), parentType, parentName, t, transactionID == \"\", err)\n\t}\n\n\treturn c.SaveData(p, t, transactionID == \"\")\n}", "func (r *GroupPolicyMigrationReportRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func CreateDescribeDispatchRuleResponse() (response *DescribeDispatchRuleResponse) {\n\tresponse = &DescribeDispatchRuleResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}", "func (client *RoleDefinitionsClient) deleteCreateRequest(ctx context.Context, scope string, roleDefinitionID string, options *RoleDefinitionsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\tif roleDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter roleDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleDefinitionId}\", url.PathEscape(roleDefinitionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func NewProjectDeploymentRuleResponse(id string, createdAt time.Time, name string, mode string, cluster string, alwaysUp bool) *ProjectDeploymentRuleResponse {\n\tthis := ProjectDeploymentRuleResponse{}\n\tthis.Id = id\n\tthis.CreatedAt = createdAt\n\tthis.Name = name\n\tthis.Mode = mode\n\tthis.Cluster = cluster\n\tvar autoDeploy bool = true\n\tthis.AutoDeploy = &autoDeploy\n\tthis.AlwaysUp = alwaysUp\n\treturn &this\n}", "func NewExportPolicyCreateResponse() *ExportPolicyCreateResponse {\n\treturn &ExportPolicyCreateResponse{}\n}", "func (client PatternClient) DeletePatternResponder(resp *http.Response) (result OperationStatus, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func ParseDeleteaspecificDomainResponse(rsp *http.Response) (*DeleteaspecificDomainResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &DeleteaspecificDomainResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func (a *CloudCostPerspectivesApiService) DeletePerspective(ctx context.Context, accountIdentifier string, perspectiveId string) (ResponseDtoString, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ResponseDtoString\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/ccm/api/perspective\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tlocalVarQueryParams.Add(\"accountIdentifier\", parameterToString(accountIdentifier, \"\"))\n\tlocalVarQueryParams.Add(\"perspectiveId\", parameterToString(perspectiveId, \"\"))\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v Failure\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 0 {\n\t\t\tvar v ResponseDtoString\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func ExampleAssignmentsVMSSClient_Delete() {\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\tclientFactory, err := armguestconfiguration.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewAssignmentsVMSSClient().Delete(ctx, \"myResourceGroupName\", \"myVMSSName\", \"SecureProtocol\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Assignment = armguestconfiguration.Assignment{\n\t// \tName: to.Ptr(\"AuditSecureProtocol\"),\n\t// \tID: to.Ptr(\"/subscriptions/subscriptionId/resourceGroups/myResourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/myVMSSName/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/AuditSecureProtocol\"),\n\t// \tLocation: to.Ptr(\"centraluseuap\"),\n\t// \tProperties: &armguestconfiguration.AssignmentProperties{\n\t// \t\tAssignmentHash: to.Ptr(\"E0D8941DD713F284284561648C00C18FA76C8602943C7CD38AFD73B56AE4C35F.E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855\"),\n\t// \t\tComplianceStatus: to.Ptr(armguestconfiguration.ComplianceStatusCompliant),\n\t// \t\tGuestConfiguration: &armguestconfiguration.Navigation{\n\t// \t\t\tName: to.Ptr(\"AuditSecureProtocol\"),\n\t// \t\t\tConfigurationParameter: []*armguestconfiguration.ConfigurationParameter{\n\t// \t\t\t},\n\t// \t\t\tContentHash: to.Ptr(\"content hash\"),\n\t// \t\t\tContentURI: to.Ptr(\"https://mystorageaccount.blob.core.windows.net/builtinconfig/AuditSecureProtocol/AuditSecureProtocol_1.0.0.3.zip\"),\n\t// \t\t\tVersion: to.Ptr(\"1.0.0.3\"),\n\t// \t\t},\n\t// \t\tLastComplianceStatusChecked: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2018-08-29T22:14:13Z\"); return t}()),\n\t// \t\tProvisioningState: to.Ptr(armguestconfiguration.ProvisioningStateSucceeded),\n\t// \t\tResourceType: to.Ptr(\"VMSS\"),\n\t// \t},\n\t// }\n}", "func CreateRemoveUserAnalyzerResponse() (response *RemoveUserAnalyzerResponse) {\n\tresponse = &RemoveUserAnalyzerResponse{\n\t\tBaseResponse: &responses.BaseResponse{},\n\t}\n\treturn\n}" ]
[ "0.722374", "0.68933475", "0.614391", "0.61086893", "0.5957358", "0.59270376", "0.57114804", "0.56331295", "0.56186", "0.56060326", "0.55410606", "0.53387797", "0.5270599", "0.52538157", "0.52283925", "0.5223366", "0.5216195", "0.5184312", "0.51793605", "0.51685613", "0.516844", "0.515406", "0.5148819", "0.51398754", "0.50707525", "0.5069559", "0.5014548", "0.49791262", "0.49550942", "0.4948599", "0.49287257", "0.49266", "0.49105802", "0.4891871", "0.48915988", "0.48864728", "0.4863981", "0.48618785", "0.48609576", "0.4857592", "0.48571694", "0.48477727", "0.48474634", "0.4842465", "0.4841714", "0.48405924", "0.483071", "0.48291248", "0.48253155", "0.4805381", "0.47983253", "0.47831652", "0.4782991", "0.4764414", "0.47505084", "0.47499704", "0.4749965", "0.47461686", "0.4744214", "0.47262436", "0.47239673", "0.47210357", "0.47147486", "0.47142515", "0.47077742", "0.47031894", "0.469492", "0.4689421", "0.4687754", "0.46848613", "0.4683643", "0.4683288", "0.46822393", "0.4680319", "0.46747425", "0.4673968", "0.46692902", "0.46687466", "0.46664774", "0.46595493", "0.46500316", "0.46481484", "0.46442148", "0.46426496", "0.46413973", "0.4622167", "0.4620663", "0.4619283", "0.46159136", "0.46155688", "0.46129858", "0.46105877", "0.46094123", "0.46061057", "0.45996347", "0.45957366", "0.45900828", "0.45849618", "0.4574924", "0.4570492" ]
0.8677458
0
use isCountryOpts instead of areOpts because it saves code in the test and tests the areOpts function with a relatively large dataset tests all isXxxOpt apart from isSortByOpt as well
func TestAreOpts(t *testing.T) { cases := []struct { c string isOpt bool }{ {"se", true}, {"bg", true}, {"il", true}, {"za", true}, {"ba", false}, {"12", false}, {"", false}, {"hugh", false}, } for _, i := range cases { var isCountry bool = isOptOf(i.c, countryOpts) if isCountry != i.isOpt { t.Errorf("Expected %v but got %v when case=%v", i.isOpt, isCountry, i.c) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"mount_path\":\n\t\t\t\topts.withMountPath = v\n\t\t\tcase \"key_name\":\n\t\t\t\topts.withKeyName = v\n\t\t\tcase \"disable_renewal\":\n\t\t\t\topts.withDisableRenewal = v\n\t\t\tcase \"namespace\":\n\t\t\t\topts.withNamespace = v\n\t\t\tcase \"address\":\n\t\t\t\topts.withAddress = v\n\t\t\tcase \"tls_ca_cert\":\n\t\t\t\topts.withTlsCaCert = v\n\t\t\tcase \"tls_ca_path\":\n\t\t\t\topts.withTlsCaPath = v\n\t\t\tcase \"tls_client_cert\":\n\t\t\t\topts.withTlsClientCert = v\n\t\t\tcase \"tls_client_key\":\n\t\t\t\topts.withTlsClientKey = v\n\t\t\tcase \"tls_server_name\":\n\t\t\t\topts.withTlsServerName = v\n\t\t\tcase \"tls_skip_verify\":\n\t\t\t\tvar err error\n\t\t\t\topts.withTlsSkipVerify, err = strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase \"token\":\n\t\t\t\topts.withToken = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func TestOptionsFilter(t *testing.T) {\n\ttearDown()\n\tws := new(WebService)\n\tws.Route(ws.GET(\"/candy/{kind}\").To(dummy))\n\tws.Route(ws.DELETE(\"/candy/{kind}\").To(dummy))\n\tws.Route(ws.POST(\"/candies\").To(dummy))\n\tAdd(ws)\n\tFilter(OPTIONSFilter())\n\n\thttpRequest, _ := http.NewRequest(\"OPTIONS\", \"http://here.io/candy/gum\", nil)\n\thttpWriter := httptest.NewRecorder()\n\tDefaultContainer.dispatch(httpWriter, httpRequest)\n\tactual := httpWriter.Header().Get(HEADER_Allow)\n\tif \"GET,DELETE\" != actual {\n\t\tt.Fatal(\"expected: GET,DELETE but got:\" + actual)\n\t}\n\n\thttpRequest, _ = http.NewRequest(\"OPTIONS\", \"http://here.io/candies\", nil)\n\thttpWriter = httptest.NewRecorder()\n\tDefaultContainer.dispatch(httpWriter, httpRequest)\n\tactual = httpWriter.Header().Get(HEADER_Allow)\n\tif \"POST\" != actual {\n\t\tt.Fatal(\"expected: POST but got:\" + actual)\n\t}\n}", "func parseOpts(opts Options, args []string, testMode bool) (*dany.Query, []string, error) {\n\tq := new(dany.Query)\n\tq.Udp = opts.Udp\n\tq.Ptr = opts.Ptr\n\tq.Usd = opts.Usd\n\tq.Tag = opts.Tag\n\n\t// Parse opts.Server\n\tif opts.Server != \"\" {\n\t\tserverIP := net.ParseIP(opts.Server)\n\t\tif serverIP == nil {\n\t\t\terr := fmt.Errorf(\"Error: unable to parse --server ip address %q\", opts.Server)\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tq.Resolvers = dany.NewResolvers(serverIP)\n\t} else if opts.Resolvers != \"\" {\n\t\tresolvers, err := dany.LoadResolvers(opts.Resolvers)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tq.Resolvers = resolvers\n\t}\n\n\t// Parse opts.Types\n\ttypeMap := make(map[string]bool)\n\tfor _, t := range dany.SupportedRRTypes {\n\t\ttypeMap[t] = true\n\t\ttypeMap[strings.ToLower(t)] = true\n\t}\n\tif opts.Types != \"\" {\n\t\ttypes := strings.Split(opts.Types, \",\")\n\t\terr := checkValidTypes(types, typeMap)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tq.Types = types\n\t}\n\n\targs, err := parseArgs(q, args, typeMap, testMode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif q.Types == nil || len(q.Types) == 0 {\n\t\tif opts.All {\n\t\t\tq.Types = dany.SupportedRRTypes\n\t\t} else {\n\t\t\tq.Types = dany.DefaultRRTypes\n\t\t}\n\t}\n\n\tif q.Resolvers == nil {\n\t\tconfig, err := dns.ClientConfigFromFile(\"/etc/resolv.conf\")\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tfor _, server := range config.Servers {\n\t\t\tserverIP := net.ParseIP(server)\n\t\t\tif serverIP == nil {\n\t\t\t\terr := fmt.Errorf(\"Error: unable to parse --server ip address %q\", opts.Server)\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tif q.Resolvers == nil {\n\t\t\t\tq.Resolvers = dany.NewResolvers(serverIP)\n\t\t\t} else {\n\t\t\t\tq.Resolvers.Append(serverIP)\n\t\t\t}\n\t\t}\n\t}\n\n\tvprintf(\"resolvers: %v\\n\", q.Resolvers.List)\n\tvprintf(\"types: %v\\n\", q.Types)\n\n\treturn q, args, nil\n}", "func OptionsEqual(xopts, yopts map[string]interface{}) bool {\n\tif len(xopts) != len(yopts) {\n\t\treturn false\n\t}\n\n\tfor k, v := range yopts {\n\t\txv, ok := xopts[k]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tif strings.HasSuffix(k, \"ttl\") || strings.HasSuffix(k, \"period\") {\n\t\t\tif !ttlEqual(fmt.Sprintf(\"%v\", v), fmt.Sprintf(\"%v\", xv)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif fmt.Sprintf(\"%v\", v) != fmt.Sprintf(\"%v\", xv) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func hasOpt(opt RunOption, opts []RunOption) bool {\n\tfor _, o := range opts {\n\t\tif o == opt {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o LogOptions) validateOpts(logDriver string, supportedOpts map[string]bool, validKVs map[string][]string) error {\n\tfor k, v := range o {\n\t\tif !supportedOpts[k] {\n\t\t\treturn fmt.Errorf(\"provided configuration key %q is not supported as a logging option for log driver %s\", k, logDriver)\n\t\t}\n\t\tif validValues, ok := validKVs[k]; ok {\n\t\t\tvalid := false\n\t\t\tfor _, vv := range validValues {\n\t\t\t\tif v == vv {\n\t\t\t\t\tvalid = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !valid {\n\t\t\t\treturn fmt.Errorf(\"provided configuration value %q is not a valid value for %q in log driver %s, valid values: %v\", v, k, logDriver, validValues)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn nil\n}", "func TestExtractArgs(t *testing.T) {\n\tpossibleOptions := getPossibleOptions()\n\ta := []string{\"--optionavecargument\", \"titi\", \"--optionsansargument\", \"--optionavecargument2\", \"toto\", \"chouette\"}\n\tremainingArgs, options, err := utils.ExtractOptions(a, possibleOptions)\n\tif (err != nil) {\n\t\tt.Errorf(err.Error())\n\t}\n\tif (len(remainingArgs) != 1) {\n\t\tt.Errorf(\"Erreur sur remaining args \" + string(len(remainingArgs)))\n\t}\n\tif (len(options) != 3) {\n\t\tt.Errorf(\"Erreur sur options\")\n\t}\n\n\tif (remainingArgs[0] != \"chouette\") {\n\t\tt.Errorf(\"Erreur sur remainingArgs : \" + remainingArgs[0])\n\t}\n\n\tif (options[\"--optionavecargument\"] != \"titi\") {\n\t\tt.Errorf(\"Erreur sur option --optionavecargument : \" + options[\"--optionavecargument\"])\n\t}\n\tif (options[\"--optionavecargument2\"] != \"toto\") {\n\t\tt.Errorf(\"Erreur sur option --optionavecargument2 : \" + options[\"--optionavecargument2\"])\n\t}\n\tif _, isPresent := options[\"--optionsansargument\"]; !isPresent {\n\t\tt.Errorf(\"Erreur sur option --optionsansargument : \" + options[\"--optionsansargument\"])\n\t}\n\tif _, isPresent := options[\"--optionsansargument2\"]; isPresent {\n\t\tt.Errorf(\"Erreur sur option --optionsansargument2 : \" + options[\"--optionsansargument2\"])\n\t}\n}", "func evaluateQueryOptions(queryOpts []eventsource.QueryOption) *options {\n\topts := &options{ // nolint:exhaustivestruct\n\t\tdescending: false,\n\t\twhere: make(map[column]whereOpt),\n\t}\n\n\tfor _, opt := range queryOpts {\n\t\topt(opts)\n\t}\n\n\treturn opts\n}", "func generalOptions() *opt.OptionSet {\n\topts := opt.NewOptionSet()\n\topts.Add(opt.NewOption(opt.String, \"search\", 's', \"\", \"search options\"))\n\topts.Add(opt.NewOption(opt.List, \"agent\", 'a',\n\t\t\"for each involved agent specify its id, host, and port\",\n\t\t\"\\\"<id> <host> <port>\\\"\"))\n\topts.Add(opt.NewOption(opt.List, \"problem\", 'p',\n\t\t\"problem file in json format as generated by translate script. \"+\n\t\t\t\"If multiple files are provided, agents are run in threads \"+\n\t\t\t\"using go-channels instead of tcp/ip communication.\",\n\t\t\"domain/problem.json\"))\n\topts.Add(opt.NewOption(opt.List, \"heuristic\", 'h', \"\", \"heur options\"))\n\topts.Add(opt.NewOption(opt.String, \"pruning\", ' ', \"none\", \"action pruning method. Values: [none|sss]\"))\n\topts.Add(opt.NewOption(opt.Bool, \"macros\", 'm', \"\",\n\t\t\"use macro projections\"))\n\topts.Add(opt.NewOption(opt.Float64, \"timeout\", 'x', \"1800.0\",\n\t\t\"time budget in seconds\"))\n\topts.Add(opt.NewOption(opt.Int32, \"planlimit\", 'q', 1, \"number of plans to generate\"))\n\topts.Add(opt.NewOption(opt.String, \"logfile\", 'l', \"\", \"write logs to file\"))\n\topts.Add(opt.NewOption(opt.Bool, \"nature\", 'n', \"\", \"add nature agent -> continual planning\"))\n\treturn opts\n}", "func checkPossibleOptions(param interface{}, paramOptions []interface{}) bool {\n\tfor _, opt := range paramOptions {\n\t\tif opt == param {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func getOpts() (options, error) {\n\n\t// Ensuring we're getting the correct # of arguments\n\tif len(os.Args) < 2 {\n\t\treturn options{}, errors.New(\"A filepath argument must be given!\")\n\t}\n\n\t// These are out options flags.\n\t// Using the flag pkg from stdlib, we provide the flag's name, a default value, and\n\t// a short description that can be displayed with --help to the user\n\tseparator := flag.String(\"separator\", \"comma\", \"Column Separator\")\n\tpretty := flag.Bool(\"pretty\", false, \"Generate pretty JSON\")\n\toutputPath := flag.String(\"outputPath\", \"\", \"Path to save JSON output file\")\n\n\t// Parsing our command line arguments\n\tflag.Parse()\n\n\t// The only non-flag arg is the file location\n\tfileLocation := flag.Arg(0)\n\n\t// Validating the separator flags\n\tif !(*separator == \"comma\" || *separator == \"semicolon\") {\n\t\treturn options{}, errors.New(\"Only comma or semicolon separators allowed\")\n\t}\n\n\t// If a path to save the output json is provided, check that the path exists and is\n\t// a directory\n\tif *outputPath != \"\" {\n\t\tfileInfo, err := os.Stat(*outputPath)\n\t\tif os.IsNotExist(err) {\n\t\t\treturn options{}, errors.New(\"Path provided to save output JSON does not exist\")\n\t\t} else if !fileInfo.IsDir() {\n\t\t\treturn options{}, errors.New(\"Path provided to save output JSON is not a directory\")\n\t\t}\n\t\t// Otherwise, if not provided, default it to the input file's directory path\n\t} else {\n\t\t*outputPath = filepath.Dir(fileLocation)\n\t}\n\n\t// Complete the output path for saving the json data by joining the path to the output\n\t// directory and the csv filename without the csv prefix\n\t*outputPath = filepath.Join(*outputPath, fmt.Sprintf(\"%s.json\", strings.TrimSuffix(filepath.Base(fileLocation), \".csv\")))\n\n\t// If all validations have been passed, we return the struct that gives our program\n\t// all it needs to run\n\treturn options{fileLocation, *separator, *pretty, *outputPath}, nil\n}", "func TestDaemon_ListWorkloadsWithOptions(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\n\tt.Run(\"no filter\", func(t *testing.T) {\n\t\ts, err := d.ListServicesWithOptions(ctx, v11.ListServicesOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t\t}\n\t\tif len(s) != 2 {\n\t\t\tt.Fatalf(\"Expected %v but got %v\", 2, len(s))\n\t\t}\n\t})\n\tt.Run(\"filter id\", func(t *testing.T) {\n\t\ts, err := d.ListServicesWithOptions(ctx, v11.ListServicesOptions{\n\t\t\tNamespace: \"\",\n\t\t\tServices: []resource.ID{resource.MustParseID(wl)}})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t\t}\n\t\tif len(s) != 1 {\n\t\t\tt.Fatalf(\"Expected %v but got %v\", 1, len(s))\n\t\t}\n\t})\n\n\tt.Run(\"filter id and namespace\", func(t *testing.T) {\n\t\t_, err := d.ListServicesWithOptions(ctx, v11.ListServicesOptions{\n\t\t\tNamespace: \"foo\",\n\t\t\tServices: []resource.ID{resource.MustParseID(wl)}})\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected error but got nil\")\n\t\t}\n\t})\n\n\tt.Run(\"filter unsupported id kind\", func(t *testing.T) {\n\t\t_, err := d.ListServicesWithOptions(ctx, v11.ListServicesOptions{\n\t\t\tNamespace: \"foo\",\n\t\t\tServices: []resource.ID{resource.MustParseID(\"default:unsupportedkind/goodbyeworld\")}})\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected error but got nil\")\n\t\t}\n\t})\n}", "func getOpts() []htindex.Option {\n\tvar opts []htindex.Option\n\tcfg := &config{}\n\terr := viper.Unmarshal(cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif cfg.Root != \"\" {\n\t\topts = append(opts, htindex.OptRoot(cfg.Root))\n\t}\n\tif cfg.Input != \"\" {\n\t\topts = append(opts, htindex.OptInput(cfg.Input))\n\t}\n\tif cfg.Output != \"\" {\n\t\topts = append(opts, htindex.OptOutput(cfg.Output))\n\t}\n\tif cfg.Jobs > 0 {\n\t\topts = append(opts, htindex.OptJobs(cfg.Jobs))\n\t}\n\tif cfg.WordsAround > 0 {\n\t\topts = append(opts, htindex.OptWordsAround(cfg.WordsAround))\n\t}\n\tif cfg.ProgressNum > 0 {\n\t\topts = append(opts, htindex.OptProgressNum(cfg.ProgressNum))\n\t}\n\treturn opts\n}", "func (opts *Opts) updateOptions() {\n\tfor option := range opts.rs.edges {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\t// by default the option state is false\n\t\t\topts.options[option] = false\n\t\t\t// if a parent exist the new option takes its state\n\t\t\tif len(opts.rs.edges[option]) > 0 {\n\t\t\t\tparent := opts.rs.edges[option][0] // TODO: what if there are multiple parents?\n\t\t\t\topts.options[option] = opts.options[parent]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor option := range opts.rs.conflicts {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\topts.options[option] = false\n\t\t}\n\t}\n}", "func GetTestOptions() []func(wfe *wfengine.WorkflowEngine) string {\n\treturn []func(wfe *wfengine.WorkflowEngine) string{\n\t\tfunc(wfe *wfengine.WorkflowEngine) string {\n\t\t\t// caching enabled, etc.\n\t\t\treturn \"default options\"\n\t\t},\n\t\tfunc(wfe *wfengine.WorkflowEngine) string {\n\t\t\t// disable caching to test recovery from failure\n\t\t\twfe.DisableActorCaching(true)\n\t\t\treturn \"caching disabled\"\n\t\t},\n\t}\n}", "func addFilterOptions(lo *storage.LookupOptions, cls *semantic.GraphClause, filterOptionsByClause map[*semantic.GraphClause]*filter.StorageOptions) {\n\tif _, ok := filterOptionsByClause[cls]; ok {\n\t\tlo.FilterOptions = filterOptionsByClause[cls]\n\t}\n}", "func (o Aliases) IsOption() {}", "func (o opts) Equal(p opts) bool { return o == p }", "func (m *resmgr) checkOpts() error {\n\tif opt.ForceConfig != \"\" && opt.FallbackConfig != \"\" {\n\t\treturn resmgrError(\"both fallback (%s) and forced (%s) configurations given\",\n\t\t\topt.FallbackConfig, opt.ForceConfig)\n\t}\n\n\treturn nil\n}", "func (mock *DataStoreMock) AddFilterDimensionOptionCalls() []struct {\n\tFilterID string\n\tName string\n\tOption string\n\tTimestamp bson.MongoTimestamp\n\tETagSelector string\n\tCurrentFilter *models.Filter\n} {\n\tvar calls []struct {\n\t\tFilterID string\n\t\tName string\n\t\tOption string\n\t\tTimestamp bson.MongoTimestamp\n\t\tETagSelector string\n\t\tCurrentFilter *models.Filter\n\t}\n\tlockDataStoreMockAddFilterDimensionOption.RLock()\n\tcalls = mock.calls.AddFilterDimensionOption\n\tlockDataStoreMockAddFilterDimensionOption.RUnlock()\n\treturn calls\n}", "func isCountry(str string) bool {\n\tfor _, entry := range govalidator.ISO3166List {\n\t\tif str == entry.EnglishShortName {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func toOptions(in *structs.ActiveData) *Options {\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\topts := &Options{}\n\tfor _, m := range in.Moves {\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.Moves = append(opts.Moves, mov)\n\t\t}\n\t}\n\topts.CanMegaEvolve = in.CanMegaEvolve\n\n\tfor _, m := range in.ZMoves {\n\t\tif m == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.ZMoves = append(opts.ZMoves, mov)\n\t\t}\n\t}\n\topts.CanZMove = len(opts.ZMoves) > 0\n\n\tfor _, m := range in.Dynamax.Moves {\n\t\tmov := toMove(m)\n\t\tif mov != nil {\n\t\t\topts.DMoves = append(opts.DMoves, mov)\n\t\t}\n\t}\n\topts.CanDynamax = in.CanDynamax\n\n\treturn opts\n}", "func CollectOptions(opts ...Option) Options {\n\tvar suiteOpts Options\n\tfor _, o := range opts {\n\t\to(&suiteOpts)\n\t}\n\treturn suiteOpts\n}", "func scanOpts(s *scanner.Scanner) (string, string, string) {\n\n\tws := s.Whitespace\n\tmo := s.Mode\n\tid := s.IsIdentRune\n\n\tdefer func() {\n\t\ts.Whitespace = ws\n\t\ts.Mode = mo\n\t\ts.IsIdentRune = id\n\t}()\n\n\t// only expect letters (at least for now)\n\ts.Whitespace = 1<<'\\t' | 1<<'\\r' | 1<<' ' | 1<<','\n\ts.IsIdentRune = func(ch rune, i int) bool {\n\t\treturn ch == '-' || ch == ';' || ch == '*' || unicode.IsLetter(ch) || unicode.IsDigit(ch)\n\t}\n\ts.Mode = scanner.ScanIdents\n\n\tvar opts, comment, line string\n\n\tvar tok rune\n\tfor tok != scanner.EOF && tok != '\\n' {\n\t\tif tok = s.Scan(); tok == scanner.EOF || tok == '\\n' {\n\t\t\tcontinue\n\t\t}\n\t\tif tok == scanner.Ident {\n\t\t\tif s.TokenText() == \";;;\" {\n\t\t\t\t// skip the current commas\n\t\t\t\tif tok = s.Scan(); tok == scanner.EOF {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// recover the comment text\n\t\t\t\tcomment = scanLine(s)\n\t\t\t} else if s.Peek() != '=' {\n\t\t\t\topts += s.TokenText()\n\t\t\t} else {\n\t\t\t\tline += s.TokenText()\n\t\t\t}\n\t\t} else {\n\t\t\tline += scanLine(s)\n\t\t}\n\t}\n\n\treturn opts, comment, line\n}", "func (self *ToolOptions) PostParse() error {\n\t// build the filter string and options based on the db and collection\n\t// specified, if any\n\n\t/*\n\t\tif self.DB != \"\" {\n\t\t\tself.FilterNS = self.DB + \".\"\n\t\t\tif self.Collection != \"\" {\n\t\t\t\tself.FilterBoth = true\n\t\t\t\tself.FilterNS += self.Collection\n\t\t\t}\n\t\t} else if self.Collection != \"\" {\n\t\t\tself.FilterOnlyColl = true\n\t\t\tself.FilterNS = \".\" + self.Collection\n\t\t}\n\n\t\t// post-parse the extra params\n\t\tif self.ExtraOptions != nil {\n\t\t\tif err := self.ExtraOptions.PostParse(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t*/\n\n\treturn nil\n}", "func optionsEqual(o1, o2 Options) bool {\n\to1v := reflect.ValueOf(&o1).Elem()\n\to2v := reflect.ValueOf(&o2).Elem()\n\tfor i := 0; i < o1v.NumField(); i++ {\n\t\tif o1v.Field(i).CanInterface() {\n\t\t\tkind := o1v.Field(i).Kind()\n\t\t\t// compare values\n\t\t\tswitch kind {\n\t\t\tcase reflect.Bool:\n\t\t\t\tif o1v.Field(i).Bool() != o2v.Field(i).Bool() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\tcase reflect.Int, reflect.Int64:\n\t\t\t\tif o1v.Field(i).Int() != o2v.Field(i).Int() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\tcase reflect.Uint32, reflect.Uint64:\n\t\t\t\tif o1v.Field(i).Uint() != o2v.Field(i).Uint() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\tcase reflect.Float64:\n\t\t\t\tif o1v.Field(i).Float() != o2v.Field(i).Float() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tif o1v.Field(i).String() != o2v.Field(i).String() {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (mock *DataStoreMock) AddFilterDimensionOptionsCalls() []struct {\n\tFilterID string\n\tName string\n\tOptions []string\n\tTimestamp bson.MongoTimestamp\n\tETagSelector string\n\tCurrentFilter *models.Filter\n} {\n\tvar calls []struct {\n\t\tFilterID string\n\t\tName string\n\t\tOptions []string\n\t\tTimestamp bson.MongoTimestamp\n\t\tETagSelector string\n\t\tCurrentFilter *models.Filter\n\t}\n\tlockDataStoreMockAddFilterDimensionOptions.RLock()\n\tcalls = mock.calls.AddFilterDimensionOptions\n\tlockDataStoreMockAddFilterDimensionOptions.RUnlock()\n\treturn calls\n}", "func hasDiffPathOpt(opts []DiffOpt) *DiffPathOpt {\n\tfor _, o := range opts {\n\t\tswitch v := o.(type) {\n\t\tcase *DiffPathOpt:\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func FilterName(value string) TestOptionsFunc {\n\treturn func(_ *testing.T, test *Test) { test.Options.FilterName = value }\n}", "func getOptions(src string) *syntax.FileOptions {\n\t// TODO(adonovan): use new fine-grained names.\n\t// And share with resolve_test.go\n\tallowGlobalReassign := option(src, \"globalreassign\")\n\trecursion := option(src, \"recursion\")\n\treturn &syntax.FileOptions{\n\t\tSet: option(src, \"set\"),\n\t\tWhile: allowGlobalReassign || recursion,\n\t\tTopLevelControl: allowGlobalReassign,\n\t\tGlobalReassign: allowGlobalReassign,\n\t\tLoadBindsGlobally: option(src, \"loadbindsglobally\"),\n\t\tRecursion: recursion,\n\t}\n}", "func (ctx *Context) IsOptions() bool {\r\n\treturn ctx.Is(\"OPTIONS\")\r\n}", "func (s1 *Service) EqualWithOpts(s2 *Service,\n\tignoreID bool, ignoreTS bool) bool {\n\ts1Copy := s1.Service.DeepCopy()\n\ts2Copy := s2.Service.DeepCopy()\n\n\tif ignoreID {\n\t\ts1Copy.ID = nil\n\t\ts2Copy.ID = nil\n\t}\n\tif ignoreTS {\n\t\ts1Copy.CreatedAt = nil\n\t\ts2Copy.CreatedAt = nil\n\n\t\ts1Copy.UpdatedAt = nil\n\t\ts2Copy.UpdatedAt = nil\n\t}\n\treturn reflect.DeepEqual(s1Copy, s2Copy)\n}", "func validateOptions(s string, options []string) (bool, error) {\n\tl := strings.ToLower(s)\n\tfor _, option := range options {\n\t\tif l == option {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"%s is a not a valid option. Valid options are %v\", s, options)\n}", "func (c *Option) Init() (err error) {\n\t// --clear-cache doesn't conduct the scan\n\tif c.ClearCache {\n\t\treturn nil\n\t}\n\n\tc.CustomHeaders = splitCustomHeaders(c.customHeaders)\n\n\t// add token to custom headers\n\tif c.token != \"\" {\n\t\tc.CustomHeaders.Set(c.tokenHeader, c.token)\n\t}\n\n\tif err := c.ReportOption.Init(c.Logger); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.ArtifactOption.Init(c.Context, c.Logger); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func validateCmdLineOpts(start_domain string, max_concurrent int) (bool, string) {\n\tif govalidator.IsURL(start_domain) == false {\n\t\treturn false, fmt.Sprintf(\"Please specify a valid URL to crawl. You entered %s.\\n\", start_domain)\n\t}\n\t// We only need to confirm if start_domain starts with http.\n\t// govalidator validates absolute and non-absolute URLs. If an absolute URL\n\t// is entered in a illegal format, govalidator will catch it.\n\tif strings.HasPrefix(start_domain, \"http\") == false {\n\t\treturn false, fmt.Sprintf(\"The domain name must be in the form http[s]://name.xx. You entered %s.\\n\", start_domain)\n\t}\n\tif max_concurrent < 1 || max_concurrent > 50 {\n\t\treturn false, fmt.Sprintf(\"Max concurrent process value must be between 1 and 50. You entered %d.\\n\", max_concurrent)\n\t}\n\treturn true, \"\"\n}", "func init() {\n\toptions.only = make(SelectedCollectors)\n\toptions.exclude = make(SelectedCollectors)\n\n\tflag.Var(&options.only, \"only\", \"Run only the listed collectors (comma-separated list of collector names)\")\n\tflag.Var(&options.exclude, \"exclude\", \"Run all the collectors except those listed (comma-separated list of collector names)\")\n\tflag.StringVar(&options.logLevel, \"log-level\", \"info\", \"Log level (one of 'warn', 'info', 'debug')\")\n}", "func ParseOptions() *Options {\n\toptions := &Options{}\n\tflagSet := goflags.NewFlagSet()\n\tflagSet.SetDescription(`dnsx is a fast and multi-purpose DNS toolkit allow to run multiple probes using retryabledns library.`)\n\n\tflagSet.CreateGroup(\"input\", \"Input\",\n\t\tflagSet.StringVarP(&options.Hosts, \"list\", \"l\", \"\", \"list of sub(domains)/hosts to resolve (file or stdin)\"),\n\t\tflagSet.StringVarP(&options.Domains, \"domain\", \"d\", \"\", \"list of domain to bruteforce (file or comma separated or stdin)\"),\n\t\tflagSet.StringVarP(&options.WordList, \"wordlist\", \"w\", \"\", \"list of words to bruteforce (file or comma separated or stdin)\"),\n\t)\n\n\tflagSet.CreateGroup(\"query\", \"Query\",\n\t\tflagSet.BoolVar(&options.A, \"a\", false, \"query A record (default)\"),\n\t\tflagSet.BoolVar(&options.AAAA, \"aaaa\", false, \"query AAAA record\"),\n\t\tflagSet.BoolVar(&options.CNAME, \"cname\", false, \"query CNAME record\"),\n\t\tflagSet.BoolVar(&options.NS, \"ns\", false, \"query NS record\"),\n\t\tflagSet.BoolVar(&options.TXT, \"txt\", false, \"query TXT record\"),\n\t\tflagSet.BoolVar(&options.SRV, \"srv\", false, \"query SRV record\"),\n\t\tflagSet.BoolVar(&options.PTR, \"ptr\", false, \"query PTR record\"),\n\t\tflagSet.BoolVar(&options.MX, \"mx\", false, \"query MX record\"),\n\t\tflagSet.BoolVar(&options.SOA, \"soa\", false, \"query SOA record\"),\n\t\tflagSet.BoolVar(&options.AXFR, \"axfr\", false, \"query AXFR\"),\n\t\tflagSet.BoolVar(&options.CAA, \"caa\", false, \"query CAA record\"),\n\t)\n\n\tflagSet.CreateGroup(\"filter\", \"Filter\",\n\t\tflagSet.BoolVarP(&options.Response, \"resp\", \"re\", false, \"display dns response\"),\n\t\tflagSet.BoolVarP(&options.ResponseOnly, \"resp-only\", \"ro\", false, \"display dns response only\"),\n\t\tflagSet.StringVarP(&options.RCode, \"rcode\", \"rc\", \"\", \"filter result by dns status code (eg. -rcode noerror,servfail,refused)\"),\n\t)\n\n\tflagSet.CreateGroup(\"probe\", \"Probe\",\n\t\tflagSet.BoolVar(&options.OutputCDN, \"cdn\", false, \"display cdn name\"),\n\t\tflagSet.BoolVar(&options.ASN, \"asn\", false, \"display host asn information\"),\n\t)\n\n\tflagSet.CreateGroup(\"rate-limit\", \"Rate-limit\",\n\t\tflagSet.IntVarP(&options.Threads, \"threads\", \"t\", 100, \"number of concurrent threads to use\"),\n\t\tflagSet.IntVarP(&options.RateLimit, \"rate-limit\", \"rl\", -1, \"number of dns request/second to make (disabled as default)\"),\n\t)\n\n\tflagSet.CreateGroup(\"update\", \"Update\",\n\t\tflagSet.CallbackVarP(GetUpdateCallback(), \"update\", \"up\", \"update dnsx to latest version\"),\n\t\tflagSet.BoolVarP(&options.DisableUpdateCheck, \"disable-update-check\", \"duc\", false, \"disable automatic dnsx update check\"),\n\t)\n\n\tflagSet.CreateGroup(\"output\", \"Output\",\n\t\tflagSet.StringVarP(&options.OutputFile, \"output\", \"o\", \"\", \"file to write output\"),\n\t\tflagSet.BoolVar(&options.JSON, \"json\", false, \"write output in JSONL(ines) format\"),\n\t)\n\n\tflagSet.CreateGroup(\"debug\", \"Debug\",\n\t\tflagSet.BoolVarP(&options.HealthCheck, \"health-check\", \"hc\", false, \"run diagnostic check up\"),\n\t\tflagSet.BoolVar(&options.Silent, \"silent\", false, \"display only results in the output\"),\n\t\tflagSet.BoolVarP(&options.Verbose, \"verbose\", \"v\", false, \"display verbose output\"),\n\t\tflagSet.BoolVarP(&options.Raw, \"debug\", \"raw\", false, \"display raw dns response\"),\n\t\tflagSet.BoolVar(&options.ShowStatistics, \"stats\", false, \"display stats of the running scan\"),\n\t\tflagSet.BoolVar(&options.Version, \"version\", false, \"display version of dnsx\"),\n\t)\n\n\tflagSet.CreateGroup(\"optimization\", \"Optimization\",\n\t\tflagSet.IntVar(&options.Retries, \"retry\", 2, \"number of dns attempts to make (must be at least 1)\"),\n\t\tflagSet.BoolVarP(&options.HostsFile, \"hostsfile\", \"hf\", false, \"use system host file\"),\n\t\tflagSet.BoolVar(&options.Trace, \"trace\", false, \"perform dns tracing\"),\n\t\tflagSet.IntVar(&options.TraceMaxRecursion, \"trace-max-recursion\", math.MaxInt16, \"Max recursion for dns trace\"),\n\t\tflagSet.BoolVar(&options.Resume, \"resume\", false, \"resume existing scan\"),\n\t\tflagSet.BoolVar(&options.Stream, \"stream\", false, \"stream mode (wordlist, wildcard, stats and stop/resume will be disabled)\"),\n\t)\n\n\tflagSet.CreateGroup(\"configs\", \"Configurations\",\n\t\tflagSet.StringVarP(&options.Resolvers, \"resolver\", \"r\", \"\", \"list of resolvers to use (file or comma separated)\"),\n\t\tflagSet.IntVarP(&options.WildcardThreshold, \"wildcard-threshold\", \"wt\", 5, \"wildcard filter threshold\"),\n\t\tflagSet.StringVarP(&options.WildcardDomain, \"wildcard-domain\", \"wd\", \"\", \"domain name for wildcard filtering (other flags will be ignored - only json output is supported)\"),\n\t)\n\n\t_ = flagSet.Parse()\n\n\tif options.HealthCheck {\n\t\tgologger.Print().Msgf(\"%s\\n\", DoHealthCheck(options, flagSet))\n\t\tos.Exit(0)\n\t}\n\n\t// Read the inputs and configure the logging\n\toptions.configureOutput()\n\n\terr := options.configureRcodes()\n\tif err != nil {\n\t\tgologger.Fatal().Msgf(\"%s\\n\", err)\n\t}\n\n\terr = options.configureResume()\n\tif err != nil {\n\t\tgologger.Fatal().Msgf(\"%s\\n\", err)\n\t}\n\n\tshowBanner()\n\n\tif options.Version {\n\t\tgologger.Info().Msgf(\"Current Version: %s\\n\", version)\n\t\tos.Exit(0)\n\t}\n\n\tif !options.DisableUpdateCheck {\n\t\tlatestVersion, err := updateutils.GetToolVersionCallback(\"dnsx\", version)()\n\t\tif err != nil {\n\t\t\tif options.Verbose {\n\t\t\t\tgologger.Error().Msgf(\"dnsx version check failed: %v\", err.Error())\n\t\t\t}\n\t\t} else {\n\t\t\tgologger.Info().Msgf(\"Current dnsx version %v %v\", version, updateutils.GetVersionDescription(version, latestVersion))\n\t\t}\n\t}\n\n\toptions.validateOptions()\n\n\treturn options\n}", "func getRemoteOptions(p *PodmanTestIntegration, args []string) []string {\n\treturn nil\n}", "func (self *LdapSearchApp) ParseOpts() (*LdapSearchOptions, error){\n\tvar opts LdapSearchOptions\n\n\tflag.StringVar(&opts.host, \"host\", \"ldap://localhost:389/\", \"ldap server URL format : ldap[s]://hostname:port/\")\n\tflag.StringVar(&opts.user, \"user\", \"\" , \"user for authentification\")\n\tflag.StringVar(&opts.passwd, \"passwd\", \"\" , \"password for authentification\")\n\tflag.StringVar(&opts.base, \"base\", \"\" , \"base DN for search\")\n\n\tflag.Parse()\n\n\tif flag.NArg() == 0 {\n\t\tself.Usage()\n\t\treturn nil, errors.New(fmt.Sprintf(\"ParseOpts() error ; see usage for more information\"))\n\t}\n\n\topts.filter = flag.Arg(0)\n\n\tif len(flag.Args()) == 1 {\n\t\topts.attributes = []string{}\n\t} else {\n\t\topts.attributes = flag.Args()[1:]\n\t}\n\n\treturn &opts, nil\n}", "func configureFlags(api *operations.OpenMockAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.KubernikusAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.SwaggertestAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func ParseOpts() {\n\t//this setups the logger so that it prints file numbers\n\tflags.Parse(&opts)\n\n\tif opts.ConfigPath != \"\" {\n\t\tlog.Info(\"loading config from: \", opts.ConfigPath)\n\t\tconfigLoader.LoadConfig(opts.ConfigPath, &Settings)\n\t} else {\n\n\t}\n\n\tif opts.AccessKey != \"\" && opts.SecretKey != \"\" {\n\t\tSettings.Auth.AccessKey = opts.AccessKey\n\t\tSettings.Auth.SecretKey = opts.SecretKey\n\t}\n\n\tloggerConfig.ConfigLogger(Settings.Logdir)\n}", "func ProcessOptions(options []string, isTmpfs bool, sourcePath string) ([]string, error) {\n\tvar (\n\t\tfoundWrite, foundSize, foundProp, foundMode, foundExec, foundSuid, foundDev, foundCopyUp, foundBind, foundZ, foundU, foundOverlay, foundIdmap, foundCopy, foundNoSwap bool\n\t)\n\n\tnewOptions := make([]string, 0, len(options))\n\tfor _, opt := range options {\n\t\t// Some options have parameters - size, mode\n\t\tsplitOpt := strings.SplitN(opt, \"=\", 2)\n\n\t\t// add advanced options such as upperdir=/path and workdir=/path, when overlay is specified\n\t\tif foundOverlay {\n\t\t\tif strings.Contains(opt, \"upperdir\") {\n\t\t\t\tnewOptions = append(newOptions, opt)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.Contains(opt, \"workdir\") {\n\t\t\t\tnewOptions = append(newOptions, opt)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(splitOpt[0], \"subpath\") {\n\t\t\tnewOptions = append(newOptions, opt)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(splitOpt[0], \"idmap\") {\n\t\t\tif foundIdmap {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'idmap' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundIdmap = true\n\t\t\tnewOptions = append(newOptions, opt)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch splitOpt[0] {\n\t\tcase \"copy\", \"nocopy\":\n\t\t\tif foundCopy {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'nocopy' and 'copy' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundCopy = true\n\t\tcase \"O\":\n\t\t\tfoundOverlay = true\n\t\tcase \"volume-opt\":\n\t\t\t// Volume-opt should be relayed and processed by driver.\n\t\t\tnewOptions = append(newOptions, opt)\n\t\tcase \"exec\", \"noexec\":\n\t\t\tif foundExec {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'noexec' and 'exec' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundExec = true\n\t\tcase \"suid\", \"nosuid\":\n\t\t\tif foundSuid {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'nosuid' and 'suid' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundSuid = true\n\t\tcase \"nodev\", \"dev\":\n\t\t\tif foundDev {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'nodev' and 'dev' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundDev = true\n\t\tcase \"rw\", \"ro\":\n\t\t\tif foundWrite {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'rw' and 'ro' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundWrite = true\n\t\tcase \"private\", \"rprivate\", \"slave\", \"rslave\", \"shared\", \"rshared\", \"unbindable\", \"runbindable\":\n\t\t\tif foundProp {\n\t\t\t\treturn nil, fmt.Errorf(\"only one root propagation mode can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundProp = true\n\t\tcase \"size\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'size' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundSize {\n\t\t\t\treturn nil, fmt.Errorf(\"only one tmpfs size can be specified: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundSize = true\n\t\tcase \"mode\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'mode' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundMode {\n\t\t\t\treturn nil, fmt.Errorf(\"only one tmpfs mode can be specified: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundMode = true\n\t\tcase \"tmpcopyup\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpcopyup' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundCopyUp {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpcopyup' or 'notmpcopyup' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundCopyUp = true\n\t\tcase \"consistency\":\n\t\t\t// Often used on MACs and mistakenly on Linux platforms.\n\t\t\t// Since Docker ignores this option so shall we.\n\t\t\tcontinue\n\t\tcase \"notmpcopyup\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'notmpcopyup' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundCopyUp {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpcopyup' or 'notmpcopyup' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundCopyUp = true\n\t\t\t// do not propagate notmpcopyup to the OCI runtime\n\t\t\tcontinue\n\t\tcase \"noswap\":\n\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'noswap' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif rootless.IsRootless() {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'noswap' option is only allowed with rootful tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundNoSwap {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpswap' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundNoSwap = true\n\t\t\tnewOptions = append(newOptions, opt)\n\t\t\tcontinue\n\t\tcase define.TypeBind, \"rbind\":\n\t\t\tif isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'bind' and 'rbind' options are not allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundBind {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'rbind' and 'bind' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundBind = true\n\t\tcase \"z\", \"Z\":\n\t\t\tif isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'z' and 'Z' options are not allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundZ {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'z' and 'Z' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundZ = true\n\t\tcase \"U\":\n\t\t\tif foundU {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'U' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundU = true\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown mount option %q: %w\", opt, ErrBadMntOption)\n\t\t}\n\t\tnewOptions = append(newOptions, opt)\n\t}\n\n\tif !foundWrite {\n\t\tnewOptions = append(newOptions, \"rw\")\n\t}\n\tif !foundProp {\n\t\tnewOptions = append(newOptions, \"rprivate\")\n\t}\n\tdefaults, err := getDefaultMountOptions(sourcePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !foundExec && defaults.noexec {\n\t\tnewOptions = append(newOptions, \"noexec\")\n\t}\n\tif !foundSuid && defaults.nosuid {\n\t\tnewOptions = append(newOptions, \"nosuid\")\n\t}\n\tif !foundDev && defaults.nodev {\n\t\tnewOptions = append(newOptions, \"nodev\")\n\t}\n\tif isTmpfs && !foundCopyUp {\n\t\tnewOptions = append(newOptions, \"tmpcopyup\")\n\t}\n\tif !isTmpfs && !foundBind {\n\t\tnewOptions = append(newOptions, \"rbind\")\n\t}\n\n\treturn newOptions, nil\n}", "func expandKeyTestingOptions(c *Client, f *KeyTestingOptions, res *Key) (map[string]interface{}, error) {\n\tif dcl.IsEmptyValueIndirect(f) {\n\t\treturn nil, nil\n\t}\n\n\tm := make(map[string]interface{})\n\tif v := f.TestingScore; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"testingScore\"] = v\n\t}\n\tif v := f.TestingChallenge; !dcl.IsEmptyValueIndirect(v) {\n\t\tm[\"testingChallenge\"] = v\n\t}\n\n\treturn m, nil\n}", "func NewOpts(exhaustCount int64) *opts {\n\treturn &opts{exhaustionCount: exhaustCount}\n}", "func isInOptions(config sonarExecuteScanOptions, property string) bool {\n\tproperty = strings.TrimSuffix(property, \"=\")\n\treturn piperutils.ContainsStringPart(config.Options, property)\n}", "func (i *iniparamsContainer) keyChk() *iniparamsContainer {\r\n\tboolkeys := []string{\r\n\t\t\"jsonparser\",\r\n\t\t\"public\",\r\n\t\t\"list\",\r\n\t\t\"deleteall\",\r\n\t\t\"anonymous\",\r\n\t\t\"listasjson\",\r\n\t\t\"channellist\",\r\n\t\t\"filelist\",\r\n\t\t\"channelhistory\",\r\n\t\t\"deletefiles\",\r\n\t\t\"simpleresult\",\r\n\t\t\"chkgisttoken\",\r\n\t\t\"filelistasjson\",\r\n\t\t\"appcheck\",\r\n\t}\r\n\tfor _, key := range boolkeys {\r\n\t\tif i.chkArgs(key) == nil {\r\n\t\t\ti.jsonControl.Options[key] = false\r\n\t\t}\r\n\t}\r\n\tstringkeys := []string{\r\n\t\t\"title\",\r\n\t\t\"cfgdirectory\",\r\n\t\t\"files\",\r\n\t\t\"get\",\r\n\t\t\"updateoverwrite\",\r\n\t\t\"updateadd\",\r\n\t\t\"delete\",\r\n\t\t\"filenames\",\r\n\t\t\"file\",\r\n\t\t\"channel\",\r\n\t\t\"content\",\r\n\t\t\"filetype\",\r\n\t\t\"initialcomment\",\r\n\t\t\"user\",\r\n\t\t\"deletefile\",\r\n\t\t\"deletehistory\",\r\n\t\t\"gistclientid\",\r\n\t\t\"gistclientsecret\",\r\n\t\t\"slackclientid\",\r\n\t\t\"slackclientsecret\",\r\n\t\t\"gistcode\",\r\n\t\t\"slackcode\",\r\n\t\t\"getfile\",\r\n\t\t\"workdir\",\r\n\t\t\"getversion\",\r\n\t\t\"gethistory\",\r\n\t}\r\n\tfor _, key := range stringkeys {\r\n\t\tif i.chkArgs(key) == nil {\r\n\t\t\ti.jsonControl.Options[key] = \"\"\r\n\t\t}\r\n\t}\r\n\tif i.chkArgs(\"deletehistories\") == nil {\r\n\t\ti.jsonControl.Options[\"deletehistories\"] = 0\r\n\t} else {\r\n\t\ti.jsonControl.Options[\"deletehistories\"] = int(i.jsonControl.Options[\"deletehistories\"].(float64))\r\n\t}\r\n\tif i.chkArgs(\"port\") == nil {\r\n\t\ti.jsonControl.Options[\"port\"] = 8080\r\n\t} else {\r\n\t\ti.jsonControl.Options[\"port\"] = int(i.jsonControl.Options[\"port\"].(float64))\r\n\t}\r\n\ti.jsonControl.Options[\"usejsoncontrol\"] = true\r\n\treturn i\r\n}", "func expandKeyTestingOptionsSlice(c *Client, f []KeyTestingOptions, res *Key) ([]map[string]interface{}, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\n\titems := []map[string]interface{}{}\n\tfor _, item := range f {\n\t\ti, err := expandKeyTestingOptions(c, &item, res)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\titems = append(items, i)\n\t}\n\n\treturn items, nil\n}", "func configureFlags(api *operations.OpenPitrixAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func sortOptions(meta *meta, args []string, toSuggest string, suggestions []string) []string {\n\tcommand := getCommand(meta, args, toSuggest)\n\tif command == nil {\n\t\treturn suggestions\n\t}\n\n\targSpecs := []ShellSuggestion(nil)\n\tfor _, suggest := range suggestions {\n\t\targSpec := command.ArgSpecs.GetByName(optionToArgSpecName(suggest))\n\t\targSpecs = append(argSpecs, ShellSuggestion{\n\t\t\tText: suggest,\n\t\t\tArg: argSpec,\n\t\t})\n\t}\n\n\tsort.Slice(argSpecs, func(i, j int) bool {\n\t\tif argSpecs[i].Arg != nil && argSpecs[j].Arg != nil && argSpecs[i].Arg.Required != argSpecs[j].Arg.Required {\n\t\t\treturn argSpecs[i].Arg.Required\n\t\t}\n\t\treturn argSpecs[i].Text < argSpecs[j].Text\n\t})\n\n\tsuggests := []string(nil)\n\tfor _, argSpec := range argSpecs {\n\t\tsuggests = append(suggests, argSpec.Text)\n\t}\n\n\treturn suggests\n}", "func passesOpenSwathFilters(line []string, options types.Parameters) bool {\n\tisDecoy, _ := strconv.Atoi(line[1])\n\tif options.IgnoreDecoys && isDecoy == 1 {\n\t\treturn false\n\t}\n\n\tmScore, _ := strconv.ParseFloat(line[22], 64)\n\tmScorePeptideExperimentWide, _ := strconv.ParseFloat(line[27], 64)\n\tpeakGroupRank, _ := strconv.Atoi(line[20])\n\n\tif mScore <= options.Mscore &&\n\t\tmScorePeptideExperimentWide <= options.MscorePeptideExperimentWide &&\n\t\tpeakGroupRank <= options.PeakGroupRank {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (*DiffPathOpt) IsDiffOpt() {}", "func TestIsOtherGeoGeoKeys(t *testing.T) {\n\tgeoKeys := []string{\"geo\", \"loc\", \"location\", \"coord\", \"coordinate\", \"coords\", \"coordinates\"}\n\n\t// For each geoKey we expect the same result\n\texp := Geo{\n\t\tGeo: map[string]interface{}{\n\t\t\t\"type\": \"Point\",\n\t\t\t\"coordinates\": []interface{}{float64(10), float64(-10)},\n\t\t},\n\t}\n\n\tdebugLog(\"===Begin TestIsOtherGeoGeoKeys===\")\n\tfor _, geoKey := range geoKeys {\n\t\trunIsOtherGeoTest(t, map[string]interface{}{\n\t\t\tgeoKey: []float64{10, -10},\n\t\t}, true, &exp)\n\t}\n\tdebugLog(\"===End TestIsOtherGeoGeoKeys===\")\n}", "func configureFlags(api *operations.JiliAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func execIsSorted(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := sort.IsSorted(args[0].(sort.Interface))\n\tp.Ret(1, ret)\n}", "func (p1 *Plugin) EqualWithOpts(p2 *Plugin, ignoreID,\n\tignoreTS, ignoreForeign bool) bool {\n\tp1Copy := p1.Plugin.DeepCopy()\n\tp2Copy := p2.Plugin.DeepCopy()\n\n\tif ignoreID {\n\t\tp1Copy.ID = nil\n\t\tp2Copy.ID = nil\n\t}\n\tif ignoreTS {\n\t\tp1Copy.CreatedAt = nil\n\t\tp2Copy.CreatedAt = nil\n\t}\n\tif ignoreForeign {\n\t\tp1Copy.Service = nil\n\t\tp1Copy.Route = nil\n\t\tp1Copy.Consumer = nil\n\t\tp2Copy.Service = nil\n\t\tp2Copy.Route = nil\n\t\tp2Copy.Consumer = nil\n\t}\n\treturn reflect.DeepEqual(p1Copy, p2Copy)\n}", "func (p *preprocessor) checkSetOprSelectList(stmt *ast.SetOprSelectList) {\n\tfor _, sel := range stmt.Selects[:len(stmt.Selects)-1] {\n\t\tswitch s := sel.(type) {\n\t\tcase *ast.SelectStmt:\n\t\t\tif s.SelectIntoOpt != nil {\n\t\t\t\tp.err = ErrWrongUsage.GenWithStackByArgs(\"UNION\", \"INTO\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif s.IsInBraces {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif s.Limit != nil {\n\t\t\t\tp.err = ErrWrongUsage.GenWithStackByArgs(\"UNION\", \"LIMIT\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif s.OrderBy != nil {\n\t\t\t\tp.err = ErrWrongUsage.GenWithStackByArgs(\"UNION\", \"ORDER BY\")\n\t\t\t\treturn\n\t\t\t}\n\t\tcase *ast.SetOprSelectList:\n\t\t\tp.checkSetOprSelectList(s)\n\t\t}\n\t}\n}", "func (g *GenOpts) CheckOpts() error {\n\tif g == nil {\n\t\treturn errors.New(\"gen opts are required\")\n\t}\n\n\tif !filepath.IsAbs(g.Target) {\n\t\tif _, err := filepath.Abs(g.Target); err != nil {\n\t\t\treturn fmt.Errorf(\"could not locate target %s: %v\", g.Target, err)\n\t\t}\n\t}\n\n\tif filepath.IsAbs(g.ServerPackage) {\n\t\treturn fmt.Errorf(\"you shouldn't specify an absolute path in --server-package: %s\", g.ServerPackage)\n\t}\n\n\tif strings.HasPrefix(g.Spec, \"http://\") || strings.HasPrefix(g.Spec, \"https://\") {\n\t\treturn nil\n\t}\n\n\tpth, err := findSwaggerSpec(g.Spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ensure spec path is absolute\n\tg.Spec, err = filepath.Abs(pth)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not locate spec: %s\", g.Spec)\n\t}\n\n\treturn nil\n}", "func (input *BeegoInput) IsOptions() bool {\n\treturn input.Is(\"OPTIONS\")\n}", "func Setup(options ...Option) {\n\tfor _, opt := range options {\n\t\topt()\n\t}\n}", "func validateOpts(opts VerifyOpts) error {\n\tcheckPub := len(opts.TrustedAKs) > 0\n\tcheckCert := len(opts.TrustedRootCerts) > 0\n\tif !checkPub && !checkCert {\n\t\treturn fmt.Errorf(\"no trust mechanism provided, either use TrustedAKs or TrustedRootCerts\")\n\t}\n\tif checkPub && checkCert {\n\t\treturn fmt.Errorf(\"multiple trust mechanisms provided, only use one of TrustedAKs or TrustedRootCerts\")\n\t}\n\treturn nil\n}", "func configureFlags(api *operations.CalculatorAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func aggregateOptionsFromCommerceOptions(payload *app.CommerceOptionsPayload) (model.AggregateOptions, error) {\n\tvar o model.AggregateOptions\n\n\tfor _, val := range payload.FilterBy {\n\t\tfb := &model.FilterBy{\n\t\t\tTag: val.Tag,\n\t\t\tValues: val.Values,\n\t\t\tInverse: false,\n\t\t}\n\t\tif val.Inverse != nil {\n\t\t\tfb.Inverse = *val.Inverse\n\t\t}\n\t\to.FilterBy = append(o.FilterBy, fb)\n\t}\n\n\to.GroupBy = payload.GroupBy\n\tif payload.TimeAfter != nil {\n\t\to.TimeAfter = *payload.TimeAfter\n\t}\n\tif payload.TimeBefore != nil {\n\t\to.TimeBefore = *payload.TimeBefore\n\t}\n\n\tif payload.Step != nil {\n\t\to.Step = *payload.Step\n\t}\n\n\tif payload.TimeHistogram != nil {\n\t\to.TimeHistogram = &model.TimeHistogram{\n\t\t\tInterval: payload.TimeHistogram.Interval,\n\t\t}\n\n\t\tif payload.TimeHistogram.TimeZone != nil {\n\t\t\tlocation, err := time.LoadLocation(*payload.TimeHistogram.TimeZone)\n\t\t\tif err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t\to.TimeHistogram.TimeZone = location\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (ssc ScreenSizeCriterion) AsCarrierCountryCriterion() (*CarrierCountryCriterion, bool) {\n\treturn nil, false\n}", "func getGrpcOpts(log logging.Logger, cfgTransport *security.TransportConfig) ([]grpc.ServerOption, error) {\n\tunaryInterceptors := []grpc.UnaryServerInterceptor{\n\t\tunaryLoggingInterceptor(log), // must be first in order to properly log errors\n\t\tunaryErrorInterceptor,\n\t\tunaryStatusInterceptor,\n\t\tunaryVersionInterceptor,\n\t}\n\tstreamInterceptors := []grpc.StreamServerInterceptor{\n\t\tstreamErrorInterceptor,\n\t}\n\ttcOpt, err := security.ServerOptionForTransportConfig(cfgTransport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsrvOpts := []grpc.ServerOption{tcOpt}\n\n\tuintOpt, err := unaryInterceptorForTransportConfig(cfgTransport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif uintOpt != nil {\n\t\tunaryInterceptors = append(unaryInterceptors, uintOpt)\n\t}\n\tsintOpt, err := streamInterceptorForTransportConfig(cfgTransport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif sintOpt != nil {\n\t\tstreamInterceptors = append(streamInterceptors, sintOpt)\n\t}\n\n\treturn append(srvOpts, []grpc.ServerOption{\n\t\tgrpc.ChainUnaryInterceptor(unaryInterceptors...),\n\t\tgrpc.ChainStreamInterceptor(streamInterceptors...),\n\t}...), nil\n}", "func processCommandLineFlags(s *suite.Suite) {\n\tgetopt.HelpColumn = 35\n\tgetopt.DisplayWidth = 120\n\tgetopt.SetParameters(\"\")\n\tgetopt.Parse()\n\n\t// Lets check to see if the version command line flag was given. If it is\n\t// lets print out the version information and exit.\n\tif *bOptVer {\n\t\tprintOutputHeader()\n\t\tos.Exit(0)\n\t}\n\n\t// Lets check to see if the help command line flag was given. If it is lets\n\t// print out the help information and exit.\n\tif *bOptHelp {\n\t\tprintOutputHeader()\n\t\tgetopt.Usage()\n\t\tos.Exit(0)\n\t}\n\n\t// ------------------------------------------------------------\n\t// Map command line parameters to struct values\n\t// ------------------------------------------------------------\n\ts.Verbose = *bOptVerbose\n\ts.Debug = *bOptDebug\n\n\ts.Settings.URL = *sOptURL\n\ts.Settings.Proxy = *sOptProxy\n\ts.Settings.Discovery = *sOptDiscovery\n\ts.Settings.APIRoot = *sOptAPIRoot\n\ts.Settings.Username = *sOptUsername\n\ts.Settings.Password = *sOptPassword\n\n\ts.CollectionIDs.ReadOnly = *sOptReadOnly\n\ts.CollectionIDs.WriteOnly = *sOptWriteOnly\n\ts.CollectionIDs.ReadWrite = *sOptReadWrite\n}", "func setupFlags(params, paramsJSON string) *pflag.FlagSet {\n\tflagSet := pflag.NewFlagSet(\"TestGetParamsFromFlags\", pflag.PanicOnError)\n\tregisterParamsFlags(flagSet)\n\t// mirror actual usage by using Parse rather than Set\n\tcmdline := []string{\"apply\"}\n\tif params != \"\" {\n\t\tcmdline = append(cmdline, \"--params\", params)\n\t}\n\tif paramsJSON != \"\" {\n\t\tcmdline = append(cmdline, \"--paramsJSON\", paramsJSON)\n\t}\n\n\tif err := flagSet.Parse(append(cmdline, \"samples/test.hcl\")); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn flagSet\n}", "func ByCountry(country Country) (c currencies, ok bool) {\n\tc, ok = currenciesByCountry[country.String()]\n\treturn\n}", "func getGeneralCountryInformation(c *gin.Context) {\n var params gciQueryParams\n _ = c.Bind(&params)\n\n if !params.Sort.isValid() {\n params.Sort = confirmed\n }\n\n if !params.Order.isValid() {\n params.Order = descending\n }\n\n columns := []string{\n \"l.id country_id\",\n \"l.country\",\n \"sum(r.confirmed) confirmed\",\n \"sum(r.recovered) recovered\",\n \"sum(r.deaths) deaths\",\n }\n query := databaseManager.\n DB.\n Table(\"location l\").\n Select(columns).\n Joins(\"inner join record r on l.id = r.location_id\").\n Group(\"l.id, l.country\").\n Order(fmt.Sprintf(\"%s %s\", string(params.Sort), string(params.Order)))\n\n var results []gci\n query.Find(&results)\n\n if params.First != 0 {\n OK(c, results[:int(math.Min(float64(params.First), float64(len(results))))])\n } else if params.Last != 0 {\n OK(c, results[len(results)-params.Last:])\n } else {\n OK(c, results)\n }\n}", "func setShowInList(infos map[string]*FeatureInfo, inclExperimental bool, gateName string) {\n\tfor _, v := range infos {\n\t\t// Only discoverable features can be listed.\n\t\tv.ShowInList = v.Discoverable\n\n\t\t// Experimental features are not listed by default, but can be listed via flag.\n\t\tif v.Stability == corev1alpha2.Experimental {\n\t\t\tv.ShowInList = inclExperimental\n\t\t}\n\n\t\t// If FeatureGate is specified, delist the Features not gated.\n\t\tif gateName != \"\" && v.FeatureGate != gateName {\n\t\t\tv.ShowInList = false\n\t\t}\n\t}\n}", "func IsOptionSet(name string, f *flag.FlagSet) bool {\n\tset := false\n\tf.Visit(func(f *flag.Flag) {\n\t\tif f.Name == name {\n\t\t\tset = true\n\t\t}\n\t})\n\treturn set\n}", "func (t1 *Target) EqualWithOpts(t2 *Target, ignoreID,\n\tignoreTS, ignoreForeign bool) bool {\n\tt1Copy := t1.Target.DeepCopy()\n\tt2Copy := t2.Target.DeepCopy()\n\n\tif ignoreID {\n\t\tt1Copy.ID = nil\n\t\tt2Copy.ID = nil\n\t}\n\tif ignoreTS {\n\t\tt1Copy.CreatedAt = nil\n\t\tt2Copy.CreatedAt = nil\n\t}\n\tif ignoreForeign {\n\t\tt1Copy.Upstream = nil\n\t\tt2Copy.Upstream = nil\n\t}\n\treturn reflect.DeepEqual(t1Copy, t2Copy)\n}", "func (mr *MockPlacementGroupClientMockRecorder) AllWithOpts(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AllWithOpts\", reflect.TypeOf((*MockPlacementGroupClient)(nil).AllWithOpts), arg0, arg1)\n}", "func (cpy *impl) IsSkip(selected []string, omit []string, srcName string, dstName string) (ret bool) {\n\tvar i int\n\n\t// Only selected fields\n\tif len(selected) > 0 {\n\t\tret = true\n\t\tfor i = range selected {\n\t\t\tif selected[i] == srcName || selected[i] == dstName {\n\t\t\t\tret = false\n\t\t\t}\n\t\t}\n\t}\n\t// All fields except selected\n\tif len(omit) > 0 {\n\t\tret = false\n\t\tfor i = range omit {\n\t\t\tif omit[i] == srcName || omit[i] == dstName {\n\t\t\t\tret = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}", "func retrieveModelConntrackOptionsFlags(depth int, m *models.ConntrackOptions, cmdPrefix string, cmd *cobra.Command) (error, bool) {\n\tretAdded := false\n\n\terr, expectTableSizeAdded := retrieveConntrackOptionsExpectTableSizeFlags(depth, m, cmdPrefix, cmd)\n\tif err != nil {\n\t\treturn err, false\n\t}\n\tretAdded = retAdded || expectTableSizeAdded\n\n\terr, tableSizeAdded := retrieveConntrackOptionsTableSizeFlags(depth, m, cmdPrefix, cmd)\n\tif err != nil {\n\t\treturn err, false\n\t}\n\tretAdded = retAdded || tableSizeAdded\n\n\terr, tcpLooseAdded := retrieveConntrackOptionsTCPLooseFlags(depth, m, cmdPrefix, cmd)\n\tif err != nil {\n\t\treturn err, false\n\t}\n\tretAdded = retAdded || tcpLooseAdded\n\n\terr, tcpMaxRetransAdded := retrieveConntrackOptionsTCPMaxRetransFlags(depth, m, cmdPrefix, cmd)\n\tif err != nil {\n\t\treturn err, false\n\t}\n\tretAdded = retAdded || tcpMaxRetransAdded\n\n\treturn nil, retAdded\n}", "func configureFlags(api *operations.ControlAsistenciaAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (o *MicrosoftGraphWorkbookSortField) GetDataOptionOk() (string, bool) {\n\tif o == nil || o.DataOption == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.DataOption, true\n}", "func isOptionShort(inString string) (bool, []string) {\r\n\tvar rx *regexp.Regexp = regexp.MustCompile(`(?i)^(-)?([!?a-z0-9]+)$`)\r\n\tm := rx.FindAllStringSubmatch(inString, -1)\r\n\tif nil == m { return false, nil }\r\n\tif 1 == len(m[0][2]) {\r\n\t\treturn true, []string{m[0][2]}\r\n\t}\r\n\r\n\tres := make([]string, 0)\r\n\t// If necessary, split a compound into its components (ex: \"-vh\" => \"-v -h\").\r\n\tfor _, c := range m[0][2] {\r\n\t\tres = append(res, fmt.Sprintf(\"%c\", c))\r\n\t}\r\n\treturn true, res\r\n}", "func (c1 *CACertificate) EqualWithOpts(c2 *CACertificate,\n\tignoreID bool, ignoreTS bool) bool {\n\tc1Copy := c1.CACertificate.DeepCopy()\n\tc2Copy := c2.CACertificate.DeepCopy()\n\n\tif ignoreID {\n\t\tc1Copy.ID = nil\n\t\tc2Copy.ID = nil\n\t}\n\tif ignoreTS {\n\t\tc1Copy.CreatedAt = nil\n\t\tc2Copy.CreatedAt = nil\n\t}\n\treturn reflect.DeepEqual(c1Copy, c2Copy)\n}", "func (q *Quandl) option(opts ...option) {\n\tfor _, opt := range opts {\n\t\topt(q)\n\t}\n}", "func (c1 *Certificate) EqualWithOpts(c2 *Certificate,\n\tignoreID bool, ignoreTS bool) bool {\n\tc1Copy := c1.Certificate.DeepCopy()\n\tc2Copy := c2.Certificate.DeepCopy()\n\n\tif ignoreID {\n\t\tc1Copy.ID = nil\n\t\tc2Copy.ID = nil\n\t}\n\tif ignoreTS {\n\t\tc1Copy.CreatedAt = nil\n\t\tc2Copy.CreatedAt = nil\n\t}\n\treturn reflect.DeepEqual(c1Copy, c2Copy)\n}", "func TestOptionsHaveHelp(t *testing.T) {\n\tfor _, f := range configFields {\n\t\t// Check all choices if this is a group, else check f.name.\n\t\tnames := f.choices\n\t\tif len(names) == 0 {\n\t\t\tnames = []string{f.name}\n\t\t}\n\t\tfor _, name := range names {\n\t\t\tif _, ok := configHelp[name]; !ok {\n\t\t\t\tt.Errorf(\"missing help message for %q\", name)\n\t\t\t}\n\t\t}\n\t}\n}", "func isOption(inString string) bool {\r\n\tvar rx *regexp.Regexp = regexp.MustCompile(`^--?`)\r\n\treturn rx.MatchString(inString)\r\n}", "func (runner *suiteRunner) checkFixtureArgs() bool {\n succeeded := true\n argType := reflect.Typeof(&C{})\n for _, fv := range []*reflect.FuncValue{runner.setUpSuite,\n runner.tearDownSuite,\n runner.setUpTest,\n runner.tearDownTest} {\n if fv != nil {\n fvType := fv.Type().(*reflect.FuncType)\n if fvType.In(1) != argType || fvType.NumIn() != 2 {\n succeeded = false\n runner.runFunc(fv, fixtureKd, func(c *C) {\n c.logArgPanic(fv, \"*gocheck.C\")\n c.status = panickedSt\n })\n }\n }\n }\n return succeeded\n}", "func TestNDPOptionsIterCheck(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tbuf []byte\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tname: \"ZeroLengthField\",\n\t\t\tbuf: []byte{0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\texpectedErr: ErrNDPOptMalformedHeader,\n\t\t},\n\t\t{\n\t\t\tname: \"ValidSourceLinkLayerAddressOption\",\n\t\t\tbuf: []byte{1, 1, 1, 2, 3, 4, 5, 6},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"TooSmallSourceLinkLayerAddressOption\",\n\t\t\tbuf: []byte{1, 1, 1, 2, 3, 4, 5},\n\t\t\texpectedErr: io.ErrUnexpectedEOF,\n\t\t},\n\t\t{\n\t\t\tname: \"ValidTargetLinkLayerAddressOption\",\n\t\t\tbuf: []byte{2, 1, 1, 2, 3, 4, 5, 6},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"TooSmallTargetLinkLayerAddressOption\",\n\t\t\tbuf: []byte{2, 1, 1, 2, 3, 4, 5},\n\t\t\texpectedErr: io.ErrUnexpectedEOF,\n\t\t},\n\t\t{\n\t\t\tname: \"ValidPrefixInformation\",\n\t\t\tbuf: []byte{\n\t\t\t\t3, 4, 43, 64,\n\t\t\t\t1, 2, 3, 4,\n\t\t\t\t5, 6, 7, 8,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t9, 10, 11, 12,\n\t\t\t\t13, 14, 15, 16,\n\t\t\t\t17, 18, 19, 20,\n\t\t\t\t21, 22, 23, 24,\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"TooSmallPrefixInformation\",\n\t\t\tbuf: []byte{\n\t\t\t\t3, 4, 43, 64,\n\t\t\t\t1, 2, 3, 4,\n\t\t\t\t5, 6, 7, 8,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t9, 10, 11, 12,\n\t\t\t\t13, 14, 15, 16,\n\t\t\t\t17, 18, 19, 20,\n\t\t\t\t21, 22, 23,\n\t\t\t},\n\t\t\texpectedErr: io.ErrUnexpectedEOF,\n\t\t},\n\t\t{\n\t\t\tname: \"InvalidPrefixInformationLength\",\n\t\t\tbuf: []byte{\n\t\t\t\t3, 3, 43, 64,\n\t\t\t\t1, 2, 3, 4,\n\t\t\t\t5, 6, 7, 8,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t9, 10, 11, 12,\n\t\t\t\t13, 14, 15, 16,\n\t\t\t},\n\t\t\texpectedErr: ErrNDPOptMalformedBody,\n\t\t},\n\t\t{\n\t\t\tname: \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformation\",\n\t\t\tbuf: []byte{\n\t\t\t\t// Source Link-Layer Address.\n\t\t\t\t1, 1, 1, 2, 3, 4, 5, 6,\n\n\t\t\t\t// Target Link-Layer Address.\n\t\t\t\t2, 1, 7, 8, 9, 10, 11, 12,\n\n\t\t\t\t// Prefix information.\n\t\t\t\t3, 4, 43, 64,\n\t\t\t\t1, 2, 3, 4,\n\t\t\t\t5, 6, 7, 8,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t9, 10, 11, 12,\n\t\t\t\t13, 14, 15, 16,\n\t\t\t\t17, 18, 19, 20,\n\t\t\t\t21, 22, 23, 24,\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformationWithUnrecognized\",\n\t\t\tbuf: []byte{\n\t\t\t\t// Source Link-Layer Address.\n\t\t\t\t1, 1, 1, 2, 3, 4, 5, 6,\n\n\t\t\t\t// Target Link-Layer Address.\n\t\t\t\t2, 1, 7, 8, 9, 10, 11, 12,\n\n\t\t\t\t// 255 is an unrecognized type. If 255 ends up\n\t\t\t\t// being the type for some recognized type,\n\t\t\t\t// update 255 to some other unrecognized value.\n\t\t\t\t255, 2, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8,\n\n\t\t\t\t// Prefix information.\n\t\t\t\t3, 4, 43, 64,\n\t\t\t\t1, 2, 3, 4,\n\t\t\t\t5, 6, 7, 8,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t9, 10, 11, 12,\n\t\t\t\t13, 14, 15, 16,\n\t\t\t\t17, 18, 19, 20,\n\t\t\t\t21, 22, 23, 24,\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"InvalidRecursiveDNSServerCutsOffAddress\",\n\t\t\tbuf: []byte{\n\t\t\t\t25, 4, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n\t\t\t\t0, 1, 2, 3, 4, 5, 6, 7,\n\t\t\t},\n\t\t\texpectedErr: ErrNDPOptMalformedBody,\n\t\t},\n\t\t{\n\t\t\tname: \"InvalidRecursiveDNSServerInvalidLengthField\",\n\t\t\tbuf: []byte{\n\t\t\t\t25, 2, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t0, 1, 2, 3, 4, 5, 6, 7, 8,\n\t\t\t},\n\t\t\texpectedErr: io.ErrUnexpectedEOF,\n\t\t},\n\t\t{\n\t\t\tname: \"RecursiveDNSServerTooSmall\",\n\t\t\tbuf: []byte{\n\t\t\t\t25, 1, 0, 0,\n\t\t\t\t0, 0, 0,\n\t\t\t},\n\t\t\texpectedErr: io.ErrUnexpectedEOF,\n\t\t},\n\t\t{\n\t\t\tname: \"RecursiveDNSServerMulticast\",\n\t\t\tbuf: []byte{\n\t\t\t\t25, 3, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n\t\t\t},\n\t\t\texpectedErr: ErrNDPOptMalformedBody,\n\t\t},\n\t\t{\n\t\t\tname: \"RecursiveDNSServerUnspecified\",\n\t\t\tbuf: []byte{\n\t\t\t\t25, 3, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t},\n\t\t\texpectedErr: ErrNDPOptMalformedBody,\n\t\t},\n\t\t{\n\t\t\tname: \"DNSSearchListLargeCompliantRFC1035\",\n\t\t\tbuf: []byte{\n\t\t\t\t31, 33, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t62, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j',\n\t\t\t\t0,\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"DNSSearchListNonCompliantRFC1035\",\n\t\t\tbuf: []byte{\n\t\t\t\t31, 33, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t63, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n\t\t\t\t'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n\t\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n\t\t\t\t'i', 'j', 'k',\n\t\t\t\t0,\n\t\t\t\t0, 0, 0, 0, 0, 0, 0, 0,\n\t\t\t},\n\t\t\texpectedErr: ErrNDPOptMalformedBody,\n\t\t},\n\t\t{\n\t\t\tname: \"DNSSearchListValidSmall\",\n\t\t\tbuf: []byte{\n\t\t\t\t31, 2, 0, 0,\n\t\t\t\t0, 0, 0, 0,\n\t\t\t\t6, 'a', 'b', 'c', 'd', 'e', 'f',\n\t\t\t\t0,\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"DNSSearchListTooSmall\",\n\t\t\tbuf: []byte{\n\t\t\t\t31, 1, 0, 0,\n\t\t\t\t0, 0, 0,\n\t\t\t},\n\t\t\texpectedErr: io.ErrUnexpectedEOF,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\topts := NDPOptions(test.buf)\n\n\t\t\tif _, err := opts.Iter(true); !errors.Is(err, test.expectedErr) {\n\t\t\t\tt.Fatalf(\"got Iter(true) = (_, %v), want = (_, %v)\", err, test.expectedErr)\n\t\t\t}\n\n\t\t\t// test.buf may be malformed but we chose not to check\n\t\t\t// the iterator so it must return true.\n\t\t\tif _, err := opts.Iter(false); err != nil {\n\t\t\t\tt.Fatalf(\"got Iter(false) = (_, %s), want = (_, nil)\", err)\n\t\t\t}\n\t\t})\n\t}\n}", "func (o *showSvcOpts) Validate() error {\n\treturn nil\n}", "func TestClientOptions_ToPreevOptions(t *testing.T) {\n\tt.Parallel()\n\n\toptions := DefaultClientOptions()\n\n\tpreevOptions := options.ToPreevOptions()\n\n\tif !strings.Contains(preevOptions.UserAgent, \"go-preev\") {\n\t\tt.Fatalf(\"expected value: %s got: %s\", \"go-preev\", preevOptions.UserAgent)\n\t}\n\n\tif preevOptions.BackOffExponentFactor != options.BackOffExponentFactor {\n\t\tt.Fatalf(\"expected value: %f got: %f\", options.BackOffExponentFactor, preevOptions.BackOffExponentFactor)\n\t}\n\n\tif preevOptions.BackOffInitialTimeout != options.BackOffInitialTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.BackOffInitialTimeout, preevOptions.BackOffInitialTimeout)\n\t}\n\n\tif preevOptions.BackOffMaximumJitterInterval != options.BackOffMaximumJitterInterval {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.BackOffMaximumJitterInterval, preevOptions.BackOffMaximumJitterInterval)\n\t}\n\n\tif preevOptions.BackOffMaxTimeout != options.BackOffMaxTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.BackOffMaxTimeout, preevOptions.BackOffMaxTimeout)\n\t}\n\n\tif preevOptions.DialerKeepAlive != options.DialerKeepAlive {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.DialerKeepAlive, preevOptions.DialerKeepAlive)\n\t}\n\n\tif preevOptions.DialerTimeout != options.DialerTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.DialerTimeout, preevOptions.DialerTimeout)\n\t}\n\n\tif preevOptions.RequestRetryCount != options.RequestRetryCount {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.RequestRetryCount, preevOptions.RequestRetryCount)\n\t}\n\n\tif preevOptions.RequestTimeout != options.RequestTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.RequestTimeout, preevOptions.RequestTimeout)\n\t}\n\n\tif preevOptions.TransportExpectContinueTimeout != options.TransportExpectContinueTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.TransportExpectContinueTimeout, preevOptions.TransportExpectContinueTimeout)\n\t}\n\n\tif preevOptions.TransportIdleTimeout != options.TransportIdleTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.TransportIdleTimeout, preevOptions.TransportIdleTimeout)\n\t}\n\n\tif preevOptions.TransportMaxIdleConnections != options.TransportMaxIdleConnections {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.TransportMaxIdleConnections, preevOptions.TransportMaxIdleConnections)\n\t}\n\n\tif preevOptions.TransportTLSHandshakeTimeout != options.TransportTLSHandshakeTimeout {\n\t\tt.Fatalf(\"expected value: %v got: %v\", options.TransportTLSHandshakeTimeout, preevOptions.TransportTLSHandshakeTimeout)\n\t}\n}", "func InitFlags() *FactoryOptions {\n\ttesting.Init()\n\t_, err := types.NewAttachedGinkgoFlagSet(flag.CommandLine, types.GinkgoFlags{}, nil, types.GinkgoFlagSections{}, types.GinkgoFlagSection{})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttestOptions := &FactoryOptions{}\n\ttestOptions.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\treturn testOptions\n}", "func main() {\n\tl := len(os.Args)\n\tif l <= 1 || l%2 != 1 {\n\t\tdie(help)\n\t}\n\tfilter := inex.NewRoot()\n\tpath := \".\"\n\tfor i := 1; i < l; i += 2 {\n\t\tswitch os.Args[i] {\n\t\tcase \"-e\", \"--exclude\":\n\t\t\tfilter = filter.Exclude(&inex.RegexpMatcher{regexp.MustCompile(os.Args[i+1])})\n\t\tcase \"-i\", \"--include\":\n\t\t\tfilter = filter.Include(&inex.RegexpMatcher{regexp.MustCompile(os.Args[i+1])})\n\t\tcase \"-c\", \"--contains\":\n\t\t\tpartial := os.Args[i+1]\n\t\t\tfilter = filter.Include(inex.FuncMatcher(func(str string) bool {\n\t\t\t\treturn strings.Contains(str, partial)\n\t\t\t}))\n\t\tcase \"-C\", \"--not-contains\":\n\t\t\tpartial := os.Args[i+1]\n\t\t\tfilter = filter.Include(inex.FuncMatcher(func(str string) bool {\n\t\t\t\treturn !strings.Contains(str, partial)\n\t\t\t}))\n\t\tcase \"-t\", \"--type\":\n\t\t\ttyp := os.Args[i+1]\n\t\t\tswitch typ {\n\t\t\tcase \"f\", \"file\", \"d\", \"directory\":\n\t\t\tdefault:\n\t\t\t\tdie(\"invalid --type provided. must be \\\"f\\\", \\\"file\\\", \\\"d\\\" or \\\"directory\\\"\")\n\t\t\t}\n\t\t\tfilter = filter.Include(inex.FuncMatcher(func(str string) bool {\n\t\t\t\tstat, err := os.Stat(str)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdie(\"failed to stat \\\"%s\\\": %s\\n\", str, err)\n\t\t\t\t}\n\t\t\t\tif typ == \"f\" || typ == \"file\" {\n\t\t\t\t\treturn !stat.IsDir()\n\t\t\t\t}\n\t\t\t\treturn stat.IsDir()\n\t\t\t}))\n\t\tcase \"-p\", \"--path\":\n\t\t\tif path != \".\" {\n\t\t\t\tdie(\"%s can only be provided once\\n\\n%s\", os.Args[i], help)\n\t\t\t}\n\t\t\tpath = os.Args[i+1]\n\t\tdefault:\n\t\t\tdie(\"unsupported operation \\\"%s\\\"\\n\\n%s\", os.Args[i], help)\n\t\t}\n\t}\n\tif filter.IsRoot() {\n\t\tdie(\"no filters provided\\n\\n%s\", help)\n\t}\n\tfilter = filter.Root()\n\tfilepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if filter.Match(path) {\n\t\t\tfmt.Println(path)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (m *MockFilterClient) GetDimensionOptionsInBatches(ctx context.Context, userAuthToken, serviceAuthToken, collectionID, filterID, name string, batchSize, maxWorkers int) (filter.DimensionOptions, string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetDimensionOptionsInBatches\", ctx, userAuthToken, serviceAuthToken, collectionID, filterID, name, batchSize, maxWorkers)\n\tret0, _ := ret[0].(filter.DimensionOptions)\n\tret1, _ := ret[1].(string)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func TestSortedFlags(t *testing.T) {\n\tcmd := &Command{}\n\tcmd.Flags().SortFlags = false\n\tnames := []string{\"C\", \"B\", \"A\", \"D\"}\n\tfor _, name := range names {\n\t\tcmd.Flags().Bool(name, false, \"\")\n\t}\n\n\ti := 0\n\tcmd.LocalFlags().VisitAll(func(f *pflag.Flag) {\n\t\tif i == len(names) {\n\t\t\treturn\n\t\t}\n\t\tif isStringInStringSlice(f.Name, names) {\n\t\t\tif names[i] != f.Name {\n\t\t\t\tt.Errorf(\"Incorrect order. Expected %v, got %v\", names[i], f.Name)\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t})\n}", "func (o *overrideOpts) Validate() error {\n\tif err := o.validateAppName(); err != nil {\n\t\treturn err\n\t}\n\treturn o.validateCDKLang()\n}", "func loadBanningOptions(conf *p2p.Config, ctx *cli.Context) error {\n\tconf.BanningEnabled = ctx.Bool(flags.Banning.Name)\n\tconf.BanningThreshold = ctx.Float64(flags.BanningThreshold.Name)\n\tconf.BanningDuration = ctx.Duration(flags.BanningDuration.Name)\n\treturn nil\n}", "func (a *Args) HasOpt(key string) bool {\n\tfor _, b := range a.binOpts {\n\t\tif b.key == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o DownsamplerOptions) validate() error {\n\tif o.Storage == nil {\n\t\treturn errNoStorage\n\t}\n\tif o.ClusterClient == nil {\n\t\treturn errNoClusterClient\n\t}\n\tif o.RulesKVStore == nil {\n\t\treturn errNoRulesStore\n\t}\n\tif o.ClockOptions == nil {\n\t\treturn errNoClockOptions\n\t}\n\tif o.InstrumentOptions == nil {\n\t\treturn errNoInstrumentOptions\n\t}\n\tif o.TagEncoderOptions == nil {\n\t\treturn errNoTagEncoderOptions\n\t}\n\tif o.TagDecoderOptions == nil {\n\t\treturn errNoTagDecoderOptions\n\t}\n\tif o.TagEncoderPoolOptions == nil {\n\t\treturn errNoTagEncoderPoolOptions\n\t}\n\tif o.TagDecoderPoolOptions == nil {\n\t\treturn errNoTagDecoderPoolOptions\n\t}\n\treturn nil\n}", "func (a *Args) IsOn(s string) bool {\n\tfor _, u := range a.uniOpts {\n\t\tif u == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func configureFlags(api *operations.ReservoirAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}" ]
[ "0.5510299", "0.5391247", "0.5304554", "0.51175886", "0.50980186", "0.5081817", "0.5009267", "0.49521753", "0.49211538", "0.48807758", "0.48724702", "0.48723876", "0.48486164", "0.4811651", "0.47531763", "0.47263643", "0.47097528", "0.47027934", "0.4702349", "0.4642556", "0.46338162", "0.46309608", "0.46286994", "0.4588905", "0.45854366", "0.45853537", "0.45657808", "0.4565625", "0.45593098", "0.45526043", "0.45485693", "0.4533525", "0.45235983", "0.4503269", "0.44904706", "0.44880608", "0.44863173", "0.44825777", "0.44528434", "0.44474307", "0.4441688", "0.44361934", "0.44352728", "0.4423603", "0.4417929", "0.44120058", "0.44098893", "0.44075212", "0.4405767", "0.43940607", "0.4392936", "0.43881717", "0.43822235", "0.43680137", "0.43647975", "0.43579563", "0.43572685", "0.43558434", "0.43557134", "0.435569", "0.43555596", "0.43485573", "0.43451473", "0.4338692", "0.43351096", "0.43350905", "0.43328705", "0.43307465", "0.4328628", "0.432297", "0.4322242", "0.43204474", "0.431839", "0.43089387", "0.43073806", "0.43064296", "0.43051058", "0.430329", "0.4300399", "0.42998236", "0.42933932", "0.42855555", "0.42788133", "0.42770013", "0.42718595", "0.42661226", "0.42656842", "0.42646405", "0.42636997", "0.42613074", "0.4258087", "0.42535043", "0.42513415", "0.42460486", "0.42456028", "0.42454177", "0.4244589", "0.42369306", "0.42366374", "0.4229926" ]
0.7578039
0
AggregateId provides a mock function with given fields:
func (_m *MockAggregate) AggregateId() AggregateId { ret := _m.Called() var r0 AggregateId if rf, ok := ret.Get(0).(func() AggregateId); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).(AggregateId) } } return r0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MockAggregateSealProof(proofType abi.RegisteredSealProof, minerAddr address.Address, count int) ([]byte, error) {\n\tproof := make([]byte, aggProofLen(count))\n\ti := copy(proof, mockAggregateSealProofPrefix)\n\tbinary.BigEndian.PutUint64(proof[i:], uint64(proofType))\n\ti += 8\n\tbinary.BigEndian.PutUint64(proof[i:], uint64(count))\n\ti += 8\n\ti += copy(proof[i:], minerAddr.Bytes())\n\n\treturn proof, nil\n}", "func (_m *Aggregator) Aggregate(ctx context.Context, fs vfs.FS, currentMilestone int, aggregateFilePath string, relnotesDir string) ([]byte, error) {\n\tret := _m.Called(ctx, fs, currentMilestone, aggregateFilePath, relnotesDir)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func(context.Context, vfs.FS, int, string, string) []byte); ok {\n\t\tr0 = rf(ctx, fs, currentMilestone, aggregateFilePath, relnotesDir)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, vfs.FS, int, string, string) error); ok {\n\t\tr1 = rf(ctx, fs, currentMilestone, aggregateFilePath, relnotesDir)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockProduct) GetAggregationByID(arg0 context.Context, arg1 db.GetAggregationByIDParams) (db.Aggregation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAggregationByID\", arg0, arg1)\n\tret0, _ := ret[0].(db.Aggregation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *InjectEvent) AggregateID() eh.UUID { return c.ID }", "func (_m *MockBookingStorage) ByID() {\n\t_m.Called()\n}", "func (_m *MockAggregate) AggregateName() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *Database) GetByID(_a0 string) (map[string]string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 map[string]string\n\tif rf, ok := ret.Get(0).(func(string) map[string]string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]string)\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(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mmForID *mAtomicRecordStorageMockForID) When(ctx context.Context, id insolar.ID) *AtomicRecordStorageMockForIDExpectation {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"AtomicRecordStorageMock.ForID mock is already set by Set\")\n\t}\n\n\texpectation := &AtomicRecordStorageMockForIDExpectation{\n\t\tmock: mmForID.mock,\n\t\tparams: &AtomicRecordStorageMockForIDParams{ctx, id},\n\t}\n\tmmForID.expectations = append(mmForID.expectations, expectation)\n\treturn expectation\n}", "func (_m *MockGroupProvider) FindOneByID(_a0 int64) (*GroupEntity, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *GroupEntity\n\tif rf, ok := ret.Get(0).(func(int64) *GroupEntity); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*GroupEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Repository) GetID(name string) (steamapis.Domain, error) {\n\tret := _m.Called(name)\n\n\tvar r0 steamapis.Domain\n\tif rf, ok := ret.Get(0).(func(string) steamapis.Domain); ok {\n\t\tr0 = rf(name)\n\t} else {\n\t\tr0 = ret.Get(0).(steamapis.Domain)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(name)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mmForID *mStorageMockForID) When(ctx context.Context, pulse insolar.PulseNumber, recordID insolar.ID) *StorageMockForIDExpectation {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"StorageMock.ForID mock is already set by Set\")\n\t}\n\n\texpectation := &StorageMockForIDExpectation{\n\t\tmock: mmForID.mock,\n\t\tparams: &StorageMockForIDParams{ctx, pulse, recordID},\n\t}\n\tmmForID.expectations = append(mmForID.expectations, expectation)\n\treturn expectation\n}", "func TestBaseAggregateHandle(t *testing.T) {\n\tinstance := &SimpleAggregate{}\n\tstore := NewNullStore()\n\tinstance.Initialize(\"dummy-key\", counterRegistry, store)\n\terrRun := instance.Handle(InitializeCommand{\n\t\tTargetValue: 3,\n\t})\n\n\tassert.Nil(t, errRun, \"Run error should be nil\")\n\tassert.Equal(t, int64(1), instance.SequenceNumber(), \"The aggregate sequence number should be 1\")\n\tassert.Equal(t, 3, instance.TargetValue, \"The aggregate target value should be 3\")\n}", "func (_m *MockORM) Group(query string) ORM {\n\tret := _m.Called(query)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string) ORM); ok {\n\t\tr0 = rf(query)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *TaskStatuser) ID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *MockGroupProvider) FindByUserID(_a0 int64) ([]*GroupEntity, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []*GroupEntity\n\tif rf, ok := ret.Get(0).(func(int64) []*GroupEntity); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*GroupEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIRepository) Id(id aggregates.Id) (aggregates.Question, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\", id)\n\tret0, _ := ret[0].(aggregates.Question)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (_m *KeyManager) ID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestEmployeeManagerMapGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tr = httptest.NewRequest(\"GET\", \"http://localhost:9090/api/v1/emplymgrmap/Nick?supervisor=true&name=Nick\", nil)\n\trctx := chi.NewRouteContext()\n\trctx.URLParams.Add(\"name\", \"Nick\")\n\tr = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetByID(w, r)\n\texpectedResponse := `{\"supervisor\":\"Sophie\",\"supervisor_of_supervisor\":\"Jonas\"}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (m *MockTChanNode) Aggregate(ctx thrift.Context, req *AggregateQueryRequest) (*AggregateQueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Aggregate\", ctx, req)\n\tret0, _ := ret[0].(*AggregateQueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *XMPPClient) ID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *AppealService) GetByID(_a0 uint) (*domain.Appeal, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *domain.Appeal\n\tif rf, ok := ret.Get(0).(func(uint) *domain.Appeal); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*domain.Appeal)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(uint) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (c *CreateRedfishResource) AggregateID() eh.UUID { return c.ID }", "func (_m *Entity) ID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockIRepository) Id(id aggregates.Id) (aggregates.Topic, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\", id)\n\tret0, _ := ret[0].(aggregates.Topic)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSpaceStorage) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func TestGetByID(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"can't create mock: %s\", err)\n\t}\n\tdefer db.Close()\n\n\tuserID := \"1\"\n\n\t// good query\n\trows := sqlmock.\n\t\tNewRows([]string{\"username\", \"admin\", \"id\", \"passwordHash\", \"token\"})\n\tuser := &User{\n\t\tUsername: \"Coolguy\",\n\t\tAdmin: false,\n\t\tID: userID,\n\t\tPasswordHash: \"CoolHash\",\n\t\tToken: \"CoolToken\",\n\t}\n\texpect := []*User{\n\t\tuser,\n\t}\n\tfor _, item := range expect {\n\t\trows = rows.AddRow(item.ID, item.Username, item.Admin, item.PasswordHash, item.Token)\n\t}\n\n\tmock.\n\t\tExpectQuery(\"SELECT id, username, admin, passwordHash, token\").\n\t\tWithArgs(userID).\n\t\tWillReturnRows(rows)\n\n\trepo := &Repo{\n\t\tDB: db,\n\t}\n\titem, err := repo.GetByID(userID)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected err: %s\", err)\n\t\treturn\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(item, expect[0]) {\n\t\tt.Errorf(\"results not match, want %v, have %v\", expect[0], item)\n\t\treturn\n\t}\n\n\t// query db error\n\tmock.\n\t\tExpectQuery(\"SELECT id, username, admin, passwordHash, token\").\n\t\tWithArgs(userID).\n\t\tWillReturnError(fmt.Errorf(\"db_error\"))\n\n\t_, err = repo.GetByID(userID)\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t\treturn\n\t}\n\tif err == nil {\n\t\tt.Errorf(\"expected error, got nil\")\n\t\treturn\n\t}\n}", "func (_m *MockAggregate) Version() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (m *MockIByIdUseCase) Id(id aggregates.Id) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Id\", id)\n}", "func (c *UpdateRedfishResourceProperties) AggregateID() eh.UUID { return c.ID }", "func (_m *Operator) ID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (mmGetByID *mPaymentRepositoryMockGetByID) When(ctx context.Context, id int64) *PaymentRepositoryMockGetByIDExpectation {\n\tif mmGetByID.mock.funcGetByID != nil {\n\t\tmmGetByID.mock.t.Fatalf(\"PaymentRepositoryMock.GetByID mock is already set by Set\")\n\t}\n\n\texpectation := &PaymentRepositoryMockGetByIDExpectation{\n\t\tmock: mmGetByID.mock,\n\t\tparams: &PaymentRepositoryMockGetByIDParams{ctx, id},\n\t}\n\tmmGetByID.expectations = append(mmGetByID.expectations, expectation)\n\treturn expectation\n}", "func (_m *DBAdapter) CreateID() (int64, error) {\n\tret := _m.Called()\n\n\tvar r0 int64\n\tif rf, ok := ret.Get(0).(func() int64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DBAdapter) CreateID() (int64, error) {\n\tret := _m.Called()\n\n\tvar r0 int64\n\tif rf, ok := ret.Get(0).(func() int64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DirectRepositoryWriter) UniqueID() []byte {\n\tret := _m.Called()\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func() []byte); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\treturn r0\n}", "func getAggregateID(records []flux.Record) (string, error) {\n\t// make sure all records are of the same aggregate.\n\taggregateID := \"\"\n\tfor _, rec := range records {\n\t\tif aggregateID != \"\" && rec.AggregateID != aggregateID {\n\t\t\treturn \"\", errors.New(\"multiple aggregates in records\")\n\t\t}\n\t\taggregateID = rec.AggregateID\n\t}\n\treturn aggregateID, nil\n}", "func (suite *EventStoreTestSuite) TestSaveInvalidAggregateId() {\n\tid, _ := uuid.Parse(\"c1138e5f-f6fb-4dd0-8e79-255c6c8d3756\")\n\tid2, _ := uuid.Parse(\"c1138e5f-f6fb-4dd0-8e79-zzzzzzzzzz\")\n\ttimestamp := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)\n\n\texpectedEvents := []eh.Event{\n\t\teh.NewEventForAggregate(mocks.EventType, &mocks.EventData{Content: \"event1\"},\n\t\t\ttimestamp, mocks.AggregateType, id, 1),\n\t\teh.NewEventForAggregate(mocks.EventType, &mocks.EventData{Content: \"event1\"},\n\t\t\ttimestamp, mocks.AggregateType, id2, 1),\n\t}\n\n\terr := suite.store.Save(context.Background(), expectedEvents, 0)\n\tassert.EqualError(suite.T(), err, \"invalid event (default)\")\n}", "func (_m *ContainerIface) ID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (e EventModel) AggregateID() string {\n\treturn e.ID\n}", "func (_m *MockORM) Having(query string, values ...interface{}) ORM {\n\tret := _m.Called(query, values)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string, ...interface{}) ORM); ok {\n\t\tr0 = rf(query, values...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestBaseAggregateGetKey(t *testing.T) {\n\tinstance := &SimpleAggregate{}\n\tstore := NewNullStore()\n\tinstance.Initialize(\"dummy-key\", counterRegistry, store)\n\tinstance.Refresh()\n\n\tassert.Equal(t, \"dummy-key\", instance.GetKey())\n}", "func (m *MockTChanCluster) Aggregate(ctx thrift.Context, req *AggregateQueryRequest) (*AggregateQueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Aggregate\", ctx, req)\n\tret0, _ := ret[0].(*AggregateQueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *JobI) GetByID(_a0 string) (*models.Job, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *models.Job\n\tif rf, ok := ret.Get(0).(func(string) *models.Job); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.Job)\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(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockGroupProvider) UpdateOneByID(id int64, updatedBy int64, name *ntypes.String, description *ntypes.String) (*GroupEntity, error) {\n\tret := _m.Called(id, updatedBy, name, description)\n\n\tvar r0 *GroupEntity\n\tif rf, ok := ret.Get(0).(func(int64, int64, *ntypes.String, *ntypes.String) *GroupEntity); ok {\n\t\tr0 = rf(id, updatedBy, name, description)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*GroupEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64, int64, *ntypes.String, *ntypes.String) error); ok {\n\t\tr1 = rf(id, updatedBy, name, description)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func awsMockStackID(stackName string) string {\n\tnh := sha1.Sum([]byte(stackName))\n\treturn fmt.Sprintf(\"arn:aws:cloudformation:mock:%012d:stack/%s/%x-%x-%x-%x-%x\",\n\t\tbinary.BigEndian.Uint32(nh[16:20]), stackName, nh[0:4], nh[4:6], nh[6:8], nh[8:10], nh[10:16])\n}", "func (e event) AggregateID() string {\n\treturn e.dbEvent.AggregateID\n}", "func (c *CommandDescriptor) AggregateID() string {\n\treturn c.id\n}", "func TestFindUserById(t *testing.T) {\n\t_, mock, err := NewMock()\n\tif err != nil {\n\t\tfmt.Printf(\"error mock: \" + err.Error())\n\t}\n\n\t// simulate any sql driver behavior in tests, without needing a real database connection\n\tquery := \"select id, user_name, password from m_user where id = \\\\?\"\n\n\trows := sqlmock.NewRows([]string{\"id\", \"user_name\", \"password\"}).\n\t\tAddRow(user.ID, user.UserName, user.Password)\n\n\tmock.ExpectQuery(query).WithArgs(user.ID).WillReturnRows(rows)\n\t// ------------ end of mock ---------------\n\n\tassert.NotNil(t, user)\n}", "func (m *PaymentRepositoryMock) MinimockGetByIDInspect() {\n\tfor _, e := range m.GetByIDMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to PaymentRepositoryMock.GetByID with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.GetByIDMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetByIDCounter) < 1 {\n\t\tif m.GetByIDMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to PaymentRepositoryMock.GetByID\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to PaymentRepositoryMock.GetByID with params: %#v\", *m.GetByIDMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcGetByID != nil && mm_atomic.LoadUint64(&m.afterGetByIDCounter) < 1 {\n\t\tm.t.Error(\"Expected call to PaymentRepositoryMock.GetByID\")\n\t}\n}", "func (_m *Delivery) GetByID(c echo.Context) error {\n\tret := _m.Called(c)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(echo.Context) error); ok {\n\t\tr0 = rf(c)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockIByIdUseCase) Id(id aggregates.Id) (aggregates.Question, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\", id)\n\tret0, _ := ret[0].(aggregates.Question)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestBaseAggregateDefineReplayMethod(t *testing.T) {\n\tinstance := &SimpleAggregate{}\n\tstore := NewNullStore()\n\tinstance.Initialize(\"dummy-key\", counterRegistry, store)\n\tinstance.Refresh()\n\n\t// Nothing should happen yet. Define the event type in our registry, but it should still not change\n\t// anything state-wise.\n\tinstance.ApplyEvent(UnknownEventTypeExample{})\n\teventType := counterRegistry.RegisterEvent(UnknownEventTypeExample{})\n\tassert.Equal(t, int64(1), instance.SequenceNumber(), \"The aggregate sequence number should be 1\")\n\tassert.Equal(t, 0, instance.TargetValue, \"The aggregate target value should be 0\")\n\n\tinstance.DefineReplayMethod(eventType, func(evt Event) {\n\t\tinstance.TargetValue *= 2\n\t})\n\n\t// Set target value\n\tinstance.ApplyEvent(InitializeEvent{\n\t\tTargetValue: 3,\n\t})\n\n\t// Apply our unknown event\n\tinstance.ApplyEvent(UnknownEventTypeExample{})\n\n\tassert.Equal(t, int64(3), instance.SequenceNumber(), \"The aggregate sequence number should be 3\")\n\tassert.Equal(t, 6, instance.TargetValue, \"The aggregate target value should be 6\")\n}", "func (m *MockCandidatePropertyGetter) Id() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Id\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockProduct) GetAggRightMetricsByAggregationId(arg0 context.Context, arg1 db.GetAggRightMetricsByAggregationIdParams) ([]db.GetAggRightMetricsByAggregationIdRow, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAggRightMetricsByAggregationId\", arg0, arg1)\n\tret0, _ := ret[0].([]db.GetAggRightMetricsByAggregationIdRow)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *EventAPIRepository) GetByIDGlobal(ctx context.Context, id string) (*model.EventDefinition, error) {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 *model.EventDefinition\n\tif rf, ok := ret.Get(0).(func(context.Context, string) *model.EventDefinition); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.EventDefinition)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string) error); ok {\n\t\tr1 = rf(ctx, id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (e event) AggregateID() uuid.UUID {\n\treturn e.AggregateEvent.AggregateID\n}", "func (_m *MockRepository) GetIdentityBySocialID(socialID string, socialNetworkType models.SocialNetworkType, executor database.QueryExecutor) (*models.Identity, error) {\n\tret := _m.Called(socialID, socialNetworkType, executor)\n\n\tvar r0 *models.Identity\n\tif rf, ok := ret.Get(0).(func(string, models.SocialNetworkType, database.QueryExecutor) *models.Identity); ok {\n\t\tr0 = rf(socialID, socialNetworkType, executor)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.Identity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, models.SocialNetworkType, database.QueryExecutor) error); ok {\n\t\tr1 = rf(socialID, socialNetworkType, executor)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (b BaseCommand) GetAggregateID() string {\n\treturn b.AggregateID\n}", "func (_m *RelationRepo) GetIdFromEmail(email string) (string, error) {\n\tret := _m.Called(email)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(email)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(email)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *RepositoryMock) AuthorGetByIDCalls() []struct {\n\tCtx context.Context\n\tID int64\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tID int64\n\t}\n\tlockRepositoryMockAuthorGetByID.RLock()\n\tcalls = mock.calls.AuthorGetByID\n\tlockRepositoryMockAuthorGetByID.RUnlock()\n\treturn calls\n}", "func (mmForID *mAtomicRecordStorageMockForID) Expect(ctx context.Context, id insolar.ID) *mAtomicRecordStorageMockForID {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"AtomicRecordStorageMock.ForID mock is already set by Set\")\n\t}\n\n\tif mmForID.defaultExpectation == nil {\n\t\tmmForID.defaultExpectation = &AtomicRecordStorageMockForIDExpectation{}\n\t}\n\n\tmmForID.defaultExpectation.params = &AtomicRecordStorageMockForIDParams{ctx, id}\n\tfor _, e := range mmForID.expectations {\n\t\tif minimock.Equal(e.params, mmForID.defaultExpectation.params) {\n\t\t\tmmForID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmForID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmForID\n}", "func (_m *Service) Get(_a0 uint) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func(uint) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (m *MockTChanNode) AggregateRaw(ctx thrift.Context, req *AggregateQueryRawRequest) (*AggregateQueryRawResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AggregateRaw\", ctx, req)\n\tret0, _ := ret[0].(*AggregateQueryRawResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Service) GetID(ctx context.Context, unitID uuid.UUID) (uint, error) {\n\tret := _m.Called(ctx, unitID)\n\n\tvar r0 uint\n\tif rf, ok := ret.Get(0).(func(context.Context, uuid.UUID) uint); ok {\n\t\tr0 = rf(ctx, unitID)\n\t} else {\n\t\tr0 = ret.Get(0).(uint)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {\n\t\tr1 = rf(ctx, unitID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Service) Add(_a0 []byte) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func([]byte) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func TestMyAggregationFunc(t *testing.T) {\n\tcolumnsMap := make(map[string]int)\n\tcolumnsMap[\"Col1\"] = 0\n\tcolumnsMap[\"Col2\"] = 1\n\ttables := []struct {\n\t\tcounter int\n\t\tfiltrCount int\n\t\tmyAggVals []float64\n\t\tcolumnsMap map[string]int\n\t\tstoreReqCols []string\n\t\tstoreFunctions []string\n\t\trecord []string\n\t\terr error\n\t\texpectedVal float64\n\t}{\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"count\"}, []string{\"1\", \"2\"}, nil, 11},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"min\"}, []string{\"1\", \"2\"}, nil, 1},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"max\"}, []string{\"1\", \"2\"}, nil, 10},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"sum\"}, []string{\"1\", \"2\"}, nil, 11},\n\t\t{1, 1, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"avg\"}, []string{\"1\", \"2\"}, nil, 5.500},\n\t\t{10, 5, []float64{0.000}, columnsMap, []string{\"Col1\"}, []string{\"random\"}, []string{\"1\", \"2\"}, ErrParseNonUnaryAgregateFunctionCall, 0},\n\t\t{0, 5, []float64{0}, columnsMap, []string{\"0\"}, []string{\"count\"}, []string{\"1\", \"2\"}, nil, 1},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"1\"}, []string{\"min\"}, []string{\"1\", \"12\"}, nil, 10},\n\t}\n\tfor _, table := range tables {\n\t\terr := aggregationFunctions(table.counter, table.filtrCount, table.myAggVals, table.columnsMap, table.storeReqCols, table.storeFunctions, table.record)\n\t\tif table.err != err {\n\t\t\tt.Error()\n\t\t}\n\t\tif table.myAggVals[0] != table.expectedVal {\n\t\t\tt.Error()\n\t\t}\n\n\t}\n}", "func (_m *API) GetAnimeMoreInfo(id int) (string, int, error) {\n\tret := _m.Called(id)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(int) string); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(int) int); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(int) error); ok {\n\t\tr2 = rf(id)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func TestAggregateFuncsQuery(t *testing.T) {\n\tt.Parallel()\n\n\tconst query = `SELECT COUNT(*), SUM(rental_rate), TOTAL(rental_rate),\n\tAVG(rental_rate), MAX(rental_rate), MIN(rental_rate),\n\tMAX(title), MAX(last_update), GROUP_CONCAT(rating,',')\n\tFROM film`\n\n\tth := testh.New(t)\n\tsrc := th.Source(sakila.SL3)\n\tsink, err := th.QuerySQL(src, query)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(sink.Recs))\n}", "func (_m *MockAggregate) clearUncommittedEvents() {\n\t_m.Called()\n}", "func (_m *Job) UUID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *MockAggregate) OriginalVersion() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (_m *MockRepository) GetIdentitiesByAccountID(accountID uuid.UUID, executor database.QueryExecutor) ([]*models.Identity, error) {\n\tret := _m.Called(accountID, executor)\n\n\tvar r0 []*models.Identity\n\tif rf, ok := ret.Get(0).(func(uuid.UUID, database.QueryExecutor) []*models.Identity); ok {\n\t\tr0 = rf(accountID, executor)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*models.Identity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(uuid.UUID, database.QueryExecutor) error); ok {\n\t\tr1 = rf(accountID, executor)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func mockMapStore(storage map[string]interface{}) ResultStoreFn {\n\treturn func(id string, key string, value interface{}) {\n\t\tutil.SetNestedField(storage, value, id, key)\n\t}\n}", "func (_m *API) GetMangaMoreInfo(id int) (string, int, error) {\n\tret := _m.Called(id)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(int) string); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(int) int); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(int) error); ok {\n\t\tr2 = rf(id)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (_m *MockAggregate) Apply(_a0 Event) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(Event) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (c *RemoveRedfishResource) AggregateID() eh.UUID { return c.ID }", "func TestEmployeeManagerMapGetAll(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetAll(w, r)\n\texpectedResponse := `{\"Jonas\":{\"Sophie\":{\"Nick\":{\"Barbara\":{},\"Peter\":{}}}}}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (_m *RunInterface) GetID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestCacheService_Set(t *testing.T) {\n\tc := MustLinkCache()\n\tdefer c.Close()\n\n\tuser := &pb.User{\n\t\tId: rand.String(10),\n\t\tName: \"test\",\n\t\tEmail: \"[email protected]\",\n\t\tRoles: append([]pb.Role{}, pb.Role_DEFAULT),\n\t}\n\n\tin := &hippo.Aggregate{\n\t\tState: user,\n\t\tVersion: 1,\n\t}\n\n\tctx := context.Background()\n\n\t// Set aggregator in cache.\n\tif err := c.Set(ctx, user.GetId(), in); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}", "func (m *MockInterface) SubscriptionID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SubscriptionID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockQueryer) GetSingleAggregationMeta(arg0 i18n.LanguageCodes, arg1, arg2 string) (*pb.Aggregation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSingleAggregationMeta\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*pb.Aggregation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStream) ID() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (_m *SchedulerQueueWriter) QueryIntervalByID(intervalId string) (models.Interval, error) {\n\tret := _m.Called(intervalId)\n\n\tvar r0 models.Interval\n\tif rf, ok := ret.Get(0).(func(string) models.Interval); ok {\n\t\tr0 = rf(intervalId)\n\t} else {\n\t\tr0 = ret.Get(0).(models.Interval)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(intervalId)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Task) DotID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (mmForID *mStorageMockForID) Expect(ctx context.Context, pulse insolar.PulseNumber, recordID insolar.ID) *mStorageMockForID {\n\tif mmForID.mock.funcForID != nil {\n\t\tmmForID.mock.t.Fatalf(\"StorageMock.ForID mock is already set by Set\")\n\t}\n\n\tif mmForID.defaultExpectation == nil {\n\t\tmmForID.defaultExpectation = &StorageMockForIDExpectation{}\n\t}\n\n\tmmForID.defaultExpectation.params = &StorageMockForIDParams{ctx, pulse, recordID}\n\tfor _, e := range mmForID.expectations {\n\t\tif minimock.Equal(e.params, mmForID.defaultExpectation.params) {\n\t\t\tmmForID.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmForID.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmForID\n}", "func (state *AggregateRoot) id() string {\n\treturn state.AggregateID.String()\n}", "func (m *MockUserDB) GetFolderId(uid uint64, kind, name string) (uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetFolderId\", uid, kind, name)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Client) ChainID() (*big.Int, error) {\n\tret := _m.Called()\n\n\tvar r0 *big.Int\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func() (*big.Int, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() *big.Int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*big.Int)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockRepository) GetACOByUUID(ctx context.Context, _a1 uuid.UUID) (*ACO, error) {\n\tret := _m.Called(ctx, _a1)\n\n\tvar r0 *ACO\n\tif rf, ok := ret.Get(0).(func(context.Context, uuid.UUID) *ACO); ok {\n\t\tr0 = rf(ctx, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*ACO)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {\n\t\tr1 = rf(ctx, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Service) Delete(_a0 uint) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func(uint) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (_m *BundleRepository) GetByIDGlobal(ctx context.Context, id string) (*model.Bundle, error) {\n\tret := _m.Called(ctx, id)\n\n\tvar r0 *model.Bundle\n\tif rf, ok := ret.Get(0).(func(context.Context, string) *model.Bundle); ok {\n\t\tr0 = rf(ctx, id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.Bundle)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string) error); ok {\n\t\tr1 = rf(ctx, id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *PluginerMock) CommitIDCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockCommitID.RLock()\n\tcalls = mock.calls.CommitID\n\tmock.lockCommitID.RUnlock()\n\treturn calls\n}", "func (m *MockConn) UserID() uint64 {\n\tret := m.ctrl.Call(m, \"UserID\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (_m *NatsConn) GetClientID() (uint64, error) {\n\tret := _m.Called()\n\n\tvar r0 uint64\n\tif rf, ok := ret.Get(0).(func() uint64); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(uint64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func TestScalarAggregate(t *testing.T) {\n\t// disable schema tracking to have weight_string column added to query send down to mysql.\n\tclusterInstance.VtGateExtraArgs = append(clusterInstance.VtGateExtraArgs, \"--schema_change_signal=false\")\n\trequire.NoError(t,\n\t\tclusterInstance.RestartVtgate())\n\n\t// update vtgate params\n\tvtParams = clusterInstance.GetVTParams(keyspaceName)\n\n\tdefer func() {\n\t\t// roll it back\n\t\tclusterInstance.VtGateExtraArgs = append(clusterInstance.VtGateExtraArgs, \"--schema_change_signal\")\n\t\trequire.NoError(t,\n\t\t\tclusterInstance.RestartVtgate())\n\t\t// update vtgate params\n\t\tvtParams = clusterInstance.GetVTParams(keyspaceName)\n\n\t}()\n\n\tmcmp, closer := start(t)\n\tdefer closer()\n\n\tmcmp.Exec(\"insert into aggr_test(id, val1, val2) values(1,'a',1), (2,'A',1), (3,'b',1), (4,'c',3), (5,'c',4)\")\n\tmcmp.AssertMatches(\"select count(distinct val1) from aggr_test\", `[[INT64(3)]]`)\n}", "func (mock *RepositoryMock) AgentGetByIDCalls() []struct {\n\tCtx context.Context\n\tID int64\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tID int64\n\t}\n\tlockRepositoryMockAgentGetByID.RLock()\n\tcalls = mock.calls.AgentGetByID\n\tlockRepositoryMockAgentGetByID.RUnlock()\n\treturn calls\n}", "func (m *MockModel) ID() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ID\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *ExecutionManager) Create(ctx context.Context, vendorType string, vendorID int64, trigger string, extraAttrs ...map[string]interface{}) (int64, error) {\n\t_va := make([]interface{}, len(extraAttrs))\n\tfor _i := range extraAttrs {\n\t\t_va[_i] = extraAttrs[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, ctx, vendorType, vendorID, trigger)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 int64\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string, int64, string, ...map[string]interface{}) (int64, error)); ok {\n\t\treturn rf(ctx, vendorType, vendorID, trigger, extraAttrs...)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, string, int64, string, ...map[string]interface{}) int64); ok {\n\t\tr0 = rf(ctx, vendorType, vendorID, trigger, extraAttrs...)\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, string, int64, string, ...map[string]interface{}) error); ok {\n\t\tr1 = rf(ctx, vendorType, vendorID, trigger, extraAttrs...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *API) GetMangaPicture(id int) ([]string, int, error) {\n\tret := _m.Called(id)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(int) []string); ok {\n\t\tr0 = rf(id)\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\tvar r1 int\n\tif rf, ok := ret.Get(1).(func(int) int); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Get(1).(int)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(int) error); ok {\n\t\tr2 = rf(id)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}" ]
[ "0.5495845", "0.5490403", "0.54627246", "0.5439933", "0.54380864", "0.5367581", "0.5240518", "0.5239894", "0.5228337", "0.5196607", "0.5162903", "0.5103768", "0.5070772", "0.5063013", "0.50611025", "0.5040642", "0.50355613", "0.5028443", "0.50251395", "0.50246865", "0.50228244", "0.5013798", "0.5008861", "0.4997269", "0.49787816", "0.49776354", "0.49626437", "0.49562013", "0.49282444", "0.49148712", "0.49115777", "0.48853517", "0.48841733", "0.48841733", "0.48735693", "0.4868747", "0.48491946", "0.48380014", "0.48239306", "0.48214242", "0.48186764", "0.48165488", "0.4814952", "0.48127538", "0.4811081", "0.47975034", "0.47961196", "0.4782843", "0.47807324", "0.4769624", "0.47615576", "0.47548553", "0.47462738", "0.47311905", "0.47297058", "0.47157", "0.46686807", "0.46647856", "0.466096", "0.46200985", "0.46176362", "0.4611327", "0.4610074", "0.45948592", "0.45760244", "0.45741248", "0.45667198", "0.45652792", "0.4565173", "0.45623985", "0.45607954", "0.4556709", "0.45531523", "0.45486346", "0.45461425", "0.4542945", "0.45425072", "0.4531181", "0.4529109", "0.4524909", "0.45168033", "0.45157376", "0.45147866", "0.4513509", "0.4511999", "0.45067343", "0.45010033", "0.44851926", "0.44840366", "0.4480561", "0.44796228", "0.44786352", "0.44759706", "0.44749978", "0.44622576", "0.44608527", "0.44595334", "0.44516203", "0.44500783", "0.44463092" ]
0.6844021
0
AggregateName provides a mock function with given fields:
func (_m *MockAggregate) AggregateName() string { ret := _m.Called() var r0 string if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { r0 = ret.Get(0).(string) } return r0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockORM) Group(query string) ORM {\n\tret := _m.Called(query)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string) ORM); ok {\n\t\tr0 = rf(query)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockProduct) GetAggregationByName(arg0 context.Context, arg1 db.GetAggregationByNameParams) (db.Aggregation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAggregationByName\", arg0, arg1)\n\tret0, _ := ret[0].(db.Aggregation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Aggregator) Aggregate(ctx context.Context, fs vfs.FS, currentMilestone int, aggregateFilePath string, relnotesDir string) ([]byte, error) {\n\tret := _m.Called(ctx, fs, currentMilestone, aggregateFilePath, relnotesDir)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func(context.Context, vfs.FS, int, string, string) []byte); ok {\n\t\tr0 = rf(ctx, fs, currentMilestone, aggregateFilePath, relnotesDir)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, vfs.FS, int, string, string) error); ok {\n\t\tr1 = rf(ctx, fs, currentMilestone, aggregateFilePath, relnotesDir)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockAggregate) AggregateId() AggregateId {\n\tret := _m.Called()\n\n\tvar r0 AggregateId\n\tif rf, ok := ret.Get(0).(func() AggregateId); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(AggregateId)\n\t\t}\n\t}\n\n\treturn r0\n}", "func MockAggregateSealProof(proofType abi.RegisteredSealProof, minerAddr address.Address, count int) ([]byte, error) {\n\tproof := make([]byte, aggProofLen(count))\n\ti := copy(proof, mockAggregateSealProofPrefix)\n\tbinary.BigEndian.PutUint64(proof[i:], uint64(proofType))\n\ti += 8\n\tbinary.BigEndian.PutUint64(proof[i:], uint64(count))\n\ti += 8\n\ti += copy(proof[i:], minerAddr.Bytes())\n\n\treturn proof, nil\n}", "func Test_Client_MapByName(t *testing.T) {\n\t// should map by name\n\tret := mockClient.MapByName(\"South Korea\")\n\tassert.Equal(t, ret.Name, \"South Korea\")\n\tassert.Equal(t, ret.Alpha2, \"KR\")\n\tassert.Equal(t, ret.Alpha3, \"KOR\")\n\tassert.Equal(t, ret.Capital, \"Seoul\")\n\tassert.Equal(t, ret.Currency, []string{\"KRW\"})\n\tassert.Equal(t, ret.CallingCode, []string{\"82\"})\n\tassert.Equal(t, ret.Region, \"Asia\")\n\tassert.Equal(t, ret.Subregion, \"Eastern Asia\")\n\n\t// should be able to map different variations of name\n\tret = mockClient.MapByName(\"south korea\")\n\tassert.Equal(t, ret.Name, \"South Korea\")\n\n\tret = mockClient.MapByName(\"대한민국\")\n\tassert.Equal(t, ret.Name, \"South Korea\")\n\n\t// should return nil when you try to map names not commonly used\n\tret = mockClient.MapByName(\"southkorea\")\n\tassert.Nil(t, ret)\n}", "func (p *PrincipalMock) Name() string {\n\treturn p.NameFunc()\n}", "func (u *MockUserRecord) RealName() string { return \"\" }", "func (_m *MockAuth) AuthName() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockTChanNode) Aggregate(ctx thrift.Context, req *AggregateQueryRequest) (*AggregateQueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Aggregate\", ctx, req)\n\tret0, _ := ret[0].(*AggregateQueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockConnection) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func Test_Client_MapByAlpha2(t *testing.T) {\n\tret := mockClient.MapByAlpha2(\"SG\")\n\tassert.Equal(t, ret.Name, \"Singapore\")\n}", "func (_m *MockStore) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestMyAggregationFunc(t *testing.T) {\n\tcolumnsMap := make(map[string]int)\n\tcolumnsMap[\"Col1\"] = 0\n\tcolumnsMap[\"Col2\"] = 1\n\ttables := []struct {\n\t\tcounter int\n\t\tfiltrCount int\n\t\tmyAggVals []float64\n\t\tcolumnsMap map[string]int\n\t\tstoreReqCols []string\n\t\tstoreFunctions []string\n\t\trecord []string\n\t\terr error\n\t\texpectedVal float64\n\t}{\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"count\"}, []string{\"1\", \"2\"}, nil, 11},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"min\"}, []string{\"1\", \"2\"}, nil, 1},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"max\"}, []string{\"1\", \"2\"}, nil, 10},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"sum\"}, []string{\"1\", \"2\"}, nil, 11},\n\t\t{1, 1, []float64{10}, columnsMap, []string{\"Col1\"}, []string{\"avg\"}, []string{\"1\", \"2\"}, nil, 5.500},\n\t\t{10, 5, []float64{0.000}, columnsMap, []string{\"Col1\"}, []string{\"random\"}, []string{\"1\", \"2\"}, ErrParseNonUnaryAgregateFunctionCall, 0},\n\t\t{0, 5, []float64{0}, columnsMap, []string{\"0\"}, []string{\"count\"}, []string{\"1\", \"2\"}, nil, 1},\n\t\t{10, 5, []float64{10}, columnsMap, []string{\"1\"}, []string{\"min\"}, []string{\"1\", \"12\"}, nil, 10},\n\t}\n\tfor _, table := range tables {\n\t\terr := aggregationFunctions(table.counter, table.filtrCount, table.myAggVals, table.columnsMap, table.storeReqCols, table.storeFunctions, table.record)\n\t\tif table.err != err {\n\t\t\tt.Error()\n\t\t}\n\t\tif table.myAggVals[0] != table.expectedVal {\n\t\t\tt.Error()\n\t\t}\n\n\t}\n}", "func (_m *Forge) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockGatewayFinalizer) GatewayFinalizerName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GatewayFinalizerName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func awsMockStackID(stackName string) string {\n\tnh := sha1.Sum([]byte(stackName))\n\treturn fmt.Sprintf(\"arn:aws:cloudformation:mock:%012d:stack/%s/%x-%x-%x-%x-%x\",\n\t\tbinary.BigEndian.Uint32(nh[16:20]), stackName, nh[0:4], nh[4:6], nh[6:8], nh[8:10], nh[10:16])\n}", "func (m *MockIModel) MapFromByFieldName(src interface{}) interfaces.IModel {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MapFromByFieldName\", src)\n\tret0, _ := ret[0].(interfaces.IModel)\n\treturn ret0\n}", "func (_m *MockORM) Joins(query string, args ...interface{}) ORM {\n\tret := _m.Called(query, args)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string, ...interface{}) ORM); ok {\n\t\tr0 = rf(query, args...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockTChanCluster) Aggregate(ctx thrift.Context, req *AggregateQueryRequest) (*AggregateQueryResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Aggregate\", ctx, req)\n\tret0, _ := ret[0].(*AggregateQueryResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Publisher) Bind(_a0 string, _a1 string) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func Test_Client_MapByAlpha3(t *testing.T) {\n\tret := mockClient.MapByAlpha3(\"SGP\")\n\tassert.Equal(t, ret.Name, \"Singapore\")\n}", "func (m *MockManager) SerializeReleaseName(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeReleaseName\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockQueryer) GetSingleAggregationMeta(arg0 i18n.LanguageCodes, arg1, arg2 string) (*pb.Aggregation, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetSingleAggregationMeta\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*pb.Aggregation)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) GetAllNamedObjects(arg0 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllNamedObjects\", arg0)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func MockAliasRef(e Expr, r []StreamName, a *bool) *AliasRef {\n\treturn &AliasRef{e, r, a}\n}", "func (_m *ServerConnexion) Rename(sSource string, sDestination string) error {\n\tret := _m.Called(sSource, sDestination)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string) error); ok {\n\t\tr0 = rf(sSource, sDestination)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockGroupProvider) Create(createdBy int64, name string, description *ntypes.String) (*GroupEntity, error) {\n\tret := _m.Called(createdBy, name, description)\n\n\tvar r0 *GroupEntity\n\tif rf, ok := ret.Get(0).(func(int64, string, *ntypes.String) *GroupEntity); ok {\n\t\tr0 = rf(createdBy, name, description)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*GroupEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64, string, *ntypes.String) error); ok {\n\t\tr1 = rf(createdBy, name, description)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestBaseAggregateHandle(t *testing.T) {\n\tinstance := &SimpleAggregate{}\n\tstore := NewNullStore()\n\tinstance.Initialize(\"dummy-key\", counterRegistry, store)\n\terrRun := instance.Handle(InitializeCommand{\n\t\tTargetValue: 3,\n\t})\n\n\tassert.Nil(t, errRun, \"Run error should be nil\")\n\tassert.Equal(t, int64(1), instance.SequenceNumber(), \"The aggregate sequence number should be 1\")\n\tassert.Equal(t, 3, instance.TargetValue, \"The aggregate target value should be 3\")\n}", "func mockedGranter(kubeutil *kube.Kube, app *v1.RadixRegistration, namespace string, serviceAccount *corev1.ServiceAccount) error {\n\treturn nil\n}", "func (m *MockTChanNode) AggregateRaw(ctx thrift.Context, req *AggregateQueryRawRequest) (*AggregateQueryRawResult_, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AggregateRaw\", ctx, req)\n\tret0, _ := ret[0].(*AggregateQueryRawResult_)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *FieldReader) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestEmployeeManagerMapGetAll(t *testing.T) {\n\tdb, mock, err := sqlmock.New()\n\tif err != nil {\n\t\tt.Fatalf(\"an error '%s' was not expected when opening a stub database connection\", err)\n\t}\n\tdefer db.Close()\n\n\trows := sqlmock.NewRows([]string{\"employee_name\", \"manager_name\"}).AddRow(\"Nick\", \"Sophie\").AddRow(\"Sophie\", \"Jonas\")\n\tmock.ExpectExec(constants.EmployeeManagerMappingDeleteQuery).WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectPrepare(regexp.QuoteMeta(constants.EmployeeManagerMappingInsertQuery)).ExpectExec().WillReturnResult(sqlmock.NewResult(0, 0))\n\tmock.ExpectQuery(constants.EmployeeManagerMappingSelectQuery).WillReturnRows(rows)\n\n\templyManagerMap := NewEmployeeManagerMapHandler(db)\n\n\tw := httptest.NewRecorder()\n\tvar jsonStr = []byte(`{\"Peter\":\"Nick\", \"Barbara\":\"Nick\", \"Nick\":\"Sophie\", \"Sophie\":\"Jonas\"}`)\n\tr := httptest.NewRequest(\"POST\", \"http://localhost:9090/api/v1/emplymgrmap\", bytes.NewBuffer(jsonStr))\n\tr = r.WithContext(context.Background())\n\templyManagerMap.Create(w, r)\n\n\tw = httptest.NewRecorder()\n\templyManagerMap.GetAll(w, r)\n\texpectedResponse := `{\"Jonas\":{\"Sophie\":{\"Nick\":{\"Barbara\":{},\"Peter\":{}}}}}`\n\tassert.Equal(t, gohttp.StatusOK, w.Code)\n\tassert.Equal(t, expectedResponse, w.Body.String())\n}", "func (m *MockProduct) ListAggregationNameByScope(arg0 context.Context, arg1 string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListAggregationNameByScope\", arg0, arg1)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockORM) Raw(_a0 string, values ...interface{}) ORM {\n\tret := _m.Called(_a0, values)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string, ...interface{}) ORM); ok {\n\t\tr0 = rf(_a0, values...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *TemplatesRepositoryMock) GetByName(_a0 string) (*Template, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *Template\n\tif rf, ok := ret.Get(0).(func(string) *Template); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*Template)\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(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockMapInterface) Get(_a0 string) collector.Interface {\n\tret := _m.Called(_a0)\n\n\tvar r0 collector.Interface\n\tif rf, ok := ret.Get(0).(func(string) collector.Interface); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(collector.Interface)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestBaseAggregateGetKey(t *testing.T) {\n\tinstance := &SimpleAggregate{}\n\tstore := NewNullStore()\n\tinstance.Initialize(\"dummy-key\", counterRegistry, store)\n\tinstance.Refresh()\n\n\tassert.Equal(t, \"dummy-key\", instance.GetKey())\n}", "func (_m *MockAggregate) Version() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (_m *Publisher) Publish(_a0 string, _a1 amqp.Publishing) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, amqp.Publishing) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (_m *Service) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockIModel) MapToByFieldName(dest interface{}) interfaces.IModel {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MapToByFieldName\", dest)\n\tret0, _ := ret[0].(interfaces.IModel)\n\treturn ret0\n}", "func (_m *CognitoIdentityProviderAPI) CreateGroupRequest(_a0 *cognitoidentityprovider.CreateGroupInput) (*request.Request, *cognitoidentityprovider.CreateGroupOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.CreateGroupInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.CreateGroupOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.CreateGroupInput) *cognitoidentityprovider.CreateGroupOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.CreateGroupOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *AWSResourceManager) ARNFromName(_a0 string) string {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *LambdaAPI) CreateAliasRequest(_a0 *lambda.CreateAliasInput) (*request.Request, *lambda.AliasConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.CreateAliasInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.CreateAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (m *MockAccessPolicyFinalizer) AccessPolicyFinalizerName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AccessPolicyFinalizerName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *Storage) DisplayName() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *mockUpdater) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (s *BasePlSqlParserListener) EnterAggregate_function_name(ctx *Aggregate_function_nameContext) {}", "func main() {\n\tfactory := salem.Mock(basic{})\n\tfactory.Omit(\"Tag\"). // Top level field directly in the basic struct\n\t\t\t\tOmit(\"SKU.GUID\") // Nested fields\n\n\tresults := factory.Execute()\n\n\tstr := utils.PrettyMongoString(results)\n\tfmt.Printf(\"Omitting fields mocks:\\n%v\\n\\n\", str)\n}", "func (_m *MockORM) Having(query string, values ...interface{}) ORM {\n\tret := _m.Called(query, values)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string, ...interface{}) ORM); ok {\n\t\tr0 = rf(query, values...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *DynamoDBAPIMock) Query(_a0 *dynamodb.QueryInput) (*dynamodb.QueryOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *dynamodb.QueryOutput\n\tif rf, ok := ret.Get(0).(func(*dynamodb.QueryInput) *dynamodb.QueryOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*dynamodb.QueryOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*dynamodb.QueryInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestBaseAggregateDefineReplayMethod(t *testing.T) {\n\tinstance := &SimpleAggregate{}\n\tstore := NewNullStore()\n\tinstance.Initialize(\"dummy-key\", counterRegistry, store)\n\tinstance.Refresh()\n\n\t// Nothing should happen yet. Define the event type in our registry, but it should still not change\n\t// anything state-wise.\n\tinstance.ApplyEvent(UnknownEventTypeExample{})\n\teventType := counterRegistry.RegisterEvent(UnknownEventTypeExample{})\n\tassert.Equal(t, int64(1), instance.SequenceNumber(), \"The aggregate sequence number should be 1\")\n\tassert.Equal(t, 0, instance.TargetValue, \"The aggregate target value should be 0\")\n\n\tinstance.DefineReplayMethod(eventType, func(evt Event) {\n\t\tinstance.TargetValue *= 2\n\t})\n\n\t// Set target value\n\tinstance.ApplyEvent(InitializeEvent{\n\t\tTargetValue: 3,\n\t})\n\n\t// Apply our unknown event\n\tinstance.ApplyEvent(UnknownEventTypeExample{})\n\n\tassert.Equal(t, int64(3), instance.SequenceNumber(), \"The aggregate sequence number should be 3\")\n\tassert.Equal(t, 6, instance.TargetValue, \"The aggregate target value should be 6\")\n}", "func (m *MockCache) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *EventBroadcaster) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *MockAggregate) Apply(_a0 Event) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(Event) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Entity) EntityName() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *LambdaAPI) CreateAlias(_a0 *lambda.CreateAliasInput) (*lambda.AliasConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.CreateAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.CreateAliasInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *JobCache) GetJobsByRepoState(_a0 string, _a1 types.RepoState) ([]*types.Job, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 []*types.Job\n\tif rf, ok := ret.Get(0).(func(string, types.RepoState) []*types.Job); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*types.Job)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, types.RepoState) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestUploader_Upload(t *testing.T) {\n m := new(MockS3)\n u := UserService{Uploader: m}\n\n m.On(\"PutObject\", \n\t\tmock.MatchedBy(func(i *s3.PutObjectInput) bool { // HL\n\t\t\t// other assertion ...\n\t\t\tassert.Equal(t, \"imre\", *i.Key)\n\t\t\treturn true\n }).\n\t\tReturn(&s3.PutObjectOutput{}, nil) // HL\n\n err := u.UploadProfile(&User{Name: \"imre\"}, []byte(`hello`)) // HL\n assert.NoError(t, err)\n m.AssertExpectations(t)\n}", "func (_m *MockUserRepositoryProvider) GetByNameAndSurname(name string, surname string) (*model.User, error) {\n\tret := _m.Called(name, surname)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string, string) *model.User); ok {\n\t\tr0 = rf(name, surname)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string) error); ok {\n\t\tr1 = rf(name, surname)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestAggregateFuncsQuery(t *testing.T) {\n\tt.Parallel()\n\n\tconst query = `SELECT COUNT(*), SUM(rental_rate), TOTAL(rental_rate),\n\tAVG(rental_rate), MAX(rental_rate), MIN(rental_rate),\n\tMAX(title), MAX(last_update), GROUP_CONCAT(rating,',')\n\tFROM film`\n\n\tth := testh.New(t)\n\tsrc := th.Source(sakila.SL3)\n\tsink, err := th.QuerySQL(src, query)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(sink.Recs))\n}", "func (_m *Job) UUID() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *RequestContext) BindQuery(_a0 interface{}) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(interface{}) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockSpaceStorage) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockbucketNameGetter) BucketName(app, env, svc string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"BucketName\", app, env, svc)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *LambdaAPI) GetAlias(_a0 *lambda.GetAliasInput) (*lambda.AliasConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.GetAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.GetAliasInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockMember) Name() string {\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *IDepTool) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *RequestContext) DefaultQuery(_a0 string, _a1 string) string {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string, string) string); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *Repository) GetID(name string) (steamapis.Domain, error) {\n\tret := _m.Called(name)\n\n\tvar r0 steamapis.Domain\n\tif rf, ok := ret.Get(0).(func(string) steamapis.Domain); ok {\n\t\tr0 = rf(name)\n\t} else {\n\t\tr0 = ret.Get(0).(steamapis.Domain)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(name)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockBaseEvent) GetName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *LogPollerWrapper) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (sink *influxdbSink) aggregationFunc(aggregationName core.AggregationType, fieldName string) string {\n\tswitch aggregationName {\n\tcase core.AggregationTypeAverage:\n\t\treturn fmt.Sprintf(\"MEAN(%q)\", fieldName)\n\tcase core.AggregationTypeMaximum:\n\t\treturn fmt.Sprintf(\"MAX(%q)\", fieldName)\n\tcase core.AggregationTypeMinimum:\n\t\treturn fmt.Sprintf(\"MIN(%q)\", fieldName)\n\tcase core.AggregationTypeMedian:\n\t\treturn fmt.Sprintf(\"MEDIAN(%q)\", fieldName)\n\tcase core.AggregationTypeCount:\n\t\treturn fmt.Sprintf(\"COUNT(%q)\", fieldName)\n\tcase core.AggregationTypePercentile50:\n\t\treturn fmt.Sprintf(\"PERCENTILE(%q, 50)\", fieldName)\n\tcase core.AggregationTypePercentile95:\n\t\treturn fmt.Sprintf(\"PERCENTILE(%q, 95)\", fieldName)\n\tcase core.AggregationTypePercentile99:\n\t\treturn fmt.Sprintf(\"PERCENTILE(%q, 99)\", fieldName)\n\t}\n\n\t// This should have been checked by the API level, so something's seriously wrong here\n\tpanic(fmt.Sprintf(\"Unknown aggregation type %q\", aggregationName))\n}", "func (_m *Worktree) Add(_a0 string) (plumbing.Hash, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 plumbing.Hash\n\tif rf, ok := ret.Get(0).(func(string) plumbing.Hash); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(plumbing.Hash)\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(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *mockJwtParser) parse(_a0 string, _a1 jwt.Keyfunc) (*jwt.Token, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *jwt.Token\n\tif rf, ok := ret.Get(0).(func(string, jwt.Keyfunc) *jwt.Token); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*jwt.Token)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, jwt.Keyfunc) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Service) Add(_a0 []byte) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func([]byte) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (m *MockTracks) GetNormalizedJourneyAggregate(ownerID int64, columnName, conversionColumnName, conversionRowValue string) ([]app.PosAggregate, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNormalizedJourneyAggregate\", ownerID, columnName, conversionColumnName, conversionRowValue)\n\tret0, _ := ret[0].([]app.PosAggregate)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetLeastPopulatedNamespace(t *testing.T) {\n\n\t// Test Data\n\tnamespaceName1 := \"TestNamespaceName1\"\n\tnamespaceName2 := \"TestNamespaceName2\"\n\tnamespaceName3 := \"TestNamespaceName3\"\n\tnamespaceName4 := \"TestNamespaceName4\"\n\tnamespaceName5 := \"TestNamespaceName5\"\n\tnamespaceCount1 := 4\n\tnamespaceCount2 := 2\n\tnamespaceCount3 := 0\n\tnamespaceCount4 := 2\n\tnamespaceCount5 := 1\n\n\t// Create A Mock HubManager\n\tmockHubManager := &MockHubManager{}\n\n\t// Replace The NewHubManagerFromConnectionString Wrapper To Provide Mock Implementation & Defer Reset\n\tnewHubManagerFromConnectionStringWrapperPlaceholder := NewHubManagerFromConnectionStringWrapper\n\tNewHubManagerFromConnectionStringWrapper = func(connectionString string) (managerInterface HubManagerInterface, e error) {\n\t\treturn mockHubManager, nil\n\t}\n\tdefer func() { NewHubManagerFromConnectionStringWrapper = newHubManagerFromConnectionStringWrapperPlaceholder }()\n\n\t// Create A Test Logger\n\tlogger := logtesting.TestLogger(t).Desugar()\n\n\t// Create The Cache's Namespace Map\n\tnamespaceMap := make(map[string]*Namespace)\n\tnamespaceMap[namespaceName1], _ = createTestNamespaceWithCount(logger, namespaceName1, namespaceCount1)\n\tnamespaceMap[namespaceName2], _ = createTestNamespaceWithCount(logger, namespaceName2, namespaceCount2)\n\tnamespaceMap[namespaceName3], _ = createTestNamespaceWithCount(logger, namespaceName3, namespaceCount3)\n\tnamespaceMap[namespaceName4], _ = createTestNamespaceWithCount(logger, namespaceName4, namespaceCount4)\n\tnamespaceMap[namespaceName5], _ = createTestNamespaceWithCount(logger, namespaceName5, namespaceCount5)\n\n\t// Create A Cache To Test\n\tcache := &Cache{\n\t\tlogger: logger,\n\t\tnamespaceMap: namespaceMap,\n\t}\n\n\t// Perform The Test\n\tnamespace := cache.GetLeastPopulatedNamespace()\n\n\t// Verify Results\n\tassert.NotNil(t, namespace)\n\tassert.Equal(t, namespaceName3, namespace.Name)\n\tassert.Equal(t, namespaceCount3, namespace.Count)\n}", "func (_m *Factory) ResolveImage(imageName string) (string, error) {\n\tret := _m.Called(imageName)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(imageName)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(imageName)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *CognitoIdentityProviderAPI) GetGroupRequest(_a0 *cognitoidentityprovider.GetGroupInput) (*request.Request, *cognitoidentityprovider.GetGroupOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.GetGroupInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.GetGroupOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.GetGroupInput) *cognitoidentityprovider.GetGroupOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.GetGroupOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (m *MockCall) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *Keyring) GetMetadata(_a0 string) (keyring.Metadata, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 keyring.Metadata\n\tif rf, ok := ret.Get(0).(func(string) keyring.Metadata); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(keyring.Metadata)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Plugin) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestGetNamespace(t *testing.T) {\n\n\t// Test Data\n\tnamespaceName1 := \"TestNamespaceName1\"\n\tnamespaceName2 := \"TestNamespaceName2\"\n\tnamespaceSecret1 := \"TestNamespaceSecret1\"\n\tnamespaceSecret2 := \"TestNamespaceSecret2\"\n\n\t// Create A Mock HubManager\n\tmockHubManager := &MockHubManager{}\n\n\t// Replace The NewHubManagerFromConnectionString Wrapper To Provide Mock Implementation & Defer Reset\n\tnewHubManagerFromConnectionStringWrapperPlaceholder := NewHubManagerFromConnectionStringWrapper\n\tNewHubManagerFromConnectionStringWrapper = func(connectionString string) (managerInterface HubManagerInterface, e error) {\n\t\treturn mockHubManager, nil\n\t}\n\tdefer func() { NewHubManagerFromConnectionStringWrapper = newHubManagerFromConnectionStringWrapperPlaceholder }()\n\n\t// Create A Test Logger\n\tlogger := logtesting.TestLogger(t).Desugar()\n\n\t// Create The Cache's EventHub Map\n\tvar err error\n\teventHubMap := make(map[string]*Namespace)\n\teventHubMap[namespaceName1], err = createTestNamespaceWithSecret(logger, namespaceName1, namespaceSecret1)\n\tassert.NotNil(t, eventHubMap[namespaceName1])\n\tassert.Nil(t, err)\n\teventHubMap[namespaceName2], err = createTestNamespaceWithSecret(logger, namespaceName2, namespaceSecret2)\n\tassert.NotNil(t, eventHubMap[namespaceName2])\n\tassert.Nil(t, err)\n\n\t// Create A Cache To Test\n\tcache := &Cache{\n\t\tlogger: logger,\n\t\teventhubMap: eventHubMap,\n\t}\n\n\t// Perform The Test\n\tnamespace := cache.GetNamespace(namespaceName2)\n\n\t// Verify The Results\n\tassert.NotNil(t, namespace)\n\tassert.Equal(t, namespaceName2, namespace.Name)\n\tassert.Equal(t, namespaceSecret2, namespace.Secret)\n}", "func Test_Client_MapByCallingCode(t *testing.T) {\n\tret := mockClient.MapByCallingCode(\"65\")\n\tassert.Equal(t, ret[0].Name, \"Singapore\")\n}", "func (_m *Repository) Tag(_a0 string) (*plumbing.Reference, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *plumbing.Reference\n\tif rf, ok := ret.Get(0).(func(string) *plumbing.Reference); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*plumbing.Reference)\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(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIUserService) QueryUserByName(name string) (*model.UserDB, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"QueryUserByName\", name)\n\tret0, _ := ret[0].(*model.UserDB)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Keyring) Get(_a0 string) (keyring.Item, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 keyring.Item\n\tif rf, ok := ret.Get(0).(func(string) keyring.Item); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(keyring.Item)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *T) Name() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *CognitoIdentityProviderAPI) AdminAddUserToGroupRequest(_a0 *cognitoidentityprovider.AdminAddUserToGroupInput) (*request.Request, *cognitoidentityprovider.AdminAddUserToGroupOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.AdminAddUserToGroupInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.AdminAddUserToGroupOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.AdminAddUserToGroupInput) *cognitoidentityprovider.AdminAddUserToGroupOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.AdminAddUserToGroupOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *Database) GetByID(_a0 string) (map[string]string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 map[string]string\n\tif rf, ok := ret.Get(0).(func(string) map[string]string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]string)\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(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockAPI) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *MockDatabase) GetUserByName(name string) *model.User {\n\tret := _m.Called(name)\n\n\tvar r0 *model.User\n\tif rf, ok := ret.Get(0).(func(string) *model.User); ok {\n\t\tr0 = rf(name)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.User)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockUpstreamIntf) Name() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Name\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *LambdaAPI) GetAliasRequest(_a0 *lambda.GetAliasInput) (*request.Request, *lambda.AliasConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.GetAliasInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.GetAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) UpdateAlias(_a0 *lambda.UpdateAliasInput) (*lambda.AliasConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateAliasInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Service) Get(_a0 uint) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func(uint) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (_m *IRepository) Store(name string, age int) error {\n\tret := _m.Called(name, age)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int) error); ok {\n\t\tr0 = rf(name, age)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}" ]
[ "0.54706424", "0.5427147", "0.5411635", "0.53259814", "0.52480215", "0.5112713", "0.5103304", "0.50429875", "0.50058126", "0.49664485", "0.49663937", "0.49218696", "0.4901599", "0.48994717", "0.48761216", "0.4872714", "0.4859629", "0.48289967", "0.4812752", "0.47973967", "0.4793255", "0.4771051", "0.4770497", "0.47660014", "0.47549275", "0.47515675", "0.47467458", "0.47450256", "0.47360632", "0.47351995", "0.47296852", "0.47292674", "0.47279495", "0.47255078", "0.47244096", "0.47217938", "0.4720331", "0.47190544", "0.47123373", "0.47066483", "0.47058818", "0.47049236", "0.470108", "0.46986324", "0.46858567", "0.46857944", "0.46728712", "0.4665711", "0.46601692", "0.46509892", "0.46473256", "0.46456534", "0.46380264", "0.4632102", "0.4629507", "0.4628571", "0.46276575", "0.46270812", "0.46210313", "0.4615848", "0.46114334", "0.46056834", "0.4599857", "0.45983484", "0.45929912", "0.45855144", "0.45821428", "0.45804128", "0.4576496", "0.45629892", "0.4559867", "0.45593813", "0.45482796", "0.4547557", "0.4546919", "0.45449197", "0.45442072", "0.45441473", "0.45436603", "0.45416132", "0.4535759", "0.45334592", "0.45324692", "0.45227957", "0.4522406", "0.45191962", "0.45171875", "0.45085305", "0.45010048", "0.4498352", "0.44908962", "0.44889238", "0.44839984", "0.44838366", "0.44812742", "0.44686493", "0.44629195", "0.4458879", "0.44550836", "0.44508553" ]
0.6614694
0
Apply provides a mock function with given fields: _a0
func (_m *MockAggregate) Apply(_a0 Event) error { ret := _m.Called(_a0) var r0 error if rf, ok := ret.Get(0).(func(Event) error); ok { r0 = rf(_a0) } else { r0 = ret.Error(0) } return r0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *mockUpdater) ApplyUpdate(_a0 context.Context, _a1 updater.Update) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, updater.Update) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockDiscountApplier) ApplyToList(_a0 []products.Product) []Product {\n\tret := _m.Called(_a0)\n\n\tvar r0 []Product\n\tif rf, ok := ret.Get(0).(func([]products.Product) []Product); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]Product)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *MockCompletableFuture[T]) ThenApply(_a0 func(T)) {\n\t_m.Called(_a0)\n}", "func (_e *MockCompletableFuture_Expecter[T]) ThenApply(_a0 interface{}) *MockCompletableFuture_ThenApply_Call[T] {\n\treturn &MockCompletableFuture_ThenApply_Call[T]{Call: _e.mock.On(\"ThenApply\", _a0)}\n}", "func (_m *AppFunctionContext) ApplyValues(format string) (string, error) {\n\tret := _m.Called(format)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(format)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(format)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockInterface) Execute(_a0 string, _a1 ...string) ([]byte, error) {\n\t_va := make([]interface{}, len(_a1))\n\tfor _i := range _a1 {\n\t\t_va[_i] = _a1[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _a0)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func(string, ...string) []byte); ok {\n\t\tr0 = rf(_a0, _a1...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, ...string) error); ok {\n\t\tr1 = rf(_a0, _a1...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockInterface) Apply(arg0 context.Context, arg1 kubernetes.ChartApplier, arg2 string, arg3 imagevector.ImageVector, arg4, arg5 string, arg6 map[string]interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Apply\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *mockStateBuilder) applyEvents(domainID string, requestID string, execution shared.WorkflowExecution, _a3 []*shared.HistoryEvent,\n\tnewRunHistory []*shared.HistoryEvent, eventStoreVersion, newRunEventStoreVersion int32, newRunNDC bool) (*shared.HistoryEvent, *decisionInfo, mutableState, error) {\n\n\tret := _m.Called(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\n\tvar r0 *shared.HistoryEvent\n\tif rf, ok := ret.Get(0).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *shared.HistoryEvent); ok {\n\t\tr0 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*shared.HistoryEvent)\n\t\t}\n\t}\n\n\tvar r1 *decisionInfo\n\tif rf, ok := ret.Get(1).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *decisionInfo); ok {\n\t\tr1 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*decisionInfo)\n\t\t}\n\t}\n\n\tvar r2 mutableState\n\tif rf, ok := ret.Get(2).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) mutableState); ok {\n\t\tr2 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(mutableState)\n\t\t}\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) error); ok {\n\t\tr3 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (_e *GiftCardHandler_Expecter) ApplyGiftCard(ctx interface{}, _a1 interface{}, giftCardCode interface{}) *GiftCardHandler_ApplyGiftCard_Call {\n\treturn &GiftCardHandler_ApplyGiftCard_Call{Call: _e.mock.On(\"ApplyGiftCard\", ctx, _a1, giftCardCode)}\n}", "func (_m *Service) Update(_a0 uint, _a1 []byte) apifarm.Query {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func(uint, []byte) apifarm.Query); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (_m *Operator) Process(_a0 context.Context, _a1 *entry.Entry) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *entry.Entry) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockInterface) Apply(ctx context.Context, persistentVolume *corev1.PersistentVolumeApplyConfiguration, opts metav1.ApplyOptions) (result *v1.PersistentVolume, err error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, persistentVolume, opts}\n\tret := m.ctrl.Call(m, \"Apply\", varargs...)\n\tret0, _ := ret[0].(*v1.PersistentVolume)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *LogProcessor) Process(_a0 []byte) (map[string]summary.SpecificTestStats, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 map[string]summary.SpecificTestStats\n\tif rf, ok := ret.Get(0).(func([]byte) map[string]summary.SpecificTestStats); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]summary.SpecificTestStats)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *ControllerInterface) UpdateArrays(_a0 string, _a1 fs.Interface) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, fs.Interface) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *CognitoIdentityProviderAPI) UpdateUserAttributesRequest(_a0 *cognitoidentityprovider.UpdateUserAttributesInput) (*request.Request, *cognitoidentityprovider.UpdateUserAttributesOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.UpdateUserAttributesInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.UpdateUserAttributesOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.UpdateUserAttributesInput) *cognitoidentityprovider.UpdateUserAttributesOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.UpdateUserAttributesOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *ApplicationServiceInterface) Update(_a0 *models.Application) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*models.Application) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockRepository) UpdateACO(ctx context.Context, acoUUID uuid.UUID, fieldsAndValues map[string]interface{}) error {\n\tret := _m.Called(ctx, acoUUID, fieldsAndValues)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, uuid.UUID, map[string]interface{}) error); ok {\n\t\tr0 = rf(ctx, acoUUID, fieldsAndValues)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockORM) Exec(_a0 string, values ...interface{}) ORM {\n\tret := _m.Called(_a0, values)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string, ...interface{}) ORM); ok {\n\t\tr0 = rf(_a0, values...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockChart) Apply(arg0 context.Context, arg1 kubernetes.ChartApplier, arg2 string, arg3 imagevector.ImageVector, arg4, arg5 string, arg6 map[string]interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Apply\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *Repository) Update(ctx context.Context, _a1 *models.Host) error {\n\tret := _m.Called(ctx, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.Host) error); ok {\n\t\tr0 = rf(ctx, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockORM) Raw(_a0 string, values ...interface{}) ORM {\n\tret := _m.Called(_a0, values)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(string, ...interface{}) ORM); ok {\n\t\tr0 = rf(_a0, values...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *LambdaAPI) UpdateAliasRequest(_a0 *lambda.UpdateAliasInput) (*request.Request, *lambda.AliasConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateAliasInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *MatchFunc) Execute(_a0 *ari.Key) bool {\n\tret := _m.Called(_a0)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(*ari.Key) bool); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func (_m *CognitoIdentityProviderAPI) UpdateUserAttributes(_a0 *cognitoidentityprovider.UpdateUserAttributesInput) (*cognitoidentityprovider.UpdateUserAttributesOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.UpdateUserAttributesOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.UpdateUserAttributesInput) *cognitoidentityprovider.UpdateUserAttributesOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.UpdateUserAttributesOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.UpdateUserAttributesInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) UpdateEventSourceMappingRequest(_a0 *lambda.UpdateEventSourceMappingInput) (*request.Request, *lambda.EventSourceMappingConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateEventSourceMappingInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.EventSourceMappingConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateEventSourceMappingInput) *lambda.EventSourceMappingConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.EventSourceMappingConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *CognitoIdentityProviderAPI) AdminUpdateUserAttributesRequest(_a0 *cognitoidentityprovider.AdminUpdateUserAttributesInput) (*request.Request, *cognitoidentityprovider.AdminUpdateUserAttributesOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.AdminUpdateUserAttributesInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.AdminUpdateUserAttributesOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.AdminUpdateUserAttributesInput) *cognitoidentityprovider.AdminUpdateUserAttributesOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.AdminUpdateUserAttributesOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *mockJwtParser) parse(_a0 string, _a1 jwt.Keyfunc) (*jwt.Token, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *jwt.Token\n\tif rf, ok := ret.Get(0).(func(string, jwt.Keyfunc) *jwt.Token); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*jwt.Token)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, jwt.Keyfunc) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) UpdateEventSourceMapping(_a0 *lambda.UpdateEventSourceMappingInput) (*lambda.EventSourceMappingConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.EventSourceMappingConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateEventSourceMappingInput) *lambda.EventSourceMappingConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.EventSourceMappingConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateEventSourceMappingInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *UseUnitOfWork) Execute(_a0 context.Context, _a1 func(context.Context, app.UnitOfWork) error) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, func(context.Context, app.UnitOfWork) error) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Index) AddOrUpdate(_a0 index.Entry) (storage.Event, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 storage.Event\n\tif rf, ok := ret.Get(0).(func(index.Entry) storage.Event); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(storage.Event)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(index.Entry) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *CognitoIdentityProviderAPI) AdminUpdateUserAttributes(_a0 *cognitoidentityprovider.AdminUpdateUserAttributesInput) (*cognitoidentityprovider.AdminUpdateUserAttributesOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.AdminUpdateUserAttributesOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.AdminUpdateUserAttributesInput) *cognitoidentityprovider.AdminUpdateUserAttributesOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.AdminUpdateUserAttributesOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.AdminUpdateUserAttributesInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (o *FakeObject) Invoke(args ...interface{}) Object {\n\ta2 := make([]reflect.Value, len(args))\n\tfor i, a := range args {\n\t\ta2[i] = reflect.ValueOf(a)\n\t}\n\treturn MakeFakeObject(reflect.ValueOf(o.Value).CallSlice(a2))\n}", "func (_m *LambdaAPI) UpdateFunctionConfigurationRequest(_a0 *lambda.UpdateFunctionConfigurationInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateFunctionConfigurationInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateFunctionConfigurationInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *Service) Update(_a0 context.Context, _a1 *roles.Role) (string, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(context.Context, *roles.Role) string); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *roles.Role) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func apply(op func(arg1, arg2 int) int, a, b int) int{\n\tp := reflect.ValueOf(op).Pointer()\n\topName := runtime.FuncForPC(p).Name()\n\tfmt.Printf(\"calling function with multi args: %s\" +\n\t\t\"(%d, %d)\\n\", opName, a, b)\n\tfmt.Print(\"the result is: \")\n\treturn op(a, b)\n}", "func (_m *DynamoDBAPIMock) UpdateTimeToLiveRequest(_a0 *dynamodb.UpdateTimeToLiveInput) (*request.Request, *dynamodb.UpdateTimeToLiveOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateTimeToLiveInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *dynamodb.UpdateTimeToLiveOutput\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateTimeToLiveInput) *dynamodb.UpdateTimeToLiveOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*dynamodb.UpdateTimeToLiveOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *UserRepo) UpdateUser(_a0 *models.User) (*models.User, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *models.User\n\tif rf, ok := ret.Get(0).(func(*models.User) *models.User); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.User)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*models.User) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *FakeScheduleService) evalApplied(_a0 models.AlertRuleKey, _a1 time.Time) {\n\t_m.Called(_a0, _a1)\n}", "func (m *MockProposalContract) Apply(args *core.ProposalApplyArgs) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Apply\", args)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *Test) A(_a0 int) int {\n\tret := _m.Called(_a0)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(int) int); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (m *MockIDistributedEnforcer) UpdateFilteredPoliciesSelf(arg0 func() bool, arg1, arg2 string, arg3 [][]string, arg4 int, arg5 ...string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1, arg2, arg3, arg4}\n\tfor _, a := range arg5 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UpdateFilteredPoliciesSelf\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *GiftCardHandler) ApplyGiftCard(ctx context.Context, _a1 *cart.Cart, giftCardCode string) (*cart.Cart, error) {\n\tret := _m.Called(ctx, _a1, giftCardCode)\n\n\tvar r0 *cart.Cart\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *cart.Cart, string) (*cart.Cart, error)); ok {\n\t\treturn rf(ctx, _a1, giftCardCode)\n\t}\n\tif rf, ok := ret.Get(0).(func(context.Context, *cart.Cart, string) *cart.Cart); ok {\n\t\tr0 = rf(ctx, _a1, giftCardCode)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cart.Cart)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(context.Context, *cart.Cart, string) error); ok {\n\t\tr1 = rf(ctx, _a1, giftCardCode)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DynamoDBAPIMock) UpdateContinuousBackupsRequest(_a0 *dynamodb.UpdateContinuousBackupsInput) (*request.Request, *dynamodb.UpdateContinuousBackupsOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateContinuousBackupsInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *dynamodb.UpdateContinuousBackupsOutput\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateContinuousBackupsInput) *dynamodb.UpdateContinuousBackupsOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*dynamodb.UpdateContinuousBackupsOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) UpdateFunctionCodeRequest(_a0 *lambda.UpdateFunctionCodeInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateFunctionCodeInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateFunctionCodeInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (b *KRMBlueprintTest) DefineApply(apply func(*assert.Assertions)) {\n\tb.apply = apply\n}", "func (_m *Service) Add(_a0 []byte) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func([]byte) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (_m *DynamoDBAPIMock) UpdateTimeToLive(_a0 *dynamodb.UpdateTimeToLiveInput) (*dynamodb.UpdateTimeToLiveOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *dynamodb.UpdateTimeToLiveOutput\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateTimeToLiveInput) *dynamodb.UpdateTimeToLiveOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*dynamodb.UpdateTimeToLiveOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateTimeToLiveInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) UpdateFunctionConfiguration(_a0 *lambda.UpdateFunctionConfigurationInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateFunctionConfigurationInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateFunctionConfigurationInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockORM) UpdateColumns(values interface{}) ORM {\n\tret := _m.Called(values)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(interface{}) ORM); ok {\n\t\tr0 = rf(values)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *Client) UpdateBuildProperties(_a0 context.Context, _a1 build.UpdateBuildPropertiesArgs) (interface{}, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 interface{}\n\tif rf, ok := ret.Get(0).(func(context.Context, build.UpdateBuildPropertiesArgs) interface{}); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(interface{})\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.UpdateBuildPropertiesArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Option) Execute(_a0 *client.Client) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*client.Client) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Repository) Update(condition *entities.User, _a1 *entities.User) (uint, error) {\n\tret := _m.Called(condition, _a1)\n\n\tvar r0 uint\n\tif rf, ok := ret.Get(0).(func(*entities.User, *entities.User) uint); ok {\n\t\tr0 = rf(condition, _a1)\n\t} else {\n\t\tr0 = ret.Get(0).(uint)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*entities.User, *entities.User) error); ok {\n\t\tr1 = rf(condition, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *RepositoryMock) Update(args db_models.DbDTO) error {\n\tret := _m.Called(args)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(db_models.DbDTO) error); ok {\n\t\tr0 = rf(args)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *LambdaAPI) PublishVersionRequest(_a0 *lambda.PublishVersionInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) UpdateAlias(_a0 *lambda.UpdateAliasInput) (*lambda.AliasConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.AliasConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateAliasInput) *lambda.AliasConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.AliasConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateAliasInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Publisher) Bind(_a0 string, _a1 string) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockAuthServiceServer) Parse(_a0 context.Context, _a1 *ParseRequest) (*ParseResponse, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *ParseResponse\n\tif rf, ok := ret.Get(0).(func(context.Context, *ParseRequest) *ParseResponse); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*ParseResponse)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *ParseRequest) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Foldable) Pack(_a0 sortedset.Set, _a1 uint64, _a2 uint8) uint64 {\n\tret := _m.Called(_a0, _a1, _a2)\n\n\tvar r0 uint64\n\tif rf, ok := ret.Get(0).(func(sortedset.Set, uint64, uint8) uint64); ok {\n\t\tr0 = rf(_a0, _a1, _a2)\n\t} else {\n\t\tr0 = ret.Get(0).(uint64)\n\t}\n\n\treturn r0\n}", "func apply(\n\ttest func(t *testing.T, conf interface{}, opts ...option),\n\tconf interface{}, opts ...option,\n) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\ttest(t, conf, opts...)\n\t}\n}", "func (_m *DynamoDBAPIMock) UpdateContinuousBackups(_a0 *dynamodb.UpdateContinuousBackupsInput) (*dynamodb.UpdateContinuousBackupsOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *dynamodb.UpdateContinuousBackupsOutput\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateContinuousBackupsInput) *dynamodb.UpdateContinuousBackupsOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*dynamodb.UpdateContinuousBackupsOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateContinuousBackupsInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockIModel) MapFromByFieldTag(src interface{}) interfaces.IModel {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MapFromByFieldTag\", src)\n\tret0, _ := ret[0].(interfaces.IModel)\n\treturn ret0\n}", "func (_m *MockHistoryEngine) ReapplyEvents(ctx context.Context, domainUUID string, workflowID string, events []*shared.HistoryEvent) error {\n\tret := _m.Called(domainUUID, workflowID, events)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string, []*shared.HistoryEvent) error); ok {\n\t\tr0 = rf(domainUUID, workflowID, events)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockIModel) MapToByFieldTag(dest interface{}) interfaces.IModel {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MapToByFieldTag\", dest)\n\tret0, _ := ret[0].(interfaces.IModel)\n\treturn ret0\n}", "func (_m *CacheManager) Update(key string, o *objects.Object) bool {\n\tret := _m.Called(key, o)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(string, *objects.Object) bool); ok {\n\t\tr0 = rf(key, o)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func (m *MockIModel) MapFromByFieldName(src interface{}) interfaces.IModel {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MapFromByFieldName\", src)\n\tret0, _ := ret[0].(interfaces.IModel)\n\treturn ret0\n}", "func (_m *LambdaAPI) UpdateFunctionCode(_a0 *lambda.UpdateFunctionCodeInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateFunctionCodeInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateFunctionCodeInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *CognitoIdentityProviderAPI) UpdateUserPoolRequest(_a0 *cognitoidentityprovider.UpdateUserPoolInput) (*request.Request, *cognitoidentityprovider.UpdateUserPoolOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.UpdateUserPoolInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.UpdateUserPoolOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.UpdateUserPoolInput) *cognitoidentityprovider.UpdateUserPoolOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.UpdateUserPoolOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockInterface) Run(_a0 io.Writer, _a1 string, _a2 ...string) error {\n\t_va := make([]interface{}, len(_a2))\n\tfor _i := range _a2 {\n\t\t_va[_i] = _a2[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _a0, _a1)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(io.Writer, string, ...string) error); ok {\n\t\tr0 = rf(_a0, _a1, _a2...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *CognitoIdentityProviderAPI) AddCustomAttributesRequest(_a0 *cognitoidentityprovider.AddCustomAttributesInput) (*request.Request, *cognitoidentityprovider.AddCustomAttributesOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.AddCustomAttributesInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.AddCustomAttributesOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.AddCustomAttributesInput) *cognitoidentityprovider.AddCustomAttributesOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.AddCustomAttributesOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *Asconn) RequestInfo(_a0 ...string) (map[string]string, aerospike.Error) {\n\t_va := make([]interface{}, len(_a0))\n\tfor _i := range _a0 {\n\t\t_va[_i] = _a0[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 map[string]string\n\tif rf, ok := ret.Get(0).(func(...string) map[string]string); ok {\n\t\tr0 = rf(_a0...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(map[string]string)\n\t\t}\n\t}\n\n\tvar r1 aerospike.Error\n\tif rf, ok := ret.Get(1).(func(...string) aerospike.Error); ok {\n\t\tr1 = rf(_a0...)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(aerospike.Error)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *Client) UpdateBuilds(_a0 context.Context, _a1 build.UpdateBuildsArgs) (*[]build.Build, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *[]build.Build\n\tif rf, ok := ret.Get(0).(func(context.Context, build.UpdateBuildsArgs) *[]build.Build); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*[]build.Build)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.UpdateBuildsArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DynamoDBAPIMock) BatchWriteItemRequest(_a0 *dynamodb.BatchWriteItemInput) (*request.Request, *dynamodb.BatchWriteItemOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*dynamodb.BatchWriteItemInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *dynamodb.BatchWriteItemOutput\n\tif rf, ok := ret.Get(1).(func(*dynamodb.BatchWriteItemInput) *dynamodb.BatchWriteItemOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*dynamodb.BatchWriteItemOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *Client) UpdateDefinitionProperties(_a0 context.Context, _a1 build.UpdateDefinitionPropertiesArgs) (interface{}, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 interface{}\n\tif rf, ok := ret.Get(0).(func(context.Context, build.UpdateDefinitionPropertiesArgs) interface{}); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(interface{})\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.UpdateDefinitionPropertiesArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *SnapshotHandler) Provide(lastSnapshot raftpb.Snapshot, entriesAppliedSinceLastSnapshot []raftpb.Entry) ([]byte, error) {\n\tret := _m.Called(lastSnapshot, entriesAppliedSinceLastSnapshot)\n\n\tvar r0 []byte\n\tif rf, ok := ret.Get(0).(func(raftpb.Snapshot, []raftpb.Entry) []byte); ok {\n\t\tr0 = rf(lastSnapshot, entriesAppliedSinceLastSnapshot)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(raftpb.Snapshot, []raftpb.Entry) error); ok {\n\t\tr1 = rf(lastSnapshot, entriesAppliedSinceLastSnapshot)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *mockContext) SetState(_a0 map[string][]byte) ([]string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(map[string][]byte) []string); ok {\n\t\tr0 = rf(_a0)\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\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(map[string][]byte) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockORM) Update(attrs ...interface{}) ORM {\n\tret := _m.Called(attrs)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(...interface{}) ORM); ok {\n\t\tr0 = rf(attrs...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *Manager) Update(ctx context.Context, projectID int64, meta map[string]string) error {\n\tret := _m.Called(ctx, projectID, meta)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, int64, map[string]string) error); ok {\n\t\tr0 = rf(ctx, projectID, meta)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *DynamoDBAPIMock) UpdateTableRequest(_a0 *dynamodb.UpdateTableInput) (*request.Request, *dynamodb.UpdateTableOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateTableInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *dynamodb.UpdateTableOutput\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateTableInput) *dynamodb.UpdateTableOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*dynamodb.UpdateTableOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *Repository) Update(ctx context.Context, ar *models.Facilities) error {\n\tret := _m.Called(ctx, ar)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.Facilities) error); ok {\n\t\tr0 = rf(ctx, ar)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockIModel) MapToByFieldName(dest interface{}) interfaces.IModel {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MapToByFieldName\", dest)\n\tret0, _ := ret[0].(interfaces.IModel)\n\treturn ret0\n}", "func (_m *MockUserProvider) UpdateOneByID(_a0 int64, _a1 *UserPatch) (*UserEntity, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *UserEntity\n\tif rf, ok := ret.Get(0).(func(int64, *UserPatch) *UserEntity); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*UserEntity)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64, *UserPatch) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Usecase) UpdateItem(_a0 context.Context, _a1 *request.ItemRequest) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *request.ItemRequest) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *CognitoIdentityProviderAPI) UpdateUserPoolDomainRequest(_a0 *cognitoidentityprovider.UpdateUserPoolDomainInput) (*request.Request, *cognitoidentityprovider.UpdateUserPoolDomainOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.UpdateUserPoolDomainInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.UpdateUserPoolDomainOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.UpdateUserPoolDomainInput) *cognitoidentityprovider.UpdateUserPoolDomainOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.UpdateUserPoolDomainOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) Invoke(_a0 *lambda.InvokeInput) (*lambda.InvokeOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.InvokeOutput\n\tif rf, ok := ret.Get(0).(func(*lambda.InvokeInput) *lambda.InvokeOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.InvokeOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.InvokeInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DynamoDBAPIMock) UpdateGlobalTableRequest(_a0 *dynamodb.UpdateGlobalTableInput) (*request.Request, *dynamodb.UpdateGlobalTableOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateGlobalTableInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *dynamodb.UpdateGlobalTableOutput\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateGlobalTableInput) *dynamodb.UpdateGlobalTableOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*dynamodb.UpdateGlobalTableOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) InvokeRequest(_a0 *lambda.InvokeInput) (*request.Request, *lambda.InvokeOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.InvokeInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.InvokeOutput\n\tif rf, ok := ret.Get(1).(func(*lambda.InvokeInput) *lambda.InvokeOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.InvokeOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockORM) Assign(attrs ...interface{}) ORM {\n\tret := _m.Called(attrs)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(...interface{}) ORM); ok {\n\t\tr0 = rf(attrs...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *AppealService) Find(_a0 map[string]interface{}) ([]*domain.Appeal, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []*domain.Appeal\n\tif rf, ok := ret.Get(0).(func(map[string]interface{}) []*domain.Appeal); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*domain.Appeal)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(map[string]interface{}) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DynamoDBAPIMock) UpdateItemRequest(_a0 *dynamodb.UpdateItemInput) (*request.Request, *dynamodb.UpdateItemOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*dynamodb.UpdateItemInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *dynamodb.UpdateItemOutput\n\tif rf, ok := ret.Get(1).(func(*dynamodb.UpdateItemInput) *dynamodb.UpdateItemOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*dynamodb.UpdateItemOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (_m *TemplatesRepositoryMock) Upsert(_a0 *Template) (*Template, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *Template\n\tif rf, ok := ret.Get(0).(func(*Template) *Template); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*Template)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*Template) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *OplogCursor) Push(_a0 []byte) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func([]byte) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Publisher) Publish(_a0 string, _a1 amqp.Publishing) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, amqp.Publishing) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Usecase) Update(ctx context.Context, _a1 *models.Category) error {\n\tret := _m.Called(ctx, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.Category) error); ok {\n\t\tr0 = rf(ctx, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockENotifyingList) Set(_a0 int, _a1 interface{}) interface{} {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 interface{}\n\tif rf, ok := ret.Get(0).(func(int, interface{}) interface{}); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(interface{})\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *Client) UpdateBuildSettings(_a0 context.Context, _a1 build.UpdateBuildSettingsArgs) (*build.BuildSettings, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *build.BuildSettings\n\tif rf, ok := ret.Get(0).(func(context.Context, build.UpdateBuildSettingsArgs) *build.BuildSettings); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*build.BuildSettings)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.UpdateBuildSettingsArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Repository) Log(_a0 *git.LogOptions) (object.CommitIter, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 object.CommitIter\n\tif rf, ok := ret.Get(0).(func(*git.LogOptions) object.CommitIter); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(object.CommitIter)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*git.LogOptions) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func mockMapStore(storage map[string]interface{}) ResultStoreFn {\n\treturn func(id string, key string, value interface{}) {\n\t\tutil.SetNestedField(storage, value, id, key)\n\t}\n}", "func (_m *CognitoIdentityProviderAPI) UpdateUserPoolClientRequest(_a0 *cognitoidentityprovider.UpdateUserPoolClientInput) (*request.Request, *cognitoidentityprovider.UpdateUserPoolClientOutput) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.UpdateUserPoolClientInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *cognitoidentityprovider.UpdateUserPoolClientOutput\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.UpdateUserPoolClientInput) *cognitoidentityprovider.UpdateUserPoolClientOutput); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*cognitoidentityprovider.UpdateUserPoolClientOutput)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (m *MockHandler) Process(arg0 *models.Event) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Reduce\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *ContextHandler) Redirect(_a0 int, _a1 string) error {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(int, string) error); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}" ]
[ "0.6667897", "0.6231973", "0.60797775", "0.57886577", "0.569986", "0.5681185", "0.56517804", "0.5511168", "0.5505724", "0.54718584", "0.5459437", "0.54411364", "0.5426445", "0.54227555", "0.53494734", "0.53305525", "0.5329849", "0.52974755", "0.5293721", "0.52798426", "0.5278468", "0.5277542", "0.5270036", "0.5267819", "0.5260364", "0.5255634", "0.5243601", "0.5204087", "0.5143019", "0.5116627", "0.50955784", "0.5092072", "0.50895035", "0.5081889", "0.50554085", "0.5036192", "0.5035281", "0.5032884", "0.5016343", "0.50121355", "0.5000556", "0.49968404", "0.49944395", "0.49897835", "0.4983707", "0.4982347", "0.4973734", "0.49718735", "0.4969903", "0.49681813", "0.4966111", "0.4961435", "0.49507594", "0.49166408", "0.4915768", "0.49062186", "0.4905908", "0.48967415", "0.48850816", "0.48781398", "0.48764458", "0.48743317", "0.48720983", "0.48718542", "0.48616835", "0.4854794", "0.4854443", "0.4851919", "0.48396972", "0.4835866", "0.482856", "0.48220226", "0.4821392", "0.4815909", "0.4815004", "0.48110503", "0.48060468", "0.48050866", "0.48042396", "0.48036793", "0.47898656", "0.4788046", "0.47716558", "0.47661442", "0.47598702", "0.47529402", "0.47525987", "0.47472253", "0.47441193", "0.47384587", "0.4736488", "0.47363597", "0.4732991", "0.47310728", "0.4730277", "0.4727548", "0.47256276", "0.47251034", "0.4721083", "0.4719421" ]
0.7186859
0
OriginalVersion provides a mock function with given fields:
func (_m *MockAggregate) OriginalVersion() int { ret := _m.Called() var r0 int if rf, ok := ret.Get(0).(func() int); ok { r0 = rf() } else { r0 = ret.Get(0).(int) } return r0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newVersionCheckerMock(version string, tags []string) *VersionChecker {\n\n\tfixedAppVersion := fixVersion(version)\n\n\treturn &VersionChecker{\n\t\tfixedAppVersion: fixedAppVersion,\n\t\tversionSource: &versionCheckerMock{\n\t\t\ttags: tags,\n\t\t\tfixVersionStrFunc: fixVersion,\n\t\t\ttagFilterFunc: versionFilterFunc(fixedAppVersion),\n\t\t},\n\t}\n}", "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func (_m *MockAggregate) Version() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (_m *U2FDevice) Version() (string, error) {\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\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func MockKernelVersion(version string) (restore func()) {\n\told := KernelVersion\n\tKernelVersion = func() string { return version }\n\treturn func() {\n\t\tKernelVersion = old\n\t}\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (m *MockEventLogger) Version() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *Mock) Version() string {\n\treturn defaultMockVersion\n}", "func (m *MockShootClients) Version() *version.Info {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(*version.Info)\n\treturn ret0\n}", "func (m *MockFullNode) Version(arg0 context.Context) (types0.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\", arg0)\n\tret0, _ := ret[0].(types0.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *System) Version() (types.Text, error) {\n\tret := _m.Called()\n\n\tvar r0 types.Text\n\tif rf, ok := ret.Get(0).(func() types.Text); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(types.Text)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockRemotePeer) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMachine) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockqueueTaskInfo) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockqueueTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func (mock *PluginerMock) VersionCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockVersion.RLock()\n\tcalls = mock.calls.Version\n\tmock.lockVersion.RUnlock()\n\treturn calls\n}", "func (m *MockTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockVersion) GetVersion(keyName string) (string, error) {\n\targs := m.Called()\n\treturn args.String(0), args.Error(1)\n}", "func (m *MockEventLogger) VersionInitial() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VersionInitial\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (_m *ObjectVersioner) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error) {\n\tret := _m.Called(in, gv)\n\n\tvar r0 runtime.Object\n\tif rf, ok := ret.Get(0).(func(runtime.Object, runtime.GroupVersioner) runtime.Object); ok {\n\t\tr0 = rf(in, gv)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(runtime.Object)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(runtime.Object, runtime.GroupVersioner) error); ok {\n\t\tr1 = rf(in, gv)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockBackend) ProtocolVersion() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockKernelData) PatchVersion(kernelFullVersion string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PatchVersion\", kernelFullVersion)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Version) UpdateWarningVersion(_a0 string) (string, bool, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 bool\n\tif rf, ok := ret.Get(1).(func(string) bool); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Get(1).(bool)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(_a0)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockClient) PublicVersion() msp.Identity {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublicVersion\")\n\tret0, _ := ret[0].(msp.Identity)\n\treturn ret0\n}", "func (m *MockPacketHandler) GetVersion() protocol.VersionNumber {\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(protocol.VersionNumber)\n\treturn ret0\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func (_m *VersionInterface) GetVersion(ctx context.Context, r *admin.GetVersionRequest) (*admin.GetVersionResponse, error) {\n\tret := _m.Called(ctx, r)\n\n\tvar r0 *admin.GetVersionResponse\n\tif rf, ok := ret.Get(0).(func(context.Context, *admin.GetVersionRequest) *admin.GetVersionResponse); ok {\n\t\tr0 = rf(ctx, r)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*admin.GetVersionResponse)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *admin.GetVersionRequest) error); ok {\n\t\tr1 = rf(ctx, r)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestVersion(t *testing.T) {\n\t//fmt.Println(\"EliteProvision [\" + Version() + \"]\")\n}", "func TestGetVersion(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(false, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\n\ttrustAgentService.router.HandleFunc(\"/version\", errorHandler(getVersion())).Methods(\"GET\")\n\n\t// test request\n\trequest, err := http.NewRequest(\"GET\", \"/version\", nil)\n\tassert.NoError(err)\n\n\trecorder := httptest.NewRecorder()\n\tresponse := recorder.Result()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tassert.Equal(http.StatusOK, response.StatusCode)\n\tfmt.Printf(\"Version: %s\\n\", recorder.Body.String())\n\tassert.NotEmpty(recorder.Body.String())\n}", "func MockMinimalRelease(t *testing.T) *Release {\n\tvar r Release\n\terr := json.Unmarshal([]byte(`\n {\n \"release_id\": \"rr\",\n \"project_name\": \"project\",\n \"config_name\": \"config\",\n \"ami\": \"ami-123456\",\n \"subnets\": [\"subnet-1\"],\n \"user_data\": \"echo DATE\",\n \"services\": {\n \"web\": {\n \"instance_type\": \"t2.small\",\n \"security_groups\": [\"web-sg\"]\n }\n }\n }\n `), &r)\n\n\tassert.NoError(t, err)\n\tr.CreatedAt = to.Timep(time.Now())\n\n\treturn &r\n}", "func (_m *LambdaAPI) PublishVersionRequest(_a0 *lambda.PublishVersionInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func NewObjectVersioner(t mockConstructorTestingTNewObjectVersioner) *ObjectVersioner {\n\tmock := &ObjectVersioner{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (i *MockOtherDataItem) GetVersion() int {\n\treturn i.Version\n}", "func (_m *LambdaAPI) PublishVersion(_a0 *lambda.PublishVersionInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *CIPDClient) ResolveVersion(ctx context.Context, packageName string, version string) (common.Pin, error) {\n\tret := _m.Called(ctx, packageName, version)\n\n\tvar r0 common.Pin\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string) common.Pin); ok {\n\t\tr0 = rf(ctx, packageName, version)\n\t} else {\n\t\tr0 = ret.Get(0).(common.Pin)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {\n\t\tr1 = rf(ctx, packageName, version)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestGetVersion(t *testing.T) {\n\ttests := []struct {\n\t\tversion string\n\t\tcommit string\n\t\tdate string\n\t\texpect string\n\t\tshortOutput bool\n\t}{\n\t\t{\n\t\t\t\"a\",\n\t\t\t\"b\",\n\t\t\t\"c\",\n\t\t\t\"waver version: a from commit b built on c\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4\",\n\t\t\t\"5b1a61f9b58e3778986c99b1282840ce64329614\",\n\t\t\t\"Thu May 21 16:48:18 PDT 2020\",\n\t\t\t\"waver version: v0.12.4 from commit 5b1a61f9b58e3778986c99b1282840ce64329614 built on Thu May 21 16:48:18 PDT 2020\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"waver version: v0.12.4-rc5 from commit 5b1a61f9b58 built on 1590105848\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\ttrue,\n\t\t},\n\t}\n\n\t// save the current global variables so they can be set back after testing\n\toldVal := version\n\toldCommit := commit\n\toldDate := date\n\n\tfor _, test := range tests {\n\t\t// run through each test, should not be run in parallel.\n\t\tversion = test.version\n\t\tcommit = test.commit\n\t\tdate = test.date\n\n\t\t// build the new Cobra command and configure stdout and args\n\t\tv := Get(test.shortOutput)\n\n\t\t// assert output string matches expectations\n\t\tassert.Equal(t, test.expect, v)\n\t}\n\n\t// put the original build values back after tests have run\n\tversion = oldVal\n\tcommit = oldCommit\n\tdate = oldDate\n}", "func (m *MockKernelData) FullVersion(arg0 *v1.NodeList) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FullVersion\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func (m *MockFullNode) StateNetworkVersion(arg0 context.Context, arg1 types0.TipSetKey) (network.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateNetworkVersion\", arg0, arg1)\n\tret0, _ := ret[0].(network.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Version) VersionFormatter(_a0 string) (string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func ReleaseMock(opts *MockReleaseOptions) *release.Release {\n\tdate := time.Unix(242085845, 0).UTC()\n\n\tname := opts.Name\n\tif name == \"\" {\n\t\tname = \"testrelease-\" + string(rand.Intn(100))\n\t}\n\n\tversion := 1\n\tif opts.Version != 0 {\n\t\tversion = opts.Version\n\t}\n\n\tnamespace := opts.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\tch := opts.Chart\n\tif opts.Chart == nil {\n\t\tch = &chart.Chart{\n\t\t\tMetadata: &chart.Metadata{\n\t\t\t\tName: \"foo\",\n\t\t\t\tVersion: \"0.1.0-beta.1\",\n\t\t\t},\n\t\t\tTemplates: []*chart.File{\n\t\t\t\t{Name: \"templates/foo.tpl\", Data: []byte(MockManifest)},\n\t\t\t},\n\t\t}\n\t}\n\n\tscode := release.StatusDeployed\n\tif len(opts.Status) > 0 {\n\t\tscode = opts.Status\n\t}\n\n\treturn &release.Release{\n\t\tName: name,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: date,\n\t\t\tLastDeployed: date,\n\t\t\tStatus: scode,\n\t\t\tDescription: \"Release mock\",\n\t\t},\n\t\tChart: ch,\n\t\tConfig: map[string]interface{}{\"name\": \"value\"},\n\t\tVersion: version,\n\t\tNamespace: namespace,\n\t\tHooks: []*release.Hook{\n\t\t\t{\n\t\t\t\tName: \"pre-install-hook\",\n\t\t\t\tKind: \"Job\",\n\t\t\t\tPath: \"pre-install-hook.yaml\",\n\t\t\t\tManifest: MockHookTemplate,\n\t\t\t\tLastRun: date,\n\t\t\t\tEvents: []release.HookEvent{release.HookPreInstall},\n\t\t\t},\n\t\t},\n\t\tManifest: MockManifest,\n\t}\n}", "func (m *MockTask) SetVersion(version int64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetVersion\", version)\n}", "func (m *MockVersionInfoDao) GetVersionByDeployVersion(version, serviceID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByDeployVersion\", version, serviceID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *mockStore) GetCurrentVersion() (time.Time, error) {\n\treturn m.version, nil\n}", "func (_Ownable *OwnableCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Ownable.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestVersion(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.Register(\"test\", \"json\", NewTestHandler(\"json\", assert))\n\tassert.Nil(err)\n\t// Perform test requests.\n\treq := restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\tresp := ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"1.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"2\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"2.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"3.0\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"4.0.0-alpha\")\n}", "func (_m *Vcs) LatestRevision(file string) (string, error) {\n\tret := _m.Called(file)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(file)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(file)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (c MockDockerClient) ServerVersion(ctx context.Context) (dockertypes.Version, error) {\n\tif c.ServerVersionFn != nil {\n\t\tfmt.Println(\"[MockDockerClient] In \", utils.CurrentFunctionName())\n\t\treturn c.ServerVersionFn(ctx)\n\t}\n\tpanic(fmt.Sprintf(\"No function defined for: %s\", utils.CurrentFunctionName()))\n}", "func (_BaseFactory *BaseFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (r *MockRepoManager) mockNextRollRev(hash string) {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.skiaHead = hash\n}", "func (m *MockDeployedVersionFinder) OpenSourceVersion(ctx context.Context, installNamespace string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OpenSourceVersion\", ctx, installNamespace)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersionStorage(openStorage func() storage.ChunkStorage, closeStorage func(storage.ChunkStorage),\n\tresetStorage func(), t *testing.T) {\n\tassert := testifyAssert.New(t)\n\n\tvar s storage.ChunkStorage = nil\n\n\ttest := func(name string, run func()) {\n\t\tt.Logf(\"subtest: %s\", name)\n\t\tresetStorage()\n\t\ts = openStorage()\n\t\tdefer func() {\n\t\t\tif s != nil {\n\t\t\t\tcloseStorage(s)\n\t\t\t\ts = nil\n\t\t\t}\n\t\t}()\n\t\trun()\n\t}\n\n\treopen := func() {\n\t\tcloseStorage(s)\n\t\t// no reset\n\t\ts = openStorage()\n\t}\n\n\ttest(\"empty by default\", func() {\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(chunks)\n\t})\n\n\ttest(\"cannot get nonexistent latest\", func() {\n\t\t_, err := s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"cannot delete nonexistent version\", func() {\n\t\terr := s.DeleteLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"write single version corrolaries\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\t_, err = s.GetLatestVersion(72)\n\t\tassert.Error(err)\n\n\t\t_, err = s.GetLatestVersion(70)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"updating versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"updating versions with durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"delete subset of versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete subset of versions with durabilitiy\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\treopen()\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\treopen()\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete all versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\t\tassert.NoError(s.DeleteLatestVersion(72))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(versions)\n\n\t\t_, err = s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n}", "func (i *MockDataItem) GetVersion() int {\n\treturn i.Version\n}", "func (m *MockChefIngesterServer) GetVersion(arg0 context.Context, arg1 *VersionRequest) (*Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MockPrepareRelease(release *Release) {\n\trelease.SetDefaultRegionAccount(to.Strp(\"region\"), to.Strp(\"account\"))\n\trelease.SetDefaults()\n\trelease.SetUUID()\n}", "func (m *MockVersionInfoDao) GetVersionByEventID(eventID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByEventID\", eventID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_BaseLibraryFactory *BaseLibraryFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibraryFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (s *suite) Test_QueryNextVersion_happy_path(c *C) {\n\tserver := NewMockServer().WithBody(`1.0`).Start(c)\n\tdefer server.Stop()\n\n\tunit := NewRemoteInventory(server.URL, \"token\", \"\", \"\", false)\n\tversion, err := unit.QueryNextVersion(\"query-project\", \"name\", \"1.@\")\n\tserver.ExpectCalled(c, true, queryNextVersionURL)\n\tc.Assert(err, IsNil)\n\tc.Assert(version, Equals, \"1.0\")\n}", "func (_AggregatorV2V3Interface *AggregatorV2V3InterfaceCaller) Version(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _AggregatorV2V3Interface.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (c *cachestub) RecordVersion(token, version string) (*cache.Record, error) {\n\treturn &cache.Record{}, nil\n}", "func (_BaseLibrary *BaseLibraryCaller) VersionTimestamp(opts *bind.CallOpts, arg0 *big.Int) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"versionTimestamp\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestSetGetGoodArgsFull(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGetGoodArgsFull\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2017-11-21T10:29:49.816Z\"),\n\t[]byte(\"digest1\"),[]byte(\"E0nioxbCYD5AlzGWXDDDl0Gt5AAKv3ppKt4XMhE1rfo\"),\n\t[]byte(\"digest2\"),[]byte(\"xLrbWN5QJBJUAsdevfrxGlN3o0p8VZMnFFnV9iMll5o\"),\n\t[]byte(\"digest3\"),[]byte(\"THIS_IS_DIGEST_3\"),\n\t[]byte(\"digest4\"),[]byte(\"THIS_IS_DIGEST_4\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n\tresGet := stub.MockInvoke(\"1\", [][]byte{[]byte(\"get\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\")})\n\tif resGet.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(resGet.Message))\n\t\tt.FailNow()\n\t}\n}", "func Mock(fake string) func() {\n\tmutex.Lock()\n\tdefer mutex.Unlock()\n\torigin := backend\n\tbackend = fake\n\treturn func() { Mock(origin) }\n}", "func (m *MockDatasetClient) GetVersion(arg0 context.Context, arg1, arg2, arg3, arg4, arg5, arg6, arg7 string) (dataset.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\tret0, _ := ret[0].(dataset.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVersion) UpdateVersion(keyName, newVersion string) error {\n\targs := m.Called()\n\treturn args.Error(0)\n}", "func mock() (mainProto.Data, extraProto.Data) {\n\trandomStr := randStr(10)\n\tmain := mainProto.Data{\n\t\tUsername: randomStr,\n\t\tEmail: randomStr + \"@gmail.com\",\n\t\tPassword: randomStr,\n\t}\n\textra := extraProto.Data{\n\t\tUserID: randomStr,\n\t\tFirstName: randomStr,\n\t\tLastName: randomStr,\n\t\tGender: \"male\",\n\t\tBirthdayUTC: int64(864466669),\n\t}\n\treturn main, extra\n}", "func (_BaseContentFactory *BaseContentFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func GetMockAppVersionList() []models.Version {\n\tversions := []models.Version{\n\t\tmodels.Version{\n\t\t\tID: \"55ebd387-9c68-4137-a367-a12025cc2cdb\",\n\t\t\tVersion: \"1.0\",\n\t\t\tAppID: \"com.aerogear.mobile_app_one\",\n\t\t\tDisabledMessage: \"Please contact an administrator\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 1,\n\t\t\tNumOfAppLaunches: 2,\n\t\t},\n\t\tmodels.Version{\n\t\t\tID: \"59ebd387-9c68-4137-a367-a12025cc1cdb\",\n\t\t\tVersion: \"1.1\",\n\t\t\tAppID: \"com.aerogear.mobile_app_one\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 0,\n\t\t\tNumOfAppLaunches: 0,\n\t\t},\n\t\tmodels.Version{\n\t\t\tID: \"59dbd387-9c68-4137-a367-a12025cc2cdb\",\n\t\t\tVersion: \"1.0\",\n\t\t\tAppID: \"com.aerogear.mobile_app_two\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 0,\n\t\t\tNumOfAppLaunches: 0,\n\t\t},\n\t}\n\n\treturn versions\n}", "func (_m *Version) GetHumanVersion() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func TestHandleGetVersion(t *testing.T) {\n\tsv := ServerVersion{Version:\"v1\", IP:\"127.0.0.1\", Port:8080}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/version\", sv.handGetVersion)\n\n\twriter := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/version\", nil)\n\tmux.ServeHTTP(writer, req)\n\n\tfmt.Println(writer.Body.String())\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWalletFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockDatasetClient) GetVersion(ctx context.Context, userAuthToken, serviceAuthToken, downloadServiceToken, collectionID, datasetID, edition, version string) (dataset.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", ctx, userAuthToken, serviceAuthToken, downloadServiceToken, collectionID, datasetID, edition, version)\n\tret0, _ := ret[0].(dataset.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCredHub) GetLatestVersion(arg0 string) (credentials.Credential, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLatestVersion\", arg0)\n\tret0, _ := ret[0].(credentials.Credential)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_MetaObject *MetaObjectCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _MetaObject.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockResponseHandler) NotModified() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"NotModified\")\n}", "func (_m *RepositoryMock) Update(args db_models.DbDTO) error {\n\tret := _m.Called(args)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(db_models.DbDTO) error); ok {\n\t\tr0 = rf(args)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func Test12(t *testing.T) {\n\tcustommutatingBaseCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tcustommutatingBaseCollection.Spec.Version = \"1.2.3\"\n\tnewCollection.Spec.Version = \"1.2.4\"\n\tcustommutatingBaseCollection.Spec.Versions[0].Version = \"1.2.4\"\n\tnewCollection.Spec.Versions[0].Version = \"1.2.4\"\n\n\terr := processUpdate(custommutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tDesiredState: \"active\",\n\t\tRepositoryUrl: \"https://github.com/some/collection/kabanero-index.yaml\",\n\t\tVersion: \"1.2.4\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n\n\tif newCollection.Spec.RepositoryUrl != \"https://github.com/some/collection/kabanero-index.yaml\" {\n\t\tt.Fatal(\"New collection.Spec.RepositoryUrl values do not match expected value of https://github.com/some/collection/kabanero-index.yaml. RepositoryUrl found: \", newCollection.Spec.RepositoryUrl)\n\t}\n\tif newCollection.Spec.Version != \"1.2.4\" {\n\t\tt.Fatal(\"New collection.Spec.Version values do not match expected value of 1.2.3. Version found: \", newCollection.Spec.Version)\n\t}\n\tif newCollection.Spec.DesiredState != \"active\" {\n\t\tt.Fatal(\"New collection.Spec.DesiredState values do not match expected value of active. DesiredStateme found: \", newCollection.Spec.DesiredState)\n\t}\n}", "func (_Upgradeable *UpgradeableCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Upgradeable.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func (m *MockChefIngesterClient) GetVersion(ctx context.Context, in *VersionRequest, opts ...grpc.CallOption) (*Version, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetVersion\", varargs...)\n\tret0, _ := ret[0].(*Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestDaemon_Version(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\tv, err := d.Version(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif v != testVersion {\n\t\tt.Fatalf(\"Expected %v but got %v\", testVersion, v)\n\t}\n}", "func (_m *ChannelStore) Restore(channelID string, timestamp int64) error {\n\tret := _m.Called(channelID, timestamp)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int64) error); ok {\n\t\tr0 = rf(channelID, timestamp)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockLinkServiceServer) GetOriginalFromShorten(arg0 context.Context, arg1 *links.GetOriginalFromShortenReq) (*links.GetOriginalFromShortenRes, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOriginalFromShorten\", arg0, arg1)\n\tret0, _ := ret[0].(*links.GetOriginalFromShortenRes)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockJournal) Restore(entry ...Entry) (Index, error) {\n\tret := _m.Called(entry)\n\n\tvar r0 Index\n\tif rf, ok := ret.Get(0).(func(...Entry) Index); ok {\n\t\tr0 = rf(entry...)\n\t} else {\n\t\tr0 = ret.Get(0).(Index)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(...Entry) error); ok {\n\t\tr1 = rf(entry...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (machine *VirtualMachine_Spec) OriginalVersion() string {\n\treturn GroupVersion.Version\n}", "func MockRoundUpdate(round uint64, p *user.Provisioners) RoundUpdate {\n\tprovisioners := p\n\tif p == nil {\n\t\tprovisioners, _ = MockProvisioners(1)\n\t}\n\n\tseed, _ := crypto.RandEntropy(33)\n\thash, _ := crypto.RandEntropy(32)\n\n\treturn RoundUpdate{\n\t\tRound: round,\n\t\tP: *provisioners,\n\t\tSeed: seed,\n\t\tHash: hash,\n\t\tLastCertificate: block.EmptyCertificate(),\n\t}\n}", "func (m *MockProductCatalog) UpdateVersionForEditor(arg0 context.Context, arg1 db.UpdateVersionForEditorParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateVersionForEditor\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_BaseGroupFactory *BaseGroupFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseGroupFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_m *Client) UpdateBuild(_a0 context.Context, _a1 build.UpdateBuildArgs) (*build.Build, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *build.Build\n\tif rf, ok := ret.Get(0).(func(context.Context, build.UpdateBuildArgs) *build.Build); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*build.Build)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.UpdateBuildArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_Accessible *AccessibleCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Accessible.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (r *MockRepoManager) mockUpdate() {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.updateCount++\n}", "func (_BaseContentFactoryExt *BaseContentFactoryExtCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactoryExt.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func mockEdit() {\n\tEdit = func(path string, filedata []byte) ([]byte, error) {\n\t\treturn filedata, nil\n\t}\n}", "func buildMockVulnClientKey(version string, os string, packages []string) string {\n\tpkgs := strings.Join(packages, \"\")\n\treturn strings.Join([]string{version, os, pkgs}, \"/\")\n}", "func TestSetupReplaceMock(t *testing.T) {\n\tt.SkipNow()\n\tstudent, mocks, err := MockCluster(false, nil, t)\n\tif err != nil {\n\t\tt.Error(\"Couldn't set up mock cluster\", err)\n\t}\n\n\t// Create a new impl for an rpc function\n\tdenyVote := func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\treturn &RequestVoteReply{Term: req.Term, VoteGranted: false}, nil\n\t}\n\n\t// replace the existing impl\n\tmocks[0].RequestVote = denyVote\n\tmocks[1].RequestVote = denyVote\n\n\tmocks[0].JoinCluster()\n\tmocks[1].JoinCluster()\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 4)\n\n\tt.Log(\"Student node is:\", student.State)\n\n\tif student.State != CANDIDATE_STATE {\n\t\tt.Error(\"student state was not candidate, was:\", student.State)\n\t}\n\n\t// test as part of an rpc function\n\tmocks[0].RequestVote = func(ctx context.Context, req *RequestVoteRequest) (*RequestVoteReply, error) {\n\t\tt.Logf(\"Mock 0 recieved request vote: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\tif req.GetLastLogIndex() != 0 || req.GetLastLogTerm() != 0 {\n\t\t\tt.Errorf(\"Student node failed to request vote correctly: last_idx: %v term: %v\", req.GetLastLogIndex(), req.GetLastLogTerm())\n\t\t}\n\n\t\tif term := student.GetCurrentTerm(); req.GetTerm() != term {\n\t\t\tt.Errorf(\"Student node sent the wrong term: (sent %v, expecting %v)\", req.GetTerm(), term)\n\t\t}\n\t\treturn denyVote(ctx, req)\n\t}\n\n\ttime.Sleep(DefaultConfig().ElectionTimeout * 5)\n}", "func (_BaseLibrary *BaseLibraryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_m *mockStateBuilder) applyEvents(domainID string, requestID string, execution shared.WorkflowExecution, _a3 []*shared.HistoryEvent,\n\tnewRunHistory []*shared.HistoryEvent, eventStoreVersion, newRunEventStoreVersion int32, newRunNDC bool) (*shared.HistoryEvent, *decisionInfo, mutableState, error) {\n\n\tret := _m.Called(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\n\tvar r0 *shared.HistoryEvent\n\tif rf, ok := ret.Get(0).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *shared.HistoryEvent); ok {\n\t\tr0 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*shared.HistoryEvent)\n\t\t}\n\t}\n\n\tvar r1 *decisionInfo\n\tif rf, ok := ret.Get(1).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *decisionInfo); ok {\n\t\tr1 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*decisionInfo)\n\t\t}\n\t}\n\n\tvar r2 mutableState\n\tif rf, ok := ret.Get(2).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) mutableState); ok {\n\t\tr2 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(mutableState)\n\t\t}\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) error); ok {\n\t\tr3 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (_m *Remote) Hook(r *http.Request) (*model.Repo, *model.Build, error) {\n\tret := _m.Called(r)\n\n\tvar r0 *model.Repo\n\tif rf, ok := ret.Get(0).(func(*http.Request) *model.Repo); ok {\n\t\tr0 = rf(r)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.Repo)\n\t\t}\n\t}\n\n\tvar r1 *model.Build\n\tif rf, ok := ret.Get(1).(func(*http.Request) *model.Build); ok {\n\t\tr1 = rf(r)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*model.Build)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(*http.Request) error); ok {\n\t\tr2 = rf(r)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func TestVersion(t *testing.T) {\n\tfor _, v := range versionTests {\n\t\tp, e := model.ParseVersion(v[0])\n\t\tassert.Nil(t, e, \"Should have parsed %s\", v)\n\t\tassert.Equal(t, p.String(), v[1], \"Should be equal %s==%s\", p.String(), v)\n\t}\n}", "func (_Editable *EditableCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Editable.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}" ]
[ "0.6774614", "0.6536822", "0.65328676", "0.65046424", "0.6437681", "0.6410609", "0.61703193", "0.61611354", "0.6090569", "0.60708857", "0.60435575", "0.6039088", "0.599811", "0.59314656", "0.59307015", "0.59270644", "0.5898324", "0.57774776", "0.57339287", "0.56818753", "0.5626438", "0.5597983", "0.559141", "0.55880386", "0.5568152", "0.5565807", "0.55470574", "0.5545606", "0.5532237", "0.55229336", "0.5506906", "0.54765546", "0.546036", "0.54407144", "0.543755", "0.54216254", "0.5397673", "0.53606933", "0.5353989", "0.53462374", "0.5311723", "0.5296098", "0.52900195", "0.5288909", "0.52825594", "0.5279029", "0.5276143", "0.5242869", "0.5242545", "0.5237863", "0.5234978", "0.5222144", "0.52115", "0.51880693", "0.5182852", "0.5175039", "0.516738", "0.51555365", "0.5155522", "0.51426023", "0.513578", "0.5127489", "0.51254696", "0.51051223", "0.51026696", "0.5101681", "0.50923973", "0.5091775", "0.50881034", "0.50814205", "0.5075931", "0.50724614", "0.50683606", "0.50680304", "0.5065555", "0.5055188", "0.50529176", "0.5045604", "0.5043328", "0.50366735", "0.5026236", "0.50259393", "0.50216496", "0.5010944", "0.5000109", "0.4999458", "0.49931905", "0.49916023", "0.49846625", "0.49840975", "0.49798793", "0.4978787", "0.4977513", "0.4975501", "0.49703482", "0.49687165", "0.49679998", "0.49678287", "0.49664646", "0.49627715" ]
0.7191302
0
StoreEvent provides a mock function with given fields: _a0
func (_m *MockAggregate) StoreEvent(_a0 EventData) { _m.Called(_a0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockEventRepository) Store(arg0 *sweeper.Event) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func MockConsensusEvent(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, i ...int) consensus.Event {\n\taev := MockAgreementEvent(hash, round, step, keys, p, i...)\n\thdr := aev.Header\n\n\tbuf := new(bytes.Buffer)\n\t_ = Marshal(buf, *aev)\n\n\treturn consensus.Event{\n\t\tHeader: hdr,\n\t\tPayload: *buf,\n\t}\n}", "func mockMapStore(storage map[string]interface{}) ResultStoreFn {\n\treturn func(id string, key string, value interface{}) {\n\t\tutil.SetNestedField(storage, value, id, key)\n\t}\n}", "func (_m *Repository) Store(_a0 *account.Account) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*account.Account) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *DB) SaveEvent(topic string, eventData interface{}, inTx func() error) error {\n\tret := _m.Called(topic, eventData, inTx)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, interface{}, func() error) error); ok {\n\t\tr0 = rf(topic, eventData, inTx)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func mockNoopStore(id string, key string, value interface{}) {}", "func encodeMockEvent(e models.Event) ([]byte, error) {\n\tbyteBuffer, err := cbor.Marshal(e)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn byteBuffer, nil\n}", "func (_m *mockStateBuilder) applyEvents(domainID string, requestID string, execution shared.WorkflowExecution, _a3 []*shared.HistoryEvent,\n\tnewRunHistory []*shared.HistoryEvent, eventStoreVersion, newRunEventStoreVersion int32, newRunNDC bool) (*shared.HistoryEvent, *decisionInfo, mutableState, error) {\n\n\tret := _m.Called(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\n\tvar r0 *shared.HistoryEvent\n\tif rf, ok := ret.Get(0).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *shared.HistoryEvent); ok {\n\t\tr0 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*shared.HistoryEvent)\n\t\t}\n\t}\n\n\tvar r1 *decisionInfo\n\tif rf, ok := ret.Get(1).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *decisionInfo); ok {\n\t\tr1 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*decisionInfo)\n\t\t}\n\t}\n\n\tvar r2 mutableState\n\tif rf, ok := ret.Get(2).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) mutableState); ok {\n\t\tr2 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(mutableState)\n\t\t}\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) error); ok {\n\t\tr3 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func TestEventStore(t *testing.T) {\n\tstartEventstore(t)\n\trabbitEventStore, err := NewRabbitEventStoreClient(&rabbit.CreateClientOption{URL: \"amqp://guest:guest@localhost:5672/\", Queue: \"EventStore\", TimeoutRequest: time.Second})\n\tassertNilError(t, err)\n\n\tid := rabbit.RandomID()\n\tresult, err := rabbitEventStore.RetrieveEvents(&framework.RetrieveEventsOption{AggregateID: id})\n\n\n\tassertNilError(t, err)\n\tif len(result) == 0 {\n\t\tt.Fatal(\"expecting return `result` to be more than 1\")\n\t}\n\n\tif result[0].AggregateID != id {\n\t\tt.Fatalf(\"expecting arrived event an event[0] to have an aggregate id of %s instead got %s\", id, result[0].AggregateID)\n\t}\n\n\tevent, err := rabbitEventStore.CreateEvent(framework.Event{AggregateID: rabbit.RandomID(), AggregateType: 2})\n\tif event.ID == \"\" {\n\t\tt.Fatal(\"expecting `ID` field to exists instead got `nil`\")\n\t}\n\n\tsuccess, err := rabbitEventStore.CreateSnapshot(&framework.CreateSnapshotOption{AggregateID: rabbit.RandomID(), AggregateVersion: 1, AggregateType: 100})\n\tif success != true {\n\t\tt.Fatalf(\"expecting `success` to be `true` but got %v\", success)\n\t}\n\n\tsnapshot, err := rabbitEventStore.RetrieveSnapshot(&framework.RetrieveSnapshotOption{AggregateType: 100, AggregateID: id})\n\tif snapshot.AggregateID != id {\n\t\tt.Fatalf(\"expecting aggregate id to equal to %q instead got %q\", id, snapshot.AggregateID)\n\t}\n}", "func TestStore(t *testing.T) {\n\tmockOrder := struct {\n\t\tOrigin [2]string `json:\"origin\"`\n\t\tDestination [2]string `json:\"destination\"`\n\t}{\n\t\tOrigin: [2]string{\"13.742310\", \"100.631418\"},\n\t\tDestination: [2]string{\"13.754179\", \"100.630377\"},\n\t}\n\n\tmockUCase := new(mocks.Usecase)\n\n\tj, err := json.Marshal(mockOrder)\n\tassert.NoError(t, err)\n\n\tmockUCase.On(\"Store\", mock.Anything, mock.AnythingOfType(\"*models.Order\")).Return(nil)\n\n\te := echo.New()\n\treq, err := http.NewRequest(echo.POST, \"/orders\", strings.NewReader(string(j)))\n\tassert.NoError(t, err)\n\treq.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"/orders\")\n\n\thandler := orderHttp.OrderHandler{\n\t\tOUsecase: mockUCase,\n\t}\n\terr = handler.Store(c)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, http.StatusOK, rec.Code)\n\tassert.JSONEq(t, `{\"id\":\"00000000-0000-0000-0000-000000000000\",\"status\":\"UNASSIGNED\",\"distance\":0}`, rec.Body.String())\n\tmockUCase.AssertExpectations(t)\n}", "func (_m *Repository) Store(ctx context.Context, _a1 *models.Host) error {\n\tret := _m.Called(ctx, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.Host) error); ok {\n\t\tr0 = rf(ctx, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockBookingStorage) Create(_a0 interface{}) {\n\t_m.Called(_a0)\n}", "func (_m *MockStorage) Add(user string, timeStamp int64, expireTime int64) error {\n\tret := _m.Called(user, timeStamp, expireTime)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int64, int64) error); ok {\n\t\tr0 = rf(user, timeStamp, expireTime)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (s *MockEventStore) Put(c context.Context, envelope interface{}) error {\n\treturn nil\n}", "func (_m *Index) AddOrUpdate(_a0 index.Entry) (storage.Event, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 storage.Event\n\tif rf, ok := ret.Get(0).(func(index.Entry) storage.Event); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(storage.Event)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(index.Entry) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func makeTestEvent(e *Event) *Event {\n\tif e.UserID == 0 {\n\t\te.UserID = 1\n\t}\n\te.Name = \"foo\"\n\te.URL = \"test\"\n\te.Source = \"WEB\"\n\te.Timestamp = e.Timestamp.Add(time.Minute * time.Duration(rand.Intn(60*12)))\n\treturn e\n}", "func (_m *IRepository) Store(name string, age int) error {\n\tret := _m.Called(name, age)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int) error); ok {\n\t\tr0 = rf(name, age)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func testEvent() common.MapStr {\n\tevent := common.MapStr{}\n\tevent[\"@timestamp\"] = common.Time(time.Now())\n\tevent[\"type\"] = \"test\"\n\tevent[\"src\"] = &common.Endpoint{}\n\tevent[\"dst\"] = &common.Endpoint{}\n\treturn event\n}", "func MockEvents() []optic.Event {\n\tevents := make([]optic.Event, 0)\n\tevents = append(events, TestRaw([]byte(\"raw\")))\n\tevents = append(events, TestMetric(1.0))\n\tevents = append(events, TestLogLine(\"logline\"))\n\treturn events\n}", "func (m *MockHandler) AddEvent(ctx context.Context, clusterID strfmt.UUID, hostID *strfmt.UUID, severity, msg string, eventTime time.Time, props ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, clusterID, hostID, severity, msg, eventTime}\n\tfor _, a := range props {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"AddEvent\", varargs...)\n}", "func (_m *EventProviderMock) GetStorageEvents(meta *types.Metadata, blockHash types.Hash) (*types.StorageDataRaw, error) {\n\tret := _m.Called(meta, blockHash)\n\n\tvar r0 *types.StorageDataRaw\n\tif rf, ok := ret.Get(0).(func(*types.Metadata, types.Hash) *types.StorageDataRaw); ok {\n\t\tr0 = rf(meta, blockHash)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*types.StorageDataRaw)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*types.Metadata, types.Hash) error); ok {\n\t\tr1 = rf(meta, blockHash)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockAggregate) Apply(_a0 Event) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(Event) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func MockWire(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, i ...int) *bytes.Buffer {\n\tev := MockAgreementEvent(hash, round, step, keys, p, i...)\n\n\tbuf := new(bytes.Buffer)\n\tif err := header.Marshal(buf, ev.Header); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := Marshal(buf, *ev); err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf\n}", "func TestEvents(t *testing.T) {\n\tti := tInfo{}\n\tAssertOk(t, ti.setup(t), \"failed to setup test\")\n\tdefer ti.teardown()\n\n\t// uuid to make each source unique\n\tcomponentID := uuid.NewV4().String()\n\n\t// create recorder events directory\n\trecorderEventsDir, err := ioutil.TempDir(\"\", \"\")\n\tAssertOk(t, err, \"failed to create recorder events directory\")\n\tdefer os.RemoveAll(recorderEventsDir)\n\n\t// create recorder\n\tevtsRecorder, err := recorder.NewRecorder(&recorder.Config{\n\t\tComponent: componentID,\n\t\tEvtsProxyURL: ti.evtProxyServices.EvtsProxy.RPCServer.GetListenURL(),\n\t\tBackupDir: recorderEventsDir}, ti.logger)\n\tAssertOk(t, err, \"failed to create events recorder\")\n\tdefer evtsRecorder.Close()\n\n\t// send events (recorder -> proxy -> dispatcher -> writer -> evtsmgr -> elastic)\n\tevtsRecorder.Event(eventtypes.SERVICE_STARTED, \"test event - 1\", nil)\n\tevtsRecorder.Event(eventtypes.SERVICE_RUNNING, \"test event - 2\", nil)\n\n\ttime.Sleep(1 * time.Second)\n\n\t// verify that it has reached elasticsearch; these are the first occurrences of an event\n\t// so it should have reached elasticsearch without being de-duped.\n\tquery := es.NewBoolQuery().Must(es.NewMatchQuery(\"source.component\", componentID),\n\t\tes.NewTermQuery(\"type.keyword\", eventtypes.SERVICE_STARTED.String()))\n\tti.assertElasticUniqueEvents(t, query, true, 1, \"4s\") // unique == 1\n\tti.assertElasticTotalEvents(t, query, true, 1, \"4s\") // total == 1\n\tquery = es.NewBoolQuery().Must(es.NewMatchQuery(\"source.component\", componentID),\n\t\tes.NewMatchQuery(\"message\", \"test event -2\").Operator(\"and\"))\n\tti.assertElasticUniqueEvents(t, query, true, 1, \"4s\") // unique == 1\n\tti.assertElasticTotalEvents(t, query, true, 1, \"4s\") // total == 1\n\n\t// send duplicates and check whether they're compressed\n\tnumDuplicates := 25\n\tfor i := 0; i < numDuplicates; i++ {\n\t\tevtsRecorder.Event(eventtypes.SERVICE_STARTED, \"test dup event - 1\", nil)\n\t\tevtsRecorder.Event(eventtypes.SERVICE_RUNNING, \"test dup event - 2\", nil)\n\t}\n\n\t// ensure the de-duped events reached elasticsearch\n\t// test duplicate event - 1\n\tquery = es.NewBoolQuery().Must(es.NewMatchQuery(\"source.component\", componentID),\n\t\tes.NewMatchQuery(\"message\", \"test dup event - 1\").Operator(\"and\"))\n\tti.assertElasticUniqueEvents(t, query, true, 1, \"4s\") // unique == 1\n\tti.assertElasticTotalEvents(t, query, true, numDuplicates, \"2s\") // total == numDuplicates\n\n\t// test duplicate event - 2\n\tquery = es.NewBoolQuery().Must(es.NewMatchQuery(\"source.component\", componentID),\n\t\tes.NewMatchQuery(\"message\", \"test dup event - 2\").Operator(\"and\"))\n\tti.assertElasticUniqueEvents(t, query, true, 1, \"4s\") // unique == 1\n\tti.assertElasticTotalEvents(t, query, true, numDuplicates, \"2s\") // total == numDuplicates\n\n\t// create test NIC object\n\ttestNIC := policygen.CreateSmartNIC(\"00-14-22-01-23-45\",\n\t\tcluster.DistributedServiceCardStatus_ADMITTED.String(),\n\t\t\"esx-1\",\n\t\t&cluster.DSCCondition{\n\t\t\tType: cluster.DSCCondition_HEALTHY.String(),\n\t\t\tStatus: cluster.ConditionStatus_FALSE.String(),\n\t\t})\n\n\t// record events with reference object\n\tfor i := 0; i < numDuplicates; i++ {\n\t\tevtsRecorder.Event(eventtypes.SERVICE_STARTED, \"test dup event - 1\", testNIC)\n\t\tevtsRecorder.Event(eventtypes.SERVICE_RUNNING, \"test dup event - 2\", testNIC)\n\t}\n\n\t// query by kind\n\tqueryByKind := es.NewTermQuery(\"object-ref.kind.keyword\", testNIC.GetKind())\n\tti.assertElasticUniqueEvents(t, queryByKind, true, 2, \"4s\") // unique == 2 (eventType1 and eventType2)\n\tti.assertElasticTotalEvents(t, queryByKind, true, numDuplicates*2, \"4s\") // total == numDuplicates\n}", "func (mmSaveOrderWithExpiration *mStoreMockSaveOrderWithExpiration) Set(f func(order pb.Order, expiration time.Duration) (err error)) *StoreMock {\n\tif mmSaveOrderWithExpiration.defaultExpectation != nil {\n\t\tmmSaveOrderWithExpiration.mock.t.Fatalf(\"Default expectation is already set for the Store.SaveOrderWithExpiration method\")\n\t}\n\n\tif len(mmSaveOrderWithExpiration.expectations) > 0 {\n\t\tmmSaveOrderWithExpiration.mock.t.Fatalf(\"Some expectations are already set for the Store.SaveOrderWithExpiration method\")\n\t}\n\n\tmmSaveOrderWithExpiration.mock.funcSaveOrderWithExpiration = f\n\treturn mmSaveOrderWithExpiration.mock\n}", "func (m *MockHandler) EventQuery() (*models.SearchQuery, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EventQuery\")\n\tret0, _ := ret[0].(*models.SearchQuery)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestEventMarshaling(t *testing.T) {\n\tassert := asserts.NewTesting(t, asserts.FailStop)\n\n\tevtIn, err := mesh.NewEvent(\"test\")\n\tassert.NoError(err)\n\tdata, err := json.Marshal(evtIn)\n\tassert.NoError(err)\n\n\tevtOut := mesh.Event{}\n\terr = json.Unmarshal(data, &evtOut)\n\tassert.NoError(err)\n\tassert.Equal(evtOut, evtIn)\n\n\tplEvtA, err := mesh.NewEvent(\"payload-a\")\n\tassert.NoError(err)\n\tplEvtB, err := mesh.NewEvent(\"payload-b\")\n\tassert.NoError(err)\n\tplEvtC, err := mesh.NewEvent(\"payload-c\")\n\tassert.NoError(err)\n\n\tevtIn, err = mesh.NewEvent(\"test\", plEvtA, plEvtB, plEvtC)\n\tassert.NoError(err)\n\tdata, err = json.Marshal(evtIn)\n\tassert.NoError(err)\n\n\tevtOut = mesh.Event{}\n\terr = json.Unmarshal(data, &evtOut)\n\tassert.NoError(err)\n\tassert.Equal(evtOut, evtIn)\n\tpl := []mesh.Event{}\n\terr = evtOut.Payload(&pl)\n\tassert.NoError(err)\n\tassert.Equal(pl[0], plEvtA)\n\tassert.Equal(pl[1], plEvtB)\n\tassert.Equal(pl[2], plEvtC)\n}", "func (m *MockEventBus) DispatchEvent(arg0 members.Event) error {\n\tret := m.ctrl.Call(m, \"DispatchEvent\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestEventPayload(t *testing.T) {\n\tassert := asserts.NewTesting(t, asserts.FailStop)\n\n\tpayloadIn := []string{\"a\", \"b\", \"c\"}\n\tpayloadOutA := []string{}\n\tevt, err := mesh.NewEvent(\"test\", payloadIn)\n\tassert.NoError(err)\n\tassert.Equal(evt.Topic(), \"test\")\n\tassert.True(evt.HasPayload())\n\terr = evt.Payload(&payloadOutA)\n\tassert.NoError(err)\n\tassert.Length(payloadOutA, 3)\n\tassert.Equal(payloadOutA, payloadIn)\n\n\tpayloadOutB := []int{}\n\tevt, err = mesh.NewEvent(\"test\", 1, 2, 3, 4, 5)\n\tassert.NoError(err)\n\tassert.Equal(evt.Topic(), \"test\")\n\tassert.True(evt.HasPayload())\n\terr = evt.Payload(&payloadOutB)\n\tassert.NoError(err)\n\tassert.Length(payloadOutB, 5)\n\tassert.Equal(payloadOutB, []int{1, 2, 3, 4, 5})\n}", "func (m *mRecentIndexStorageMockAddObject) Set(f func(p context.Context, p1 insolar.ID)) *RecentIndexStorageMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.AddObjectFunc = f\n\treturn m.mock\n}", "func (_m *StoreClient) Store(o interfaces.StoredObject) (string, error) {\n\tret := _m.Called(o)\n\n\tvar r0 string\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(interfaces.StoredObject) (string, error)); ok {\n\t\treturn rf(o)\n\t}\n\tif rf, ok := ret.Get(0).(func(interfaces.StoredObject) string); ok {\n\t\tr0 = rf(o)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tif rf, ok := ret.Get(1).(func(interfaces.StoredObject) error); ok {\n\t\tr1 = rf(o)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Service) Add(_a0 []byte) apifarm.Query {\n\tret := _m.Called(_a0)\n\n\tvar r0 apifarm.Query\n\tif rf, ok := ret.Get(0).(func([]byte) apifarm.Query); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(apifarm.Query)\n\t}\n\n\treturn r0\n}", "func (_m *mockContext) SetState(_a0 map[string][]byte) ([]string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(map[string][]byte) []string); ok {\n\t\tr0 = rf(_a0)\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\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(map[string][]byte) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *RunInterface) CreateLastEvent() (int, error) {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockSender) AddEvent(ctx context.Context, clusterID strfmt.UUID, hostID *strfmt.UUID, severity, msg string, eventTime time.Time, props ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, clusterID, hostID, severity, msg, eventTime}\n\tfor _, a := range props {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"AddEvent\", varargs...)\n}", "func mockOlt() *fields {\n\tdh := newMockDeviceHandler()\n\tnewOlt := &fields{}\n\tnewOlt.deviceHandlers = map[string]*DeviceHandler{}\n\tnewOlt.deviceHandlers[dh.device.Id] = dh\n\treturn newOlt\n}", "func (_m *RunInterface) CreateEvent(event protocol.Event) (int, error) {\n\tret := _m.Called(event)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(protocol.Event) int); ok {\n\t\tr0 = rf(event)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(protocol.Event) error); ok {\n\t\tr1 = rf(event)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockBookingStorage) Update(_a0 interface{}) {\n\t_m.Called(_a0)\n}", "func (client *MockClient) Event(object runtime.Object, eventType string, reason string, message string) {\n\tclient.createEvent(buildEvent(object, eventType, reason, message))\n}", "func (_m *mockDbOperation) StoreMetadata(metadata db.Metadata, dir string) error {\n\tret := _m.Called(metadata, dir)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(db.Metadata, string) error); ok {\n\t\tr0 = rf(metadata, dir)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockStorageMetrics) MeasurePersistEvent(arg0 func() (*spec.Event, error)) (*spec.Event, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MeasurePersistEvent\", arg0)\n\tret0, _ := ret[0].(*spec.Event)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockMapInterface) Add(_a0 collector.Interface) {\n\t_m.Called(_a0)\n}", "func (m *MockConsensus) PushEvent(arg0 hash.Event) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PushEvent\", arg0)\n}", "func (m *MockMembers) DispatchEvent(arg0 members.Event) error {\n\tret := m.ctrl.Call(m, \"DispatchEvent\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func newMockEncodeDataFunc(mockStore *mock.NodeStore) func(chunk Chunk) []byte {\n\treturn func(chunk Chunk) []byte {\n\t\tif err := mockStore.Put(chunk.Address(), encodeData(chunk)); err != nil {\n\t\t\tlog.Error(fmt.Sprintf(\"%T: Chunk %v put: %v\", mockStore, chunk.Address().Log(), err))\n\t\t}\n\t\treturn chunk.Address()[:]\n\t}\n}", "func (_m *MockENotifyingList) Set(_a0 int, _a1 interface{}) interface{} {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 interface{}\n\tif rf, ok := ret.Get(0).(func(int, interface{}) interface{}); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(interface{})\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestHandler_OK(t *testing.T) {\n\tnow, _ := clock.ParseRFC3339(\"2000-01-01T00:00:00Z\")\n\tinputMachineID := \"AAAAAAAA-A00A-1234-1234-5864377B4831\"\n\ttimeProvider := clock.FrozenTimeProvider{\n\t\tCurrent: now,\n\t}\n\tvar request = events.APIGatewayProxyRequest{\n\t\tHTTPMethod: \"POST\",\n\t\tResource: \"/preflight/{machine_id}\",\n\t\tPathParameters: map[string]string{\"machine_id\": inputMachineID},\n\t\tHeaders: map[string]string{\"Content-Type\": \"application/json\"},\n\t\tBody: `{\n\t\"os_build\":\"20D5029f\",\n\t\"santa_version\":\"2021.1\",\n\t\"hostname\":\"my-awesome-macbook-pro.attlocal.net\",\n\t\"transitive_rule_count\":0,\n\t\"os_version\":\"11.2\",\n\t\"certificate_rule_count\":2,\n\t\"client_mode\":\"MONITOR\",\n\t\"serial_num\":\"C02123456789\",\n\t\"binary_rule_count\":3,\n\t\"primary_user\":\"nobody\",\n\t\"compiler_rule_count\":0\n}`,\n\t}\n\tmockedConfigurationFetcher := &MockDynamodb{}\n\n\tconfig := machineconfiguration.MachineConfiguration{\n\t\tClientMode: types.Lockdown,\n\t\tBatchSize: 37,\n\t\tUploadLogsURL: \"/aaa\",\n\t\tEnableBundles: true,\n\t\tAllowedPathRegex: \"\",\n\t\tCleanSync: false,\n\t}\n\n\treturnedConfig, err := attributevalue.MarshalMap(config)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tmockedConfigurationFetcher.On(\"GetItem\", mock.Anything, mock.Anything).Return(&awsdynamodb.GetItemOutput{\n\t\tItem: returnedConfig,\n\t}, nil)\n\n\tmockedStateTracking := &MockDynamodb{}\n\tmockedStateTracking.On(\"GetItem\", mock.Anything, mock.Anything).Return(&awsdynamodb.GetItemOutput{\n\t\tItem: nil,\n\t}, nil)\n\n\t// mockedStateTracking.On(\"PutItem\", mock.MatchedBy(func(item interface{}) bool {\n\tmockedStateTracking.On(\"PutItem\", mock.MatchedBy(func(syncState syncstate.SyncStateRow) bool {\n\t\treturn syncState.MachineID == inputMachineID && syncState.BatchSize == 37 && syncState.LastCleanSync == \"2000-01-01T00:00:00Z\" && syncState.FeedSyncCursor == \"2000-01-01T00:00:00Z\"\n\t})).Return(&awsdynamodb.PutItemOutput{}, nil)\n\n\tmockedStateTracking.On(\"PutItem\", mock.MatchedBy(func(sensorData sensordata.SensorData) bool {\n\t\treturn sensorData.OSBuild == \"20D5029f\" && sensorData.SerialNum == \"C02123456789\" && sensorData.MachineID == inputMachineID && sensorData.PrimaryUser == \"nobody\" && sensorData.BinaryRuleCount == 3 && sensorData.CompilerRuleCount == 0\n\t})).Return(&awsdynamodb.PutItemOutput{}, nil)\n\n\th := &PostPreflightHandler{\n\t\ttimeProvider: timeProvider,\n\t\tmachineConfigurationService: machineconfiguration.GetMachineConfigurationService(mockedConfigurationFetcher, timeProvider),\n\t\tstateTrackingService: getStateTrackingService(mockedStateTracking, timeProvider),\n\t\tcleanSyncService: getCleanSyncService(timeProvider),\n\t}\n\n\tresp, err := h.Handle(request)\n\n\tassert.Empty(t, err)\n\tassert.Equal(t, 200, resp.StatusCode)\n\n\t// Ensure that the response matches the configuration returned\n\tassert.Equal(t, `{\"client_mode\":\"LOCKDOWN\",\"blocked_path_regex\":\"\",\"allowed_path_regex\":\"\",\"batch_size\":37,\"enable_bundles\":true,\"enable_transitive_rules\":false,\"clean_sync\":true,\"upload_logs_url\":\"/aaa\"}`, resp.Body)\n}", "func (m *MockEventLogger) Append(event eventlog.EventData) (uint64, uint64, time.Time, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Append\", event)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(uint64)\n\tret2, _ := ret[2].(time.Time)\n\tret3, _ := ret[3].(error)\n\treturn ret0, ret1, ret2, ret3\n}", "func (_m *RunInterface) CreateLogEvent(stage string, stream string, text string) (int, error) {\n\tret := _m.Called(stage, stream, text)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(string, string, string) int); ok {\n\t\tr0 = rf(stage, stream, text)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string, string) error); ok {\n\t\tr1 = rf(stage, stream, text)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *UsersRepository) Store(users *entities.User) error {\n\tret := _m.Called(users)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*entities.User) error); ok {\n\t\tr0 = rf(users)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockAggregate) clearUncommittedEvents() {\n\t_m.Called()\n}", "func (m *MockCommand) SubscribeEvent(body string) (map[string]interface{}, error) {\n\tret := m.ctrl.Call(m, \"SubscribeEvent\", body)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *LambdaAPI) UpdateEventSourceMapping(_a0 *lambda.UpdateEventSourceMappingInput) (*lambda.EventSourceMappingConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.EventSourceMappingConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.UpdateEventSourceMappingInput) *lambda.EventSourceMappingConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.EventSourceMappingConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.UpdateEventSourceMappingInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockArticleRepository) Store(a *article.Article) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", a)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *ServiceArticleInterface) Store(ctx context.Context, article *domain.Article) error {\n\tret := _m.Called(ctx, article)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *domain.Article) error); ok {\n\t\tr0 = rf(ctx, article)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (mmSaveOrder *mStoreMockSaveOrder) Set(f func(o1 pb.Order) (err error)) *StoreMock {\n\tif mmSaveOrder.defaultExpectation != nil {\n\t\tmmSaveOrder.mock.t.Fatalf(\"Default expectation is already set for the Store.SaveOrder method\")\n\t}\n\n\tif len(mmSaveOrder.expectations) > 0 {\n\t\tmmSaveOrder.mock.t.Fatalf(\"Some expectations are already set for the Store.SaveOrder method\")\n\t}\n\n\tmmSaveOrder.mock.funcSaveOrder = f\n\treturn mmSaveOrder.mock\n}", "func NewMockStore() *MockStore {\n\treturn &MockStore{\n\t\tmem: map[int]Post{},\n\t}\n}", "func (mmSaveOrderWithExpiration *mStoreMockSaveOrderWithExpiration) Inspect(f func(order pb.Order, expiration time.Duration)) *mStoreMockSaveOrderWithExpiration {\n\tif mmSaveOrderWithExpiration.mock.inspectFuncSaveOrderWithExpiration != nil {\n\t\tmmSaveOrderWithExpiration.mock.t.Fatalf(\"Inspect function is already set for StoreMock.SaveOrderWithExpiration\")\n\t}\n\n\tmmSaveOrderWithExpiration.mock.inspectFuncSaveOrderWithExpiration = f\n\n\treturn mmSaveOrderWithExpiration\n}", "func (_m *MockENotifyingList) Add(_a0 interface{}) bool {\n\tret := _m.Called(_a0)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(interface{}) bool); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func (m *MockNotificationEventDao) GetNotificationEventByHash(hash string) (*model.NotificationEvent, error) {\n\tret := m.ctrl.Call(m, \"GetNotificationEventByHash\", hash)\n\tret0, _ := ret[0].(*model.NotificationEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestPostWrite(t *testing.T) {\n\t// set up test server and mocked LogStore\n\tmockLogStore := new(MockedLogStore)\n\tserver := newTestServer(mockLogStore)\n\ttestServer := httptest.NewServer(server.server.Handler)\n\tdefer testServer.Close()\n\tclient := testServer.Client()\n\n\tlogsToWrite := []logstore.LogEntry{\n\t\tlogEntry(MustParse(\"2018-01-01T12:00:00.000Z\"), \"event 1\"),\n\t\tlogEntry(MustParse(\"2018-01-01T12:01:00.000Z\"), \"event 2\"),\n\t\tlogEntry(MustParse(\"2018-01-01T12:03:00.000Z\"), \"event 3\"),\n\t}\n\n\t//\n\t// set up mock expectations\n\t//\n\n\tmockLogStore.On(\"Ready\").Return(true, nil)\n\tmockLogStore.On(\"Write\", logsToWrite).Return(nil)\n\n\t//\n\t// make call\n\t//\n\tjsonBytes, _ := json.Marshal(logsToWrite)\n\tbody := strings.NewReader(string(jsonBytes))\n\tresp, _ := client.Post(testServer.URL+\"/write\", \"application/json\", body)\n\t// should return 503 (Service Unavailable)\n\tassert.Equalf(t, http.StatusOK, resp.StatusCode, \"unexpected response code\")\n\tassert.Equalf(t, ``, readBody(t, resp), \"unexpected response\")\n\n\t// verify that expected calls were made\n\tmockLogStore.AssertExpectations(t)\n}", "func (mmSavePosition *mStoreMockSavePosition) When(t1 pb.TotalPosition) *StoreMockSavePositionExpectation {\n\tif mmSavePosition.mock.funcSavePosition != nil {\n\t\tmmSavePosition.mock.t.Fatalf(\"StoreMock.SavePosition mock is already set by Set\")\n\t}\n\n\texpectation := &StoreMockSavePositionExpectation{\n\t\tmock: mmSavePosition.mock,\n\t\tparams: &StoreMockSavePositionParams{t1},\n\t}\n\tmmSavePosition.expectations = append(mmSavePosition.expectations, expectation)\n\treturn expectation\n}", "func (_m *MockHistoryEngine) ReplicateEvents(ctx context.Context, request *gohistory.ReplicateEventsRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.ReplicateEventsRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockTracks) Store(t app.Track) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Store\", t)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestUploader_Upload(t *testing.T) {\n m := new(MockS3)\n u := UserService{Uploader: m}\n\n m.On(\"PutObject\", \n\t\tmock.MatchedBy(func(i *s3.PutObjectInput) bool { // HL\n\t\t\t// other assertion ...\n\t\t\tassert.Equal(t, \"imre\", *i.Key)\n\t\t\treturn true\n }).\n\t\tReturn(&s3.PutObjectOutput{}, nil) // HL\n\n err := u.UploadProfile(&User{Name: \"imre\"}, []byte(`hello`)) // HL\n assert.NoError(t, err)\n m.AssertExpectations(t)\n}", "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func (_m *Knapsack) OsqueryHistoryInstanceStore() types.GetterSetterDeleterIteratorUpdater {\n\tret := _m.Called()\n\n\tvar r0 types.GetterSetterDeleterIteratorUpdater\n\tif rf, ok := ret.Get(0).(func() types.GetterSetterDeleterIteratorUpdater); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(types.GetterSetterDeleterIteratorUpdater)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestInterface(t *testing.T) {\n\tvar _ events.EventStore = &LoggingDecoratorEventStore{}\n}", "func (m *MockMachine) PublishLifecycleEvent(arg0 lifecycle.Type, arg1 ...lifecycle.Option) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"PublishLifecycleEvent\", varargs...)\n}", "func (_m *MockEStringToStringMapEntry) ENotify(_a0 ENotification) {\n\t_m.Called(_a0)\n}", "func (mmSavePosition *mStoreMockSavePosition) Set(f func(t1 pb.TotalPosition) (err error)) *StoreMock {\n\tif mmSavePosition.defaultExpectation != nil {\n\t\tmmSavePosition.mock.t.Fatalf(\"Default expectation is already set for the Store.SavePosition method\")\n\t}\n\n\tif len(mmSavePosition.expectations) > 0 {\n\t\tmmSavePosition.mock.t.Fatalf(\"Some expectations are already set for the Store.SavePosition method\")\n\t}\n\n\tmmSavePosition.mock.funcSavePosition = f\n\treturn mmSavePosition.mock\n}", "func (_m *OplogCursor) Push(_a0 []byte) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func([]byte) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func TestBatchOnUploadEvent(t *testing.T) {\n\tsw := &mocks.SavingWriter{}\n\tbatch := Batch{sw}\n\terr := batch.OnUploadEvent(&spec.Measurement{\n\t\tAppInfo: spec.AppInfo{\n\t\t\tNumBytes: 100000000,\n\t\t},\n\t\tDirection: \"upload\",\n\t\tElapsed: 3.0,\n\t\tOrigin: \"client\",\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(sw.Data) != 1 {\n\t\tt.Fatal(\"invalid length\")\n\t}\n\tvar event struct {\n\t\tKey string `json:\"key\"`\n\t\tValue struct {\n\t\t\tAppInfo struct {\n\t\t\t\tNumBytes int64 `json:\"num_bytes\"`\n\t\t\t} `json:\"app_info\"`\n\t\t\tDirection string `json:\"direction\"`\n\t\t\tElapsed float64 `json:\"elapsed\"`\n\t\t\tOrigin string `json:\"origin\"`\n\t\t} `json:\"value\"`\n\t}\n\terr = json.Unmarshal(sw.Data[0], &event)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif event.Key != \"measurement\" {\n\t\tt.Fatal(\"Unexpected event key\")\n\t}\n\tif event.Value.AppInfo.NumBytes != 100000000 {\n\t\tt.Fatal(\"Unexpected num bytes field value\")\n\t}\n\tif event.Value.Direction != \"upload\" {\n\t\tt.Fatal(\"Unexpected direction field value\")\n\t}\n\tif event.Value.Elapsed != 3.0 {\n\t\tt.Fatal(\"Unexpected elapsed field value\")\n\t}\n\tif event.Value.Origin != \"client\" {\n\t\tt.Fatal(\"Unexpected elapsed field value\")\n\t}\n}", "func TestAddEventHub(t *testing.T) {\n\n\t// Test Data\n\tnamespaceName1 := \"TestNamespaceName1\"\n\tnamespaceName2 := \"TestNamespaceName2\"\n\n\t// Create A Mock HubManager\n\tmockHubManager := &MockHubManager{}\n\n\t// Replace The NewHubManagerFromConnectionString Wrapper To Provide Mock Implementation & Defer Reset\n\tnewHubManagerFromConnectionStringWrapperPlaceholder := NewHubManagerFromConnectionStringWrapper\n\tNewHubManagerFromConnectionStringWrapper = func(connectionString string) (managerInterface HubManagerInterface, e error) {\n\t\treturn mockHubManager, nil\n\t}\n\tdefer func() { NewHubManagerFromConnectionStringWrapper = newHubManagerFromConnectionStringWrapperPlaceholder }()\n\n\t// Create A Test Logger\n\tlogger := logtesting.TestLogger(t).Desugar()\n\n\t// Create Test Namespaces\n\tnamespace1, err := createTestNamespaceWithCount(logger, namespaceName1, 1)\n\tassert.Nil(t, err)\n\n\t// Create The Cache's EventHub Map\n\teventHubMap := make(map[string]*Namespace)\n\teventHubMap[namespaceName1] = namespace1\n\n\t// Create A Cache To Test\n\tcache := &Cache{\n\t\tlogger: logger,\n\t\teventhubMap: eventHubMap,\n\t}\n\n\t// Perform The Test\n\tfoo, _ := createTestNamespaceWithCount(logger, namespaceName2, 0)\n\tcache.AddEventHub(context.TODO(), namespaceName2, foo)\n\n\t// Verify The Results\n\tassert.Len(t, cache.eventhubMap, 2)\n\tassert.NotNil(t, cache.eventhubMap[namespaceName1])\n\tassert.NotNil(t, cache.eventhubMap[namespaceName2])\n\tassert.Equal(t, namespaceName1, cache.eventhubMap[namespaceName1].Name)\n\tassert.Equal(t, namespaceName2, cache.eventhubMap[namespaceName2].Name)\n\tassert.Equal(t, 1, cache.eventhubMap[namespaceName1].Count)\n\tassert.Equal(t, 1, cache.eventhubMap[namespaceName2].Count)\n}", "func (_m *Keyring) Set(_a0 keyring.Item) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(keyring.Item) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockHost) EventBus() event.Bus {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EventBus\")\n\tret0, _ := ret[0].(event.Bus)\n\treturn ret0\n}", "func MockAgreementEvent(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, iterativeIdx ...int) *Agreement {\n\t// Make sure we create an event made by an actual voting committee member\n\tc := p.CreateVotingCommittee(round, step, len(keys))\n\tcKeys := createCommitteeKeySet(c, keys)\n\n\tidx := 0\n\tif len(iterativeIdx) != 0 {\n\t\tidx = iterativeIdx[0]\n\t}\n\n\tif idx > len(keys) {\n\t\tpanic(\"wrong iterative index: cannot iterate more than there are keys\")\n\t}\n\n\ta := New(header.Header{Round: round, Step: step, BlockHash: hash, PubKeyBLS: cKeys[idx].BLSPubKeyBytes})\n\t// generating reduction events (votes) and signing them\n\tsteps := GenVotes(hash, round, step, keys, p)\n\n\twhole := new(bytes.Buffer)\n\tif err := header.MarshalSignableVote(whole, a.Header); err != nil {\n\t\tpanic(err)\n\t}\n\n\tsig, _ := bls.Sign(cKeys[idx].BLSSecretKey, cKeys[idx].BLSPubKey, whole.Bytes())\n\ta.VotesPerStep = steps\n\ta.SetSignature(sig.Compress())\n\treturn a\n}", "func (_m *MockAggregate) getUncommittedEvents() []Event {\n\tret := _m.Called()\n\n\tvar r0 []Event\n\tif rf, ok := ret.Get(0).(func() []Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestMockOnEvent(t *testing.T) {\n\tmockServer := &MockRailsServer{T: t, Behaviour: MockEvent}\n\n\tdialer := wstest.NewDialer(mockServer)\n\tdialer.HandshakeTimeout = time.Second * 2\n\n\tclient := NewClient(fakeEndpoint).WithDialer(dialer)\n\n\tcalled := make(chan struct{})\n\n\tclient.OnEvent(\"AgentChannel\", func(conn *websocket.Conn, payload *Payload, error error) {\n\t\tcalled <- struct{}{}\n\t\treturn\n\t})\n\n\terr := client.Serve()\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treceiveSleepMs(2000, called, t)\n}", "func (_m *MockHistoryEngine) ReapplyEvents(ctx context.Context, domainUUID string, workflowID string, events []*shared.HistoryEvent) error {\n\tret := _m.Called(domainUUID, workflowID, events)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string, []*shared.HistoryEvent) error); ok {\n\t\tr0 = rf(domainUUID, workflowID, events)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (a *BaseAggregateSourced) StoreEvent(data interface{}) {\n\tv := a.GetVersion() + len(a.events) + 1\n\ttimestamp := GetTimestamp()\n\t_, typeName := GetTypeName(data)\n\te := &Event{\n\t\tType: typeName,\n\t\tTimestamp: timestamp,\n\t\tAggregateID: a.ID,\n\t\tAggregateType: a.TypeName,\n\t\tVersion: v,\n\t\tData: data,\n\t}\n\n\ta.events = append(a.events, e)\n}", "func (_m *Repository) Store(p *entity.Person) error {\n\tret := _m.Called(p)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*entity.Person) error); ok {\n\t\tr0 = rf(p)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockServer) HandleEvent(event sdk.Event) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"HandleEvent\", event)\n}", "func (t *MockTransporter) Publish(e *Event) error {\n\tfmt.Println(string(e.GetEventAsJSON()))\n\treturn nil\n}", "func (mmGetPosition *mStoreMockGetPosition) When(account string, contractID string) *StoreMockGetPositionExpectation {\n\tif mmGetPosition.mock.funcGetPosition != nil {\n\t\tmmGetPosition.mock.t.Fatalf(\"StoreMock.GetPosition mock is already set by Set\")\n\t}\n\n\texpectation := &StoreMockGetPositionExpectation{\n\t\tmock: mmGetPosition.mock,\n\t\tparams: &StoreMockGetPositionParams{account, contractID},\n\t}\n\tmmGetPosition.expectations = append(mmGetPosition.expectations, expectation)\n\treturn expectation\n}", "func (_m *StoreService) Insert(_a0 context.Context, _a1 *models.Snapshot, _a2 []byte) error {\n\tret := _m.Called(_a0, _a1, _a2)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.Snapshot, []byte) error); ok {\n\t\tr0 = rf(_a0, _a1, _a2)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func TestService_Handle_Invitee(t *testing.T) {\n\tdata := make(map[string]string)\n\t// using this mockStore as a hack in order to obtain the auto-generated thid after\n\t// automatically sending the request back to Bob\n\tvar lock sync.RWMutex\n\tstore := &mockStore{\n\t\tput: func(s string, bytes []byte) error {\n\t\t\tlock.Lock()\n\t\t\tdefer lock.Unlock()\n\t\t\tdata[s] = string(bytes)\n\t\t\treturn nil\n\t\t},\n\t\tget: func(s string) (bytes []byte, e error) {\n\t\t\tlock.RLock()\n\t\t\tdefer lock.RUnlock()\n\t\t\tif state, found := data[s]; found {\n\t\t\t\treturn []byte(state), nil\n\t\t\t}\n\t\t\treturn nil, storage.ErrDataNotFound\n\t\t},\n\t}\n\tprov := protocol.MockProvider{}\n\tctx := context{outboundDispatcher: prov.OutboundDispatcher(), didCreator: &mockdid.MockDIDCreator{Doc: getMockDID()}}\n\tnewDidDoc, err := ctx.didCreator.CreateDID()\n\trequire.NoError(t, err)\n\n\ts, err := New(&mockdid.MockDIDCreator{Doc: getMockDID()}, &protocol.MockProvider{CustomStore: store})\n\trequire.NoError(t, err)\n\tactionCh := make(chan service.DIDCommAction, 10)\n\terr = s.RegisterActionEvent(actionCh)\n\trequire.NoError(t, err)\n\tstatusCh := make(chan service.StateMsg, 10)\n\terr = s.RegisterMsgEvent(statusCh)\n\trequire.NoError(t, err)\n\tdone := make(chan bool)\n\tgo func() {\n\t\tfor e := range statusCh {\n\t\t\tif e.Type == service.PostState {\n\t\t\t\t// receive the events\n\t\t\t\tif e.StateID == \"completed\" {\n\t\t\t\t\tdone <- true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tgo func() { require.NoError(t, service.AutoExecuteActionEvent(actionCh)) }()\n\n\t// Alice receives an invitation from Bob\n\tpayloadBytes, err := json.Marshal(\n\t\t&Invitation{\n\t\t\tType: ConnectionInvite,\n\t\t\tID: randomString(),\n\t\t\tLabel: \"Bob\",\n\t\t\tDID: \"did:example:bob\",\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\tmsg := service.DIDCommMsg{Type: ConnectionInvite, Outbound: false, Payload: payloadBytes}\n\terr = s.Handle(&msg)\n\trequire.NoError(t, err)\n\n\t// Alice automatically sends a Request to Bob and is now in REQUESTED state.\n\tvar thid string\n\tvar currState string\n\tfor k, v := range data {\n\t\tthid = k\n\t\tcurrState = v\n\t\tbreak\n\t}\n\trequire.NotEmpty(t, thid)\n\trequire.Equal(t, (&requested{}).Name(), currState)\n\n\tconnection := &Connection{\n\t\tDID: newDidDoc.ID,\n\t\tDIDDoc: newDidDoc,\n\t}\n\n\tconnectionSignature, err := prepareConnectionSignature(connection)\n\trequire.NoError(t, err)\n\n\t// Bob replies with a Response\n\tpayloadBytes, err = json.Marshal(\n\t\t&Response{\n\t\t\tType: ConnectionResponse,\n\t\t\tID: randomString(),\n\t\t\tConnectionSignature: connectionSignature,\n\t\t\tThread: &decorator.Thread{ID: thid},\n\t\t},\n\t)\n\trequire.NoError(t, err)\n\tmsg = service.DIDCommMsg{Type: ConnectionResponse, Outbound: false, Payload: payloadBytes}\n\terr = s.Handle(&msg)\n\trequire.NoError(t, err)\n\n\t// Alice automatically sends an ACK to Bob\n\t// Alice must now be in COMPLETED state\n\tselect {\n\tcase <-done:\n\tcase <-time.After(2 * time.Second):\n\t\trequire.Fail(t, \"didn't receive post event complete\")\n\t}\n\tvalidateState(t, s, thid, (&completed{}).Name())\n}", "func NewEventProviderMock(t NewEventProviderMockT) *EventProviderMock {\n\tmock := &EventProviderMock{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *mRecentIndexStorageMockAddObjectWithTLL) Set(f func(p context.Context, p1 insolar.ID, p2 int)) *RecentIndexStorageMock {\n\tm.mainExpectation = nil\n\tm.expectationSeries = nil\n\n\tm.mock.AddObjectWithTLLFunc = f\n\treturn m.mock\n}", "func (_m *MockHistoryEngine) ReplicateRawEvents(ctx context.Context, request *gohistory.ReplicateRawEventsRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.ReplicateRawEventsRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockBookingStorage) ByID() {\n\t_m.Called()\n}", "func TestIndexHandler(t *testing.T) {\n\telist := []Event{testEvent}\n\n\th := Handler{\n\t\tdb: MockDatabase{elist: elist},\n\t}\n\treq, w := newReqParams(\"GET\")\n\n\th.Index(w, req, httprouter.Params{})\n\n\tcases := []struct {\n\t\tlabel, actual, expected interface{}\n\t}{\n\t\t{\"Response code\", w.Code, 200},\n\t\t{\"Response body contains context\", strings.Contains(w.Body.String(), testEvent.Context), true},\n\t\t{\"Response body contains event type\", strings.Contains(w.Body.String(), testEvent.EventType), true},\n\t\t{\"Response body contains data\", strings.Contains(w.Body.String(), testEvent.Data), true},\n\t\t{\"Response body contains id\", strings.Contains(w.Body.String(), testEvent.ID.String()), true},\n\t\t{\"Response body contains account id\", strings.Contains(w.Body.String(), testEvent.OriginalAccountID.String()), true},\n\t}\n\n\ttestCases(t, cases)\n}", "func (_m *AuthorController) Store(c *fiber.Ctx) error {\n\tret := _m.Called(c)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*fiber.Ctx) error); ok {\n\t\tr0 = rf(c)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Index) Delete(_a0 index.Entry) (storage.Event, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 storage.Event\n\tif rf, ok := ret.Get(0).(func(index.Entry) storage.Event); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(storage.Event)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(index.Entry) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func mockHandler(resp queryrange.Response, err error) queryrange.Handler {\n\treturn queryrange.HandlerFunc(func(ctx context.Context, req queryrange.Request) (queryrange.Response, error) {\n\t\tif expired := ctx.Err(); expired != nil {\n\t\t\treturn nil, expired\n\t\t}\n\n\t\treturn resp, err\n\t})\n}", "func NewStrictMockDBStore() *MockDBStore {\n\treturn &MockDBStore{\n\t\tCommitsVisibleToUploadFunc: &DBStoreCommitsVisibleToUploadFunc{\n\t\t\tdefaultHook: func(context.Context, int, int, *string) ([]string, *string, error) {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.CommitsVisibleToUpload\")\n\t\t\t},\n\t\t},\n\t\tDirtyRepositoriesFunc: &DBStoreDirtyRepositoriesFunc{\n\t\t\tdefaultHook: func(context.Context) (map[int]int, error) {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.DirtyRepositories\")\n\t\t\t},\n\t\t},\n\t\tDoneFunc: &DBStoreDoneFunc{\n\t\t\tdefaultHook: func(error) error {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.Done\")\n\t\t\t},\n\t\t},\n\t\tGetConfigurationPoliciesFunc: &DBStoreGetConfigurationPoliciesFunc{\n\t\t\tdefaultHook: func(context.Context, dbstore.GetConfigurationPoliciesOptions) ([]dbstore.ConfigurationPolicy, int, error) {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.GetConfigurationPolicies\")\n\t\t\t},\n\t\t},\n\t\tGetUploadsFunc: &DBStoreGetUploadsFunc{\n\t\t\tdefaultHook: func(context.Context, dbstore.GetUploadsOptions) ([]dbstore.Upload, int, error) {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.GetUploads\")\n\t\t\t},\n\t\t},\n\t\tHandleFunc: &DBStoreHandleFunc{\n\t\t\tdefaultHook: func() basestore.TransactableHandle {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.Handle\")\n\t\t\t},\n\t\t},\n\t\tSelectRepositoriesForRetentionScanFunc: &DBStoreSelectRepositoriesForRetentionScanFunc{\n\t\t\tdefaultHook: func(context.Context, time.Duration, int) ([]int, error) {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.SelectRepositoriesForRetentionScan\")\n\t\t\t},\n\t\t},\n\t\tTransactFunc: &DBStoreTransactFunc{\n\t\t\tdefaultHook: func(context.Context) (DBStore, error) {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.Transact\")\n\t\t\t},\n\t\t},\n\t\tUpdateUploadRetentionFunc: &DBStoreUpdateUploadRetentionFunc{\n\t\t\tdefaultHook: func(context.Context, []int, []int) error {\n\t\t\t\tpanic(\"unexpected invocation of MockDBStore.UpdateUploadRetention\")\n\t\t\t},\n\t\t},\n\t}\n}", "func (mmSaveOrder *mStoreMockSaveOrder) When(o1 pb.Order) *StoreMockSaveOrderExpectation {\n\tif mmSaveOrder.mock.funcSaveOrder != nil {\n\t\tmmSaveOrder.mock.t.Fatalf(\"StoreMock.SaveOrder mock is already set by Set\")\n\t}\n\n\texpectation := &StoreMockSaveOrderExpectation{\n\t\tmock: mmSaveOrder.mock,\n\t\tparams: &StoreMockSaveOrderParams{o1},\n\t}\n\tmmSaveOrder.expectations = append(mmSaveOrder.expectations, expectation)\n\treturn expectation\n}", "func (_m *MockStatusStoreIface) StoreCooldownEndsAt(t time.Time) error {\n\tret := _m.Called(t)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(time.Time) error); ok {\n\t\tr0 = rf(t)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (client *MockClient) Eventf(object runtime.Object, eventType string, reason string, messageFormat string, args ...interface{}) {\n\tclient.createEvent(buildEvent(object, eventType, reason, fmt.Sprintf(messageFormat, args...)))\n}" ]
[ "0.6289277", "0.62114894", "0.62100565", "0.6184719", "0.6097846", "0.5966063", "0.59371525", "0.5930946", "0.5930256", "0.58361834", "0.57825756", "0.5665977", "0.56246656", "0.5573866", "0.5529164", "0.55186653", "0.55073816", "0.5465433", "0.54647565", "0.54395753", "0.54009056", "0.539963", "0.5374", "0.53677607", "0.53677547", "0.5367006", "0.53480434", "0.53449386", "0.5315398", "0.5310176", "0.53014266", "0.528184", "0.52733546", "0.52599126", "0.5235878", "0.52292514", "0.5222072", "0.52200615", "0.52150893", "0.520929", "0.5207736", "0.5203688", "0.5201462", "0.52006125", "0.5193076", "0.5192697", "0.5192282", "0.5190024", "0.51586294", "0.5154788", "0.51460546", "0.51348305", "0.5128642", "0.51060426", "0.5102158", "0.5098677", "0.50972736", "0.5094397", "0.5093097", "0.5083813", "0.50811267", "0.5079228", "0.50769794", "0.50693023", "0.5061744", "0.5056206", "0.505066", "0.50478077", "0.5036733", "0.50354975", "0.50341886", "0.50310725", "0.50215435", "0.5018743", "0.501634", "0.50101036", "0.50075245", "0.50025755", "0.49946204", "0.49936426", "0.49920815", "0.49877286", "0.49874282", "0.49855375", "0.4984062", "0.49826944", "0.49821216", "0.49708387", "0.495925", "0.49410102", "0.49377546", "0.49329332", "0.49303174", "0.4917124", "0.49096227", "0.49074805", "0.4898856", "0.48745185", "0.48736", "0.48707923" ]
0.78557014
0
Version provides a mock function with given fields:
func (_m *MockAggregate) Version() int { ret := _m.Called() var r0 int if rf, ok := ret.Get(0).(func() int); ok { r0 = rf() } else { r0 = ret.Get(0).(int) } return r0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *U2FDevice) Version() (string, error) {\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\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func newVersionCheckerMock(version string, tags []string) *VersionChecker {\n\n\tfixedAppVersion := fixVersion(version)\n\n\treturn &VersionChecker{\n\t\tfixedAppVersion: fixedAppVersion,\n\t\tversionSource: &versionCheckerMock{\n\t\t\ttags: tags,\n\t\t\tfixVersionStrFunc: fixVersion,\n\t\t\ttagFilterFunc: versionFilterFunc(fixedAppVersion),\n\t\t},\n\t}\n}", "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (m *MockEventLogger) Version() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *Mock) Version() string {\n\treturn defaultMockVersion\n}", "func (m *MockShootClients) Version() *version.Info {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(*version.Info)\n\treturn ret0\n}", "func (m *MockFullNode) Version(arg0 context.Context) (types0.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\", arg0)\n\tret0, _ := ret[0].(types0.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *System) Version() (types.Text, error) {\n\tret := _m.Called()\n\n\tvar r0 types.Text\n\tif rf, ok := ret.Get(0).(func() types.Text); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(types.Text)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *PluginerMock) VersionCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockVersion.RLock()\n\tcalls = mock.calls.Version\n\tmock.lockVersion.RUnlock()\n\treturn calls\n}", "func MockKernelVersion(version string) (restore func()) {\n\told := KernelVersion\n\tKernelVersion = func() string { return version }\n\treturn func() {\n\t\tKernelVersion = old\n\t}\n}", "func (_m *MockAggregate) OriginalVersion() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func TestVersion(t *testing.T) {\n\t//fmt.Println(\"EliteProvision [\" + Version() + \"]\")\n}", "func (m *MockqueueTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockqueueTaskInfo) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockRemotePeer) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockMachine) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func TestGetVersion(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(false, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\n\ttrustAgentService.router.HandleFunc(\"/version\", errorHandler(getVersion())).Methods(\"GET\")\n\n\t// test request\n\trequest, err := http.NewRequest(\"GET\", \"/version\", nil)\n\tassert.NoError(err)\n\n\trecorder := httptest.NewRecorder()\n\tresponse := recorder.Result()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tassert.Equal(http.StatusOK, response.StatusCode)\n\tfmt.Printf(\"Version: %s\\n\", recorder.Body.String())\n\tassert.NotEmpty(recorder.Body.String())\n}", "func (m *MockTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func TestVersion(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.Register(\"test\", \"json\", NewTestHandler(\"json\", assert))\n\tassert.Nil(err)\n\t// Perform test requests.\n\treq := restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\tresp := ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"1.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"2\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"2.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"3.0\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"4.0.0-alpha\")\n}", "func TestGetVersion(t *testing.T) {\n\ttests := []struct {\n\t\tversion string\n\t\tcommit string\n\t\tdate string\n\t\texpect string\n\t\tshortOutput bool\n\t}{\n\t\t{\n\t\t\t\"a\",\n\t\t\t\"b\",\n\t\t\t\"c\",\n\t\t\t\"waver version: a from commit b built on c\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4\",\n\t\t\t\"5b1a61f9b58e3778986c99b1282840ce64329614\",\n\t\t\t\"Thu May 21 16:48:18 PDT 2020\",\n\t\t\t\"waver version: v0.12.4 from commit 5b1a61f9b58e3778986c99b1282840ce64329614 built on Thu May 21 16:48:18 PDT 2020\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"waver version: v0.12.4-rc5 from commit 5b1a61f9b58 built on 1590105848\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\ttrue,\n\t\t},\n\t}\n\n\t// save the current global variables so they can be set back after testing\n\toldVal := version\n\toldCommit := commit\n\toldDate := date\n\n\tfor _, test := range tests {\n\t\t// run through each test, should not be run in parallel.\n\t\tversion = test.version\n\t\tcommit = test.commit\n\t\tdate = test.date\n\n\t\t// build the new Cobra command and configure stdout and args\n\t\tv := Get(test.shortOutput)\n\n\t\t// assert output string matches expectations\n\t\tassert.Equal(t, test.expect, v)\n\t}\n\n\t// put the original build values back after tests have run\n\tversion = oldVal\n\tcommit = oldCommit\n\tdate = oldDate\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func (m *MockVersion) GetVersion(keyName string) (string, error) {\n\targs := m.Called()\n\treturn args.String(0), args.Error(1)\n}", "func (m *MockPacketHandler) GetVersion() protocol.VersionNumber {\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(protocol.VersionNumber)\n\treturn ret0\n}", "func (_m *MockBackend) ProtocolVersion() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_BaseFactory *BaseFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestGetVersion(t *testing.T) {\n\tv := \"0.0.0\"\n\tmaj, min, patch := getVersion(v)\n\n\tif maj != 0 && min != 0 && patch != 0 {\n\t\tt.Error(\"maj, min or patch are not set to 0\", maj, min, patch)\n\t}\n\n\tv = \"1.2.4\"\n\n\tmaj, min, patch = getVersion(v)\n\n\tif maj != 1 && min != 2 && patch != 4 {\n\t\tt.Error(\"maj, min or patch are not set to 1, 2, 4\", maj, min, patch)\n\t}\n}", "func (_m *VersionInterface) GetVersion(ctx context.Context, r *admin.GetVersionRequest) (*admin.GetVersionResponse, error) {\n\tret := _m.Called(ctx, r)\n\n\tvar r0 *admin.GetVersionResponse\n\tif rf, ok := ret.Get(0).(func(context.Context, *admin.GetVersionRequest) *admin.GetVersionResponse); ok {\n\t\tr0 = rf(ctx, r)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*admin.GetVersionResponse)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *admin.GetVersionRequest) error); ok {\n\t\tr1 = rf(ctx, r)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestHandleGetVersion(t *testing.T) {\n\tsv := ServerVersion{Version:\"v1\", IP:\"127.0.0.1\", Port:8080}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/version\", sv.handGetVersion)\n\n\twriter := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/version\", nil)\n\tmux.ServeHTTP(writer, req)\n\n\tfmt.Println(writer.Body.String())\n}", "func (_BaseLibraryFactory *BaseLibraryFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibraryFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestDaemon_Version(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\tv, err := d.Version(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif v != testVersion {\n\t\tt.Fatalf(\"Expected %v but got %v\", testVersion, v)\n\t}\n}", "func (c MockDockerClient) ServerVersion(ctx context.Context) (dockertypes.Version, error) {\n\tif c.ServerVersionFn != nil {\n\t\tfmt.Println(\"[MockDockerClient] In \", utils.CurrentFunctionName())\n\t\treturn c.ServerVersionFn(ctx)\n\t}\n\tpanic(fmt.Sprintf(\"No function defined for: %s\", utils.CurrentFunctionName()))\n}", "func (_m *LambdaAPI) PublishVersion(_a0 *lambda.PublishVersionInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *ObjectVersioner) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error) {\n\tret := _m.Called(in, gv)\n\n\tvar r0 runtime.Object\n\tif rf, ok := ret.Get(0).(func(runtime.Object, runtime.GroupVersioner) runtime.Object); ok {\n\t\tr0 = rf(in, gv)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(runtime.Object)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(runtime.Object, runtime.GroupVersioner) error); ok {\n\t\tr1 = rf(in, gv)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *CIPDClient) ResolveVersion(ctx context.Context, packageName string, version string) (common.Pin, error) {\n\tret := _m.Called(ctx, packageName, version)\n\n\tvar r0 common.Pin\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string) common.Pin); ok {\n\t\tr0 = rf(ctx, packageName, version)\n\t} else {\n\t\tr0 = ret.Get(0).(common.Pin)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {\n\t\tr1 = rf(ctx, packageName, version)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockKernelData) FullVersion(arg0 *v1.NodeList) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FullVersion\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\tfor _, v := range versionTests {\n\t\tp, e := model.ParseVersion(v[0])\n\t\tassert.Nil(t, e, \"Should have parsed %s\", v)\n\t\tassert.Equal(t, p.String(), v[1], \"Should be equal %s==%s\", p.String(), v)\n\t}\n}", "func (m *MockFullNode) StateNetworkVersion(arg0 context.Context, arg1 types0.TipSetKey) (network.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateNetworkVersion\", arg0, arg1)\n\tret0, _ := ret[0].(network.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_AggregatorV2V3Interface *AggregatorV2V3InterfaceCaller) Version(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _AggregatorV2V3Interface.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestVersionStorage(openStorage func() storage.ChunkStorage, closeStorage func(storage.ChunkStorage),\n\tresetStorage func(), t *testing.T) {\n\tassert := testifyAssert.New(t)\n\n\tvar s storage.ChunkStorage = nil\n\n\ttest := func(name string, run func()) {\n\t\tt.Logf(\"subtest: %s\", name)\n\t\tresetStorage()\n\t\ts = openStorage()\n\t\tdefer func() {\n\t\t\tif s != nil {\n\t\t\t\tcloseStorage(s)\n\t\t\t\ts = nil\n\t\t\t}\n\t\t}()\n\t\trun()\n\t}\n\n\treopen := func() {\n\t\tcloseStorage(s)\n\t\t// no reset\n\t\ts = openStorage()\n\t}\n\n\ttest(\"empty by default\", func() {\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(chunks)\n\t})\n\n\ttest(\"cannot get nonexistent latest\", func() {\n\t\t_, err := s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"cannot delete nonexistent version\", func() {\n\t\terr := s.DeleteLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"write single version corrolaries\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\t_, err = s.GetLatestVersion(72)\n\t\tassert.Error(err)\n\n\t\t_, err = s.GetLatestVersion(70)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"updating versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"updating versions with durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"delete subset of versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete subset of versions with durabilitiy\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\treopen()\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\treopen()\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete all versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\t\tassert.NoError(s.DeleteLatestVersion(72))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(versions)\n\n\t\t_, err = s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n}", "func TestVersion(t *testing.T) {\n\tvers := Version()\n\tif len(vers) == 0 {\n\t\tt.Error(\"version string is not present\")\n\t}\n}", "func (_m *LambdaAPI) PublishVersionRequest(_a0 *lambda.PublishVersionInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func NewObjectVersioner(t mockConstructorTestingTNewObjectVersioner) *ObjectVersioner {\n\tmock := &ObjectVersioner{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (_Ownable *OwnableCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Ownable.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockClient) PublicVersion() msp.Identity {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublicVersion\")\n\tret0, _ := ret[0].(msp.Identity)\n\treturn ret0\n}", "func (m *MockVersionInfoDao) GetVersionByDeployVersion(version, serviceID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByDeployVersion\", version, serviceID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MockMinimalRelease(t *testing.T) *Release {\n\tvar r Release\n\terr := json.Unmarshal([]byte(`\n {\n \"release_id\": \"rr\",\n \"project_name\": \"project\",\n \"config_name\": \"config\",\n \"ami\": \"ami-123456\",\n \"subnets\": [\"subnet-1\"],\n \"user_data\": \"echo DATE\",\n \"services\": {\n \"web\": {\n \"instance_type\": \"t2.small\",\n \"security_groups\": [\"web-sg\"]\n }\n }\n }\n `), &r)\n\n\tassert.NoError(t, err)\n\tr.CreatedAt = to.Timep(time.Now())\n\n\treturn &r\n}", "func (m *MockKernelData) PatchVersion(kernelFullVersion string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PatchVersion\", kernelFullVersion)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Version) UpdateWarningVersion(_a0 string) (string, bool, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 bool\n\tif rf, ok := ret.Get(1).(func(string) bool); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Get(1).(bool)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(_a0)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (_BaseGroupFactory *BaseGroupFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseGroupFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWalletFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func ReleaseMock(opts *MockReleaseOptions) *release.Release {\n\tdate := time.Unix(242085845, 0).UTC()\n\n\tname := opts.Name\n\tif name == \"\" {\n\t\tname = \"testrelease-\" + string(rand.Intn(100))\n\t}\n\n\tversion := 1\n\tif opts.Version != 0 {\n\t\tversion = opts.Version\n\t}\n\n\tnamespace := opts.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\tch := opts.Chart\n\tif opts.Chart == nil {\n\t\tch = &chart.Chart{\n\t\t\tMetadata: &chart.Metadata{\n\t\t\t\tName: \"foo\",\n\t\t\t\tVersion: \"0.1.0-beta.1\",\n\t\t\t},\n\t\t\tTemplates: []*chart.File{\n\t\t\t\t{Name: \"templates/foo.tpl\", Data: []byte(MockManifest)},\n\t\t\t},\n\t\t}\n\t}\n\n\tscode := release.StatusDeployed\n\tif len(opts.Status) > 0 {\n\t\tscode = opts.Status\n\t}\n\n\treturn &release.Release{\n\t\tName: name,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: date,\n\t\t\tLastDeployed: date,\n\t\t\tStatus: scode,\n\t\t\tDescription: \"Release mock\",\n\t\t},\n\t\tChart: ch,\n\t\tConfig: map[string]interface{}{\"name\": \"value\"},\n\t\tVersion: version,\n\t\tNamespace: namespace,\n\t\tHooks: []*release.Hook{\n\t\t\t{\n\t\t\t\tName: \"pre-install-hook\",\n\t\t\t\tKind: \"Job\",\n\t\t\t\tPath: \"pre-install-hook.yaml\",\n\t\t\t\tManifest: MockHookTemplate,\n\t\t\t\tLastRun: date,\n\t\t\t\tEvents: []release.HookEvent{release.HookPreInstall},\n\t\t\t},\n\t\t},\n\t\tManifest: MockManifest,\n\t}\n}", "func (m *MockVersionInfoDao) GetVersionByEventID(eventID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByEventID\", eventID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\n\ttests := []struct {\n\t\tInput driver.Version\n\t\tMajor int\n\t\tMinor int\n\t\tSub string\n\t\tSubInt int\n\t\tSubIsInt bool\n\t}{\n\t\t{\"1.2.3\", 1, 2, \"3\", 3, true},\n\t\t{\"\", 0, 0, \"\", 0, false},\n\t\t{\"1.2.3a\", 1, 2, \"3a\", 0, false},\n\t\t{\"13.12\", 13, 12, \"\", 0, false},\n\t}\n\n\tfor _, test := range tests {\n\t\tif v := test.Input.Major(); v != test.Major {\n\t\t\tt.Errorf(\"Major failed for '%s', expected %d, got %d\", test.Input, test.Major, v)\n\t\t}\n\t\tif v := test.Input.Minor(); v != test.Minor {\n\t\t\tt.Errorf(\"Minor failed for '%s', expected %d, got %d\", test.Input, test.Minor, v)\n\t\t}\n\t\tif v := test.Input.Sub(); v != test.Sub {\n\t\t\tt.Errorf(\"Sub failed for '%s', expected '%s', got '%s'\", test.Input, test.Sub, v)\n\t\t}\n\t\tif v, vIsInt := test.Input.SubInt(); vIsInt != test.SubIsInt || v != test.SubInt {\n\t\t\tt.Errorf(\"SubInt failed for '%s', expected (%d,%v), got (%d,%v)\", test.Input, test.SubInt, test.SubIsInt, v, vIsInt)\n\t\t}\n\t}\n}", "func (m *MockTask) SetVersion(version int64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetVersion\", version)\n}", "func Test_LatestVersion(t *testing.T) {\n\tmockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"0.6.1\\n\"))\n\t}))\n\tdefer mockServer.Close()\n\n\tversion, err := latestVersion(mockServer.URL)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttestVersion := semver.New(\"0.6.1\")\n\tif !version.Equal(*testVersion) {\n\t\tt.Error(\"Version equality check failed.\")\n\t}\n}", "func (_Upgradeable *UpgradeableCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Upgradeable.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func (m *MockEventLogger) VersionInitial() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VersionInitial\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func Version(frame wdte.Frame, args ...wdte.Func) wdte.Func {\n\tframe = frame.Sub(\"version\")\n\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn wdte.Error{\n\t\t\tErr: ErrNoBuildInfo,\n\t\t\tFrame: frame,\n\t\t}\n\t}\n\n\tfor _, dep := range info.Deps {\n\t\tif dep.Path != \"github.com/DeedleFake/wdte\" {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn wdte.String(dep.Version)\n\t}\n\n\treturn wdte.Error{\n\t\tErr: ErrDepNotFound,\n\t\tFrame: frame,\n\t}\n}", "func (s *suite) Test_QueryNextVersion_happy_path(c *C) {\n\tserver := NewMockServer().WithBody(`1.0`).Start(c)\n\tdefer server.Stop()\n\n\tunit := NewRemoteInventory(server.URL, \"token\", \"\", \"\", false)\n\tversion, err := unit.QueryNextVersion(\"query-project\", \"name\", \"1.@\")\n\tserver.ExpectCalled(c, true, queryNextVersionURL)\n\tc.Assert(err, IsNil)\n\tc.Assert(version, Equals, \"1.0\")\n}", "func mockServer(settings serverSettings) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tspecVersion := req.URL.Query().Get(\"specversion\")\n\t\tspecVersionInt, err := strconv.Atoi(specVersion)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tw.Write([]byte(\"Request had invalid spec version: \" + specVersion))\n\t\t\treturn\n\t\t}\n\t\tlistVersion := req.URL.Query().Get(\"listversion\")\n\t\tlistVersionInt, err := strconv.Atoi(listVersion)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\tw.Write([]byte(\"Request had invalid version: \" + listVersion))\n\t\t\treturn\n\t\t}\n\t\tif listVersionInt == 0 {\n\t\t\tlistVersionInt = settings.vendorListLatestVersion\n\t\t}\n\t\tspecVersionVendorLists, ok := settings.vendorLists[specVersionInt]\n\t\tif !ok {\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\tw.Write([]byte(\"Version not found: spec version \" + specVersion + \" list version \" + listVersion))\n\t\t\treturn\n\t\t}\n\t\tresponse, ok := specVersionVendorLists[listVersionInt]\n\t\tif !ok {\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t\tw.Write([]byte(\"Version not found: \" + listVersion))\n\t\t\treturn\n\t\t}\n\t\tw.Write([]byte(response))\n\t}\n}", "func GetMockAppVersionList() []models.Version {\n\tversions := []models.Version{\n\t\tmodels.Version{\n\t\t\tID: \"55ebd387-9c68-4137-a367-a12025cc2cdb\",\n\t\t\tVersion: \"1.0\",\n\t\t\tAppID: \"com.aerogear.mobile_app_one\",\n\t\t\tDisabledMessage: \"Please contact an administrator\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 1,\n\t\t\tNumOfAppLaunches: 2,\n\t\t},\n\t\tmodels.Version{\n\t\t\tID: \"59ebd387-9c68-4137-a367-a12025cc1cdb\",\n\t\t\tVersion: \"1.1\",\n\t\t\tAppID: \"com.aerogear.mobile_app_one\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 0,\n\t\t\tNumOfAppLaunches: 0,\n\t\t},\n\t\tmodels.Version{\n\t\t\tID: \"59dbd387-9c68-4137-a367-a12025cc2cdb\",\n\t\t\tVersion: \"1.0\",\n\t\t\tAppID: \"com.aerogear.mobile_app_two\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 0,\n\t\t\tNumOfAppLaunches: 0,\n\t\t},\n\t}\n\n\treturn versions\n}", "func (_MetaObject *MetaObjectCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _MetaObject.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestGetVersion(t *testing.T) {\n\n\tversion, err := GetVersion()\n\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\n\tif version != \"v1\"{\n\t\tt.Errorf(\"app version not match: %s, expect: %s.\", version, \"v1\")\n\t}\n\n\tfmt.Println(version)\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func (_HelloWorld *HelloWorldCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _HelloWorld.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func (_BaseContentFactory *BaseContentFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockVersion) UpdateVersion(keyName, newVersion string) error {\n\targs := m.Called()\n\treturn args.Error(0)\n}", "func (_BaseLibrary *BaseLibraryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestSetGetGoodArgsFull(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGetGoodArgsFull\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2017-11-21T10:29:49.816Z\"),\n\t[]byte(\"digest1\"),[]byte(\"E0nioxbCYD5AlzGWXDDDl0Gt5AAKv3ppKt4XMhE1rfo\"),\n\t[]byte(\"digest2\"),[]byte(\"xLrbWN5QJBJUAsdevfrxGlN3o0p8VZMnFFnV9iMll5o\"),\n\t[]byte(\"digest3\"),[]byte(\"THIS_IS_DIGEST_3\"),\n\t[]byte(\"digest4\"),[]byte(\"THIS_IS_DIGEST_4\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n\tresGet := stub.MockInvoke(\"1\", [][]byte{[]byte(\"get\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\")})\n\tif resGet.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(resGet.Message))\n\t\tt.FailNow()\n\t}\n}", "func (_Accessible *AccessibleCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Accessible.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockChefIngesterServer) GetVersion(arg0 context.Context, arg1 *VersionRequest) (*Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *cachestub) RecordVersion(token, version string) (*cache.Record, error) {\n\treturn &cache.Record{}, nil\n}", "func (_BaseContentFactoryExt *BaseContentFactoryExtCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactoryExt.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (i *MockOtherDataItem) GetVersion() int {\n\treturn i.Version\n}", "func buildMockVulnClientKey(version string, os string, packages []string) string {\n\tpkgs := strings.Join(packages, \"\")\n\treturn strings.Join([]string{version, os, pkgs}, \"/\")\n}", "func (_m *Vcs) LatestRevision(file string) (string, error) {\n\tret := _m.Called(file)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(file)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(file)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (p Reviewer) Version() (int, int, int) {\n return 0,0,0\n}", "func TestVersion(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, \"\")\n\n\t// There's not much we can robustly assert about the actual version.\n\twant := debug.Version() // e.g. \"master\"\n\n\t// basic\n\t{\n\t\tres := gopls(t, tree, \"version\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(want)\n\t}\n\n\t// -json flag\n\t{\n\t\tres := gopls(t, tree, \"version\", \"-json\")\n\t\tres.checkExit(true)\n\t\tvar v debug.ServerVersion\n\t\tif res.toJSON(&v) {\n\t\t\tif v.Version != want {\n\t\t\t\tt.Errorf(\"expected Version %q, got %q (%v)\", want, v.Version, res)\n\t\t\t}\n\t\t}\n\t}\n}", "func (_AggregatorV2V3Interface *AggregatorV2V3InterfaceCallerSession) Version() (*big.Int, error) {\n\treturn _AggregatorV2V3Interface.Contract.Version(&_AggregatorV2V3Interface.CallOpts)\n}", "func (_Contract *ContractCaller) Version(opts *bind.CallOpts) ([4]byte, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([4]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([4]byte)).(*[4]byte)\n\n\treturn out0, err\n\n}", "func (i *MockDataItem) GetVersion() int {\n\treturn i.Version\n}", "func (m *MockDatasetClient) GetVersion(ctx context.Context, userAuthToken, serviceAuthToken, downloadServiceToken, collectionID, datasetID, edition, version string) (dataset.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", ctx, userAuthToken, serviceAuthToken, downloadServiceToken, collectionID, datasetID, edition, version)\n\tret0, _ := ret[0].(dataset.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Version) VersionFormatter(_a0 string) (string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *LambdaAPI) ListVersionsByFunction(_a0 *lambda.ListVersionsByFunctionInput) (*lambda.ListVersionsByFunctionOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.ListVersionsByFunctionOutput\n\tif rf, ok := ret.Get(0).(func(*lambda.ListVersionsByFunctionInput) *lambda.ListVersionsByFunctionOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.ListVersionsByFunctionOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.ListVersionsByFunctionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockDatasetClient) GetVersion(arg0 context.Context, arg1, arg2, arg3, arg4, arg5, arg6, arg7 string) (dataset.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7)\n\tret0, _ := ret[0].(dataset.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_Editable *EditableCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Editable.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockChefIngesterClient) GetVersion(ctx context.Context, in *VersionRequest, opts ...grpc.CallOption) (*Version, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetVersion\", varargs...)\n\tret0, _ := ret[0].(*Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *mockStore) GetCurrentVersion() (time.Time, error) {\n\treturn m.version, nil\n}", "func TestAlfredVersion(t *testing.T) {\n\ttests := []struct {\n\t\tdir string\n\t\tenvvar string\n\t\tx int\n\t\terr bool\n\t}{\n\t\t{rootDirV3, \"\", 3, false},\n\t\t{rootDirV3, \"3\", 3, false},\n\t\t{rootDirV3, \"4\", 4, false},\n\t\t{rootDirV4, \"\", 4, false},\n\t\t{rootDirV4, \"4\", 4, false},\n\t\t{\".\", \"\", 0, true},\n\t\t{\".\", \"four\", 0, true},\n\t}\n\n\tfor _, td := range tests {\n\t\ttd := td // pin variable\n\t\tt.Run(fmt.Sprintf(\"dir=%q, env=%q\", td.dir, td.envvar), func(t *testing.T) {\n\t\t\twithEnv(map[string]string{\n\t\t\t\t\"alfred_version\": td.envvar,\n\t\t\t\t// ensure defaults\n\t\t\t\t\"alfred_workflow_data\": \"\",\n\t\t\t\t\"alfred_workflow_cache\": \"\",\n\t\t\t}, func() {\n\t\t\t\tinfo, err := NewInfo(LibDir(td.dir), testPlist)\n\t\t\t\tif td.err {\n\t\t\t\t\tassert.NotNil(t, err, \"expected error\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trequire.Nil(t, err, \"unexpected error\")\n\t\t\t\tassert.Equal(t, td.x, info.AlfredMajorVersion, \"unexpected version\")\n\t\t\t})\n\t\t})\n\t}\n}", "func TestMakeUpVersion(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tmajor uint8\n\t\tminor uint8\n\t\tfix uint8\n\t\twant uint32\n\t}{\n\t\t{\n\t\t\tname: \"MakeUpversionTest\",\n\t\t\tmajor: FixVersion,\n\t\t\tminor: MinorVersion,\n\t\t\tfix: FixVersion,\n\t\t\twant: 16843008,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := makeUpVersion(tt.major, tt.minor, tt.fix); got != tt.want {\n\t\t\t\tt.Errorf(\"makeUpVersion() = %v, majorVersion %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *MockVersionInfoDao) GetLatestScsVersion(sid string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetLatestScsVersion\", sid)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *MockRepoManager) mockUpdate() {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.updateCount++\n}", "func TestSuccessfullyUpdateVersion(t *testing.T) {\n\tids, err := helpers.GetIDsAndTimestamps()\n\tif err != nil {\n\t\tlog.ErrorC(\"unable to generate mongo timestamp\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tdatasetAPI := httpexpect.New(t, cfg.DatasetAPIURL)\n\n\tneo4JStore, err := neo4j.NewDatastore(cfg.Neo4jAddr, \"\", neo4j.GenericHierarchyCPIHTestData)\n\tif err != nil {\n\t\tt.Errorf(\"unable to connect to neo4j. error: [%v]\\n\", err)\n\t\tlog.ErrorC(\"unable to connect to neo4j\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tConvey(\"Given an unpublished dataset, edition and version\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceEditionConfirmed, ids.UniqueTimestamp, 1)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceEditionConfirmed)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update meta data against the version resource\", func() {\n\t\t\tConvey(\"Then version resource is updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionMetaDataJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.ReleaseDate, ShouldEqual, \"2018-11-11\")\n\t\t\t\tSo(len(*updatedVersion.UsageNotes), ShouldEqual, 2)\n\n\t\t\t\tSo((*updatedVersion.UsageNotes)[0].Title, ShouldEqual, \"Coefficients of variation\")\n\n\t\t\t\talert := mongo.Alert{\n\t\t\t\t\tDescription: \"All data entries (observations) for Plymouth have been updated\",\n\t\t\t\t\tDate: \"2017-04-05\",\n\t\t\t\t\tType: \"Correction\",\n\t\t\t\t}\n\n\t\t\t\talertList := &[]mongo.Alert{alert}\n\n\t\t\t\tSo(updatedVersion.Alerts, ShouldResemble, alertList)\n\n\t\t\t\tlatestChange := mongo.LatestChange{\n\t\t\t\t\tDescription: \"change to the period frequency from quarterly to monthly\",\n\t\t\t\t\tName: \"Changes to the period frequency\",\n\t\t\t\t\tType: \"Summary of Changes\",\n\t\t\t\t}\n\n\t\t\t\tlatestChangesList := []mongo.LatestChange{latestChange}\n\n\t\t\t\tSo(updatedVersion.LatestChanges, ShouldResemble, latestChangesList)\n\n\t\t\t\tSo(updatedVersion.Links.Spatial.HRef, ShouldEqual, \"http://ons.gov.uk/new-geography-list\")\n\n\t\t\t\t// Check self link does not update - the only link that can be updated is `spatial`\n\t\t\t\tSo(updatedVersion.Links.Self.HRef, ShouldNotEqual, \"http://bogus/bad-link\")\n\n\t\t\t\ttemporal := mongo.TemporalFrequency{\n\t\t\t\t\tStartDate: \"2014-11-11\",\n\t\t\t\t\tEndDate: \"2017-11-11\",\n\t\t\t\t\tFrequency: \"monthly\",\n\t\t\t\t}\n\n\t\t\t\ttemporalList := []mongo.TemporalFrequency{temporal}\n\n\t\t\t\tSo(updatedVersion.Temporal, ShouldResemble, temporalList)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of associated\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToAssociatedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"associated\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"associated\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedWithCollectionIDJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated, and CollectionID removed\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tlog.Debug(\"edition id\", log.Data{\"edition_id\": ids.EditionUnpublished})\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, and CollectionID removed\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tinstanceProps, err := neo4JStore.GetInstanceProperties(ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"failed to get properties from neo4j instance node\", err, nil)\n\t\t\t\t\tt.FailNow()\n\t\t\t\t}\n\n\t\t\t\tSo(instanceProps[\"is_published\"], ShouldBeTrue)\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceEditionConfirmed); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given an unpublished dataset, edition and a version that has been associated\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 2)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\t// TODO Remove skipped tests when code has been refactored (and hence fixed)\n\t\t// 1 test skipped\n\t\tSkipConvey(\"When a PUT request to update version resource to remove collection id\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated accordingly and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionFromAssociatedToEditionConfirmedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"edition-confirmed\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"edition-confirmed\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetAssociated+\"/editions/2018/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetAssociated, 0))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given a published dataset and edition, and a version that has been associated\", t, func() {\n\t\tedition := \"2017\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetPublished, ids.EditionPublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 3)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.Fail()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetPublished, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionPublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetPublished+\"/editions/2017/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetPublished)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetPublished, 1))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n}", "func (m *MockCredHub) GetLatestVersion(arg0 string) (credentials.Credential, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetLatestVersion\", arg0)\n\tret0, _ := ret[0].(credentials.Credential)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_TTFT20 *TTFT20Caller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _TTFT20.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func MockPrepareRelease(release *Release) {\n\trelease.SetDefaultRegionAccount(to.Strp(\"region\"), to.Strp(\"account\"))\n\trelease.SetDefaults()\n\trelease.SetUUID()\n}", "func (s *server) Version(args interface{}, resp *string) error {\n\t*resp = s.impl.Version()\n\treturn nil\n}" ]
[ "0.6758605", "0.67251813", "0.67000055", "0.6609332", "0.64761645", "0.6366889", "0.63209385", "0.6299836", "0.6254888", "0.6251358", "0.62467533", "0.6206996", "0.61766696", "0.61749876", "0.6163177", "0.61334395", "0.61285645", "0.6045214", "0.60311085", "0.59991527", "0.59780043", "0.5972327", "0.5809572", "0.5763437", "0.5735553", "0.5733567", "0.56698334", "0.5639091", "0.56316745", "0.5614854", "0.5565358", "0.55575854", "0.5550443", "0.5540317", "0.55292064", "0.5526643", "0.55252606", "0.5512674", "0.55123496", "0.54945344", "0.5493332", "0.54916865", "0.5486929", "0.54759943", "0.54744834", "0.5471515", "0.54630345", "0.5447711", "0.5442445", "0.54387516", "0.5430792", "0.54232603", "0.5413834", "0.54056025", "0.5401446", "0.53893965", "0.53862745", "0.53707683", "0.536795", "0.5366152", "0.5360527", "0.5358357", "0.5352271", "0.5346502", "0.5332647", "0.5322228", "0.5317006", "0.531597", "0.53057957", "0.53049374", "0.52958095", "0.52561265", "0.5250947", "0.52503437", "0.5249327", "0.52156156", "0.5215192", "0.5192897", "0.51724225", "0.5171494", "0.51644033", "0.51619583", "0.5146279", "0.51450366", "0.5135991", "0.51353836", "0.5128635", "0.512798", "0.51223546", "0.51203734", "0.51174253", "0.51094663", "0.5107706", "0.5101336", "0.50998956", "0.50990653", "0.509501", "0.50907755", "0.50850403", "0.5082755" ]
0.6841355
0
clearUncommittedEvents provides a mock function with given fields:
func (_m *MockAggregate) clearUncommittedEvents() { _m.Called() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockAggregate) getUncommittedEvents() []Event {\n\tret := _m.Called()\n\n\tvar r0 []Event\n\tif rf, ok := ret.Get(0).(func() []Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockEventDao) UnfinishedEvents(target, targetID string, optTypes ...string) ([]*model.ServiceEvent, error) {\n\tvarargs := []interface{}{target, targetID}\n\tfor _, a := range optTypes {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UnfinishedEvents\", varargs...)\n\tret0, _ := ret[0].([]*model.ServiceEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Entity) ClearEvents() {\n\t_m.Called()\n}", "func (state *MockedChangesetSyncState) Unmock() {\n\tgit.Mocks.ExecReader = state.execReader\n\tgit.Mocks.ResolveRevision = state.resolveRevision\n\trepoupdater.MockRepoLookup = state.mockRepoLookup\n}", "func (_m *MockHistoryEngine) ReapplyEvents(ctx context.Context, domainUUID string, workflowID string, events []*shared.HistoryEvent) error {\n\tret := _m.Called(domainUUID, workflowID, events)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string, []*shared.HistoryEvent) error); ok {\n\t\tr0 = rf(domainUUID, workflowID, events)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockRepoSyncInfoKeeper) UnTrack(repos string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UnTrack\", repos)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (*FakeReconcilerClient) UnsubscribeFromEvents(events chan interface{}) {\n\n}", "func (_m *MockHistoryer) Erase(tx *dbutil.Tx) error {\n\tret := _m.Called(tx)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*dbutil.Tx) error); ok {\n\t\tr0 = rf(tx)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *LogPollerWrapper) LatestEvents() ([]types.OracleRequest, []types.OracleResponse, error) {\n\tret := _m.Called()\n\n\tvar r0 []types.OracleRequest\n\tvar r1 []types.OracleResponse\n\tvar r2 error\n\tif rf, ok := ret.Get(0).(func() ([]types.OracleRequest, []types.OracleResponse, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() []types.OracleRequest); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]types.OracleRequest)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() []types.OracleResponse); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).([]types.OracleResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(2).(func() error); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func MockEvents() []optic.Event {\n\tevents := make([]optic.Event, 0)\n\tevents = append(events, TestRaw([]byte(\"raw\")))\n\tevents = append(events, TestMetric(1.0))\n\tevents = append(events, TestLogLine(\"logline\"))\n\treturn events\n}", "func TestActiveMultiEvent_Deactivate(t *testing.T) {\r\n\tnumber := 10\r\n\tvar events []*ActiveEvent\r\n\tvar mock []*mockUnixHelper\r\n\r\n\tfor i := 0; i < number; i++ {\r\n\t\tunixMock := &mockUnixHelper{}\r\n\t\tnewActive := &ActiveEvent{FileDescriptor: i, unix: unixMock}\r\n\t\tunixMock.On(\"close\", i).Return(nil).Once()\r\n\t\tevents = append(events, newActive)\r\n\t\tmock = append(mock, unixMock)\r\n\t}\r\n\r\n\tnewActiveMulti := ActiveMultiEvent{events: events}\r\n\tnewActiveMulti.Deactivate()\r\n\r\n\trequire.Nil(t, newActiveMulti.events)\r\n\tfor _, event := range events {\r\n\t\trequire.Nil(t, event)\r\n\t}\r\n\tfor _, m := range mock {\r\n\t\tm.AssertExpectations(t)\r\n\t}\r\n}", "func (mock *GitModuleControllerMock) OnRemoveCalls() []struct {\n\tCtx context.Context\n\tName string\n\tSync v1.GitModuleHandler\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tName string\n\t\tSync v1.GitModuleHandler\n\t}\n\tlockGitModuleControllerMockOnRemove.RLock()\n\tcalls = mock.calls.OnRemove\n\tlockGitModuleControllerMockOnRemove.RUnlock()\n\treturn calls\n}", "func (_m *MockENotifyingList) Clear() {\n\t_m.Called()\n}", "func (m *MockCommand) UnsubscribeEvent(body string) error {\n\tret := m.ctrl.Call(m, \"UnsubscribeEvent\", body)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *TeamStore) RemoveAllMembersByUser(userID string) error {\n\tret := _m.Called(userID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(userID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *mockStateBuilder) applyEvents(domainID string, requestID string, execution shared.WorkflowExecution, _a3 []*shared.HistoryEvent,\n\tnewRunHistory []*shared.HistoryEvent, eventStoreVersion, newRunEventStoreVersion int32, newRunNDC bool) (*shared.HistoryEvent, *decisionInfo, mutableState, error) {\n\n\tret := _m.Called(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\n\tvar r0 *shared.HistoryEvent\n\tif rf, ok := ret.Get(0).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *shared.HistoryEvent); ok {\n\t\tr0 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*shared.HistoryEvent)\n\t\t}\n\t}\n\n\tvar r1 *decisionInfo\n\tif rf, ok := ret.Get(1).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *decisionInfo); ok {\n\t\tr1 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*decisionInfo)\n\t\t}\n\t}\n\n\tvar r2 mutableState\n\tif rf, ok := ret.Get(2).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) mutableState); ok {\n\t\tr2 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(mutableState)\n\t\t}\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) error); ok {\n\t\tr3 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (_m *TeamStore) RemoveAllMembersByTeam(teamID string) error {\n\tret := _m.Called(teamID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(teamID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (mock *FilterStoreMock) PutStateAsEmptyCalls() []struct {\n\tCtx context.Context\n\tFilterJobID string\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tFilterJobID string\n\t}\n\tmock.lockPutStateAsEmpty.RLock()\n\tcalls = mock.calls.PutStateAsEmpty\n\tmock.lockPutStateAsEmpty.RUnlock()\n\treturn calls\n}", "func (mock *RepositoryMock) GetUnprocessedEventsCalls() []struct {\n\tCtx context.Context\n\tLimit uint64\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tLimit uint64\n\t}\n\tmock.lockGetUnprocessedEvents.RLock()\n\tcalls = mock.calls.GetUnprocessedEvents\n\tmock.lockGetUnprocessedEvents.RUnlock()\n\treturn calls\n}", "func (_m *DBClient) DeleteNotificationsOld(age int) error {\n\tret := _m.Called(age)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(int) error); ok {\n\t\tr0 = rf(age)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *CloudWatchEventsModelAPI) DeleteCloudWatchEvents(event types.Event) error {\n\tret := _m.Called(event)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(types.Event) error); ok {\n\t\tr0 = rf(event)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *ChannelStore) ClearSidebarOnTeamLeave(userID string, teamID string) error {\n\tret := _m.Called(userID, teamID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string) error); ok {\n\t\tr0 = rf(userID, teamID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *EventProviderMock) GetStorageEvents(meta *types.Metadata, blockHash types.Hash) (*types.StorageDataRaw, error) {\n\tret := _m.Called(meta, blockHash)\n\n\tvar r0 *types.StorageDataRaw\n\tif rf, ok := ret.Get(0).(func(*types.Metadata, types.Hash) *types.StorageDataRaw); ok {\n\t\tr0 = rf(meta, blockHash)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*types.StorageDataRaw)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*types.Metadata, types.Hash) error); ok {\n\t\tr1 = rf(meta, blockHash)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *StoreServiceMock) RemoveCalls() []struct {\n\tEntry ytfeed.Entry\n} {\n\tvar calls []struct {\n\t\tEntry ytfeed.Entry\n\t}\n\tmock.lockRemove.RLock()\n\tcalls = mock.calls.Remove\n\tmock.lockRemove.RUnlock()\n\treturn calls\n}", "func (mock *FilterStoreMock) PutStateAsEmptyCalls() []struct {\n\tFilterJobID string\n} {\n\tvar calls []struct {\n\t\tFilterJobID string\n\t}\n\tlockFilterStoreMockPutStateAsEmpty.RLock()\n\tcalls = mock.calls.PutStateAsEmpty\n\tlockFilterStoreMockPutStateAsEmpty.RUnlock()\n\treturn calls\n}", "func (m *MockCallback) OnRemoveAll() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnRemoveAll\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (a *BaseAggregateSourced) ClearEvents() {\n\ta.events = nil\n}", "func (_m *MockHistoryEngine) ReplicateRawEvents(ctx context.Context, request *gohistory.ReplicateRawEventsRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.ReplicateRawEventsRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Entity) Events() []core.Event {\n\tret := _m.Called()\n\n\tvar r0 []core.Event\n\tif rf, ok := ret.Get(0).(func() []core.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]core.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *Consumer) Unassign() error {\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}", "func (_m *Blockchain) OnCommit(b api.Block) ([]api.Block, *treemap.Map, error) {\n\tret := _m.Called(b)\n\n\tvar r0 []api.Block\n\tif rf, ok := ret.Get(0).(func(api.Block) []api.Block); ok {\n\t\tr0 = rf(b)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]api.Block)\n\t\t}\n\t}\n\n\tvar r1 *treemap.Map\n\tif rf, ok := ret.Get(1).(func(api.Block) *treemap.Map); ok {\n\t\tr1 = rf(b)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*treemap.Map)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(api.Block) error); ok {\n\t\tr2 = rf(b)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (_m *TeamStore) ClearAllCustomRoleAssignments() error {\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}", "func (_m *ChannelStore) RemoveAllDeactivatedMembers(channelID string) error {\n\tret := _m.Called(channelID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(channelID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockORM) Omit(columns ...string) ORM {\n\tret := _m.Called(columns)\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func(...string) ORM); ok {\n\t\tr0 = rf(columns...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *VolumeDriver) Unset() error {\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}", "func TestUpdateSubscriptionDeleteFilter(t *testing.T) {\n\trepository, mock := initTest(t)\n\n\t// subscription to update\n\tsubscription := models.Subscription{\n\t\tID: \"42\",\n\t\tCallbackURL: \"url\",\n\t\tCallbackType: models.HTTP,\n\t\tFilters: map[models.EventType]models.Filter{\n\t\t\tmodels.DirectoryBlockCommit: {Filtering: fmt.Sprintf(\"no change filtering\")},\n\t\t},\n\t}\n\tsubscriptionContext := &models.SubscriptionContext{\n\t\tSubscription: subscription,\n\t\tFailures: 0,\n\t}\n\n\tcolumns := []string{\"failures\", \"callback\", \"callback_type\", \"status\", \"info\", \"access_token\", \"username\", \"password\", \"event_type\", \"filtering\"}\n\tmock.ExpectQuery(`SELECT failures, callback, callback_type, status, info, access_token, username, password, event_type, filtering FROM subscriptions LEFT JOIN filters ON filters.subscription = subscriptions.id WHERE subscriptions.id = \\?`).\n\t\tWithArgs(subscription.ID).\n\t\tWillReturnRows(sqlmock.NewRows(columns).\n\t\t\tAddRow(subscriptionContext.Failures, \"url-change\", subscription.CallbackType, subscription.SubscriptionStatus, subscription.SubscriptionInfo, subscription.Credentials.AccessToken, subscription.Credentials.BasicAuthUsername, subscription.Credentials.BasicAuthPassword, models.DirectoryBlockCommit, \"no change filtering\").\n\t\t\tAddRow(subscriptionContext.Failures, \"url-change\", subscription.CallbackType, subscription.SubscriptionStatus, subscription.SubscriptionInfo, subscription.Credentials.AccessToken, subscription.Credentials.BasicAuthUsername, subscription.Credentials.BasicAuthPassword, models.ChainCommit, \"this will be deleted\"))\n\n\tmock.ExpectBegin()\n\tmock.ExpectExec(`UPDATE subscriptions`).WithArgs(subscriptionContext.Failures, subscription.CallbackURL, subscription.CallbackType, subscription.SubscriptionStatus, subscription.SubscriptionInfo, subscription.Credentials.AccessToken, subscription.Credentials.BasicAuthUsername, subscription.Credentials.BasicAuthPassword, subscription.ID).WillReturnResult(sqlmock.NewResult(42, 1))\n\tmock.ExpectExec(`DELETE FROM filters`).WithArgs(subscription.ID, models.ChainCommit).WillReturnResult(sqlmock.NewResult(42, 1))\n\tmock.ExpectCommit()\n\n\t// now we execute our method\n\tupdatedSubscriptionContext, err := repository.UpdateSubscription(subscriptionContext)\n\tif err != nil {\n\t\tt.Errorf(\"error was not expected creating subscription: %s\", err)\n\t}\n\n\tassertSubscription(t, subscriptionContext, updatedSubscriptionContext)\n\n\t// we make sure that all expectations were met\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"there were unfulfilled expectations: %s\", err)\n\t}\n}", "func (_m *Consumer) Unsubscribe() error {\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}", "func (m *MockClient) ClearMilestone(org, repo string, num int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClearMilestone\", org, repo, num)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockStudyServiceApiClient) UnpublishSurvey(arg0 context.Context, arg1 *api.SurveyReferenceRequest, arg2 ...grpc.CallOption) (*api.ServiceStatus, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UnpublishSurvey\", varargs...)\n\tret0, _ := ret[0].(*api.ServiceStatus)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStream) RemoveEventListener(streamEventListener types.StreamEventListener) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"RemoveEventListener\", streamEventListener)\n}", "func (_m *MockHistoryEngine) ReplicateEvents(ctx context.Context, request *gohistory.ReplicateEventsRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.ReplicateEventsRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *JetReleaserMock) MinimockCloseAllUntilInspect() {\n\tfor _, e := range m.CloseAllUntilMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to JetReleaserMock.CloseAllUntil with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.CloseAllUntilMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCloseAllUntilCounter) < 1 {\n\t\tif m.CloseAllUntilMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to JetReleaserMock.CloseAllUntil\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to JetReleaserMock.CloseAllUntil with params: %#v\", *m.CloseAllUntilMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcCloseAllUntil != nil && mm_atomic.LoadUint64(&m.afterCloseAllUntilCounter) < 1 {\n\t\tm.t.Error(\"Expected call to JetReleaserMock.CloseAllUntil\")\n\t}\n}", "func (_m *MockMessageProducer) Events() chan kafka.Event {\n\tret := _m.Called()\n\n\tvar r0 chan kafka.Event\n\tif rf, ok := ret.Get(0).(func() chan kafka.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan kafka.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockNotificationEventDao) GetNotificationEventNotHandle() ([]*model.NotificationEvent, error) {\n\tret := m.ctrl.Call(m, \"GetNotificationEventNotHandle\")\n\tret0, _ := ret[0].([]*model.NotificationEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestRemoveEventHub(t *testing.T) {\n\t// Test Data\n\tnamespaceName1 := \"TestNamespaceName1\"\n\tnamespaceName2 := \"TestNamespaceName2\"\n\n\t// Create A Mock HubManager\n\tmockHubManager := &MockHubManager{}\n\n\t// Replace The NewHubManagerFromConnectionString Wrapper To Provide Mock Implementation & Defer Reset\n\tnewHubManagerFromConnectionStringWrapperPlaceholder := NewHubManagerFromConnectionStringWrapper\n\tNewHubManagerFromConnectionStringWrapper = func(connectionString string) (managerInterface HubManagerInterface, e error) {\n\t\treturn mockHubManager, nil\n\t}\n\tdefer func() { NewHubManagerFromConnectionStringWrapper = newHubManagerFromConnectionStringWrapperPlaceholder }()\n\n\t// Create A Test Logger\n\tlogger := logtesting.TestLogger(t).Desugar()\n\n\t// Create Test Namespaces\n\tnamespace1, err := createTestNamespaceWithCount(logger, namespaceName1, 1)\n\tassert.NotNil(t, namespace1)\n\tassert.Nil(t, err)\n\tnamespace2, err := createTestNamespaceWithCount(logger, namespaceName2, 1)\n\tassert.NotNil(t, namespace2)\n\tassert.Nil(t, err)\n\n\t// Create The Cache's EventHub Map\n\teventhubMap := make(map[string]*Namespace)\n\teventhubMap[namespaceName1] = namespace1\n\teventhubMap[namespaceName2] = namespace2\n\n\t// Create A Cache To Test\n\tcache := &Cache{\n\t\tlogger: logger,\n\t\teventhubMap: eventhubMap,\n\t}\n\n\t// Perform The Test\n\tcache.RemoveEventHub(context.TODO(), namespaceName2)\n\n\t// Verify The Results\n\tassert.Len(t, cache.eventhubMap, 1)\n\tassert.Nil(t, cache.eventhubMap[namespaceName2])\n\tassert.Equal(t, namespaceName1, cache.eventhubMap[namespaceName1].Name)\n\tassert.Nil(t, cache.eventhubMap[namespaceName2])\n\tassert.Equal(t, 1, namespace1.Count)\n\tassert.Equal(t, 0, namespace2.Count)\n}", "func (_m *CloudWatchEventsModelAPI) UpdateCloudWatchEvents(event types.Event) error {\n\tret := _m.Called(event)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(types.Event) error); ok {\n\t\tr0 = rf(event)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Subscriber) Unsubscribe() error {\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}", "func (_m *ChannelStore) ClearAllCustomRoleAssignments() error {\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}", "func (_m *MockHistoryEngine) RemoveSignalMutableState(ctx context.Context, request *gohistory.RemoveSignalMutableStateRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.RemoveSignalMutableStateRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockCallback) OnRemove(arg0 int) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OnRemove\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockGeneralRepository) GetEvents(arg0 []models.SubscriptionRequest, arg1, arg2 int64) ([]models.Event, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetEvents\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]models.Event)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockOobService) UnregisterMsgEvent(arg0 chan<- service.StateMsg) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UnregisterMsgEvent\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func Unset() {\n\tmock = time.Time{}\n}", "func (mock *MailgunMock) UnsubscribeCalls() []struct {\n\tAddress string\n\tTag string\n} {\n\tvar calls []struct {\n\t\tAddress string\n\t\tTag string\n\t}\n\tlockMailgunMockUnsubscribe.RLock()\n\tcalls = mock.calls.Unsubscribe\n\tlockMailgunMockUnsubscribe.RUnlock()\n\treturn calls\n}", "func (_m *TeamStore) RemoveMembers(teamID string, userIds []string) error {\n\tret := _m.Called(teamID, userIds)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, []string) error); ok {\n\t\tr0 = rf(teamID, userIds)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Backend) InternalVodRemoveRecords(ctx context.Context, request *models.InternalVodRemoveRecordsRequest) (*models.VodsResponse, error) {\n\tret := _m.Called(ctx, request)\n\n\tvar r0 *models.VodsResponse\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.InternalVodRemoveRecordsRequest) *models.VodsResponse); ok {\n\t\tr0 = rf(ctx, request)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*models.VodsResponse)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *models.InternalVodRemoveRecordsRequest) error); ok {\n\t\tr1 = rf(ctx, request)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *StoreServiceMock) RemoveOldCalls() []struct {\n\tChannelID string\n\tKeep int\n} {\n\tvar calls []struct {\n\t\tChannelID string\n\t\tKeep int\n\t}\n\tmock.lockRemoveOld.RLock()\n\tcalls = mock.calls.RemoveOld\n\tmock.lockRemoveOld.RUnlock()\n\treturn calls\n}", "func (_m *Consumer) Events() chan kafka.Event {\n\tret := _m.Called()\n\n\tvar r0 chan kafka.Event\n\tif rf, ok := ret.Get(0).(func() chan kafka.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan kafka.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *Route53API) WaitUntilResourceRecordSetsChanged(_a0 *route53.GetChangeInput) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*route53.GetChangeInput) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockTx) RemovePatientsByClient(_a0 uint, _a1 ...bool) error {\n\t_va := make([]interface{}, len(_a1))\n\tfor _i := range _a1 {\n\t\t_va[_i] = _a1[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _a0)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(uint, ...bool) error); ok {\n\t\tr0 = rf(_a0, _a1...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *InviteeMutation) ClearEvents() {\n\tm.clearedevents = true\n}", "func (_m *Watcher) Events() chan fsnotify.Event {\n\tret := _m.Called()\n\n\tvar r0 chan fsnotify.Event\n\tif rf, ok := ret.Get(0).(func() chan fsnotify.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan fsnotify.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *ChannelStore) RemoveMembers(channelID string, userIds []string) error {\n\tret := _m.Called(channelID, userIds)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, []string) error); ok {\n\t\tr0 = rf(channelID, userIds)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockEventBus) RemoveHandler(arg0 members.Handler) {\n\tm.ctrl.Call(m, \"RemoveHandler\", arg0)\n}", "func (mock *EnvironmentMock) RemoveHeaderCalls() []struct {\n\tKey string\n} {\n\tvar calls []struct {\n\t\tKey string\n\t}\n\tlockEnvironmentMockRemoveHeader.RLock()\n\tcalls = mock.calls.RemoveHeader\n\tlockEnvironmentMockRemoveHeader.RUnlock()\n\treturn calls\n}", "func (_m *DB) SaveEvent(topic string, eventData interface{}, inTx func() error) error {\n\tret := _m.Called(topic, eventData, inTx)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, interface{}, func() error) error); ok {\n\t\tr0 = rf(topic, eventData, inTx)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockCache) Evict() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Evict\")\n}", "func (m *MockEventRepository) Remove(arg0 sweeper.Snowflake) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Remove\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *RunInterface) CreateLastEvent() (int, error) {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockManager) RemoveStateFile() error {\n\tret := m.ctrl.Call(m, \"RemoveStateFile\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mock *QueuerMock) UnsubCalls() []struct {\n\tTopic string\n} {\n\tvar calls []struct {\n\t\tTopic string\n\t}\n\tmock.lockUnsub.RLock()\n\tcalls = mock.calls.Unsub\n\tmock.lockUnsub.RUnlock()\n\treturn calls\n}", "func (c MockClient) VerifyAndClear(matcher RequestMatcher, times Times) error {\n\terr_verify := c.Verify(matcher, times)\n\terr_clear := c.Clear(matcher)\n\tif err_verify != nil {\n\t\treturn stacktrace.Propagate(err_verify, \"could not verify\")\n\t}\n\tif err_clear != nil {\n\t\treturn stacktrace.Propagate(err_clear, \"could not clear\")\n\t}\n\treturn nil\n}", "func (m *MockCache) PurgeOrderBookRows() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"PurgeOrderBookRows\")\n}", "func (_m *DBClient) CleanupOld(age int) error {\n\tret := _m.Called(age)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(int) error); ok {\n\t\tr0 = rf(age)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockTx) Commit() error {\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}", "func (mock *SessionRepositoryMock) RemoveCalls() []struct {\n\tSession string\n} {\n\tvar calls []struct {\n\t\tSession string\n\t}\n\tlockSessionRepositoryMockRemove.RLock()\n\tcalls = mock.calls.Remove\n\tlockSessionRepositoryMockRemove.RUnlock()\n\treturn calls\n}", "func (m *MockMembers) DispatchEvent(arg0 members.Event) error {\n\tret := m.ctrl.Call(m, \"DispatchEvent\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestPost_BBServerPullClosed(t *testing.T) {\n\tcases := []struct {\n\t\theader string\n\t}{\n\t\t{\n\t\t\t\"pr:deleted\",\n\t\t},\n\t\t{\n\t\t\t\"pr:merged\",\n\t\t},\n\t\t{\n\t\t\t\"pr:declined\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tt.Run(c.header, func(t *testing.T) {\n\t\t\tRegisterMockTestingT(t)\n\t\t\tpullCleaner := emocks.NewMockPullCleaner()\n\t\t\tallowlist, err := events.NewRepoAllowlistChecker(\"*\")\n\t\t\tOk(t, err)\n\t\t\tlogger := logging.NewNoopLogger(t)\n\t\t\tscope, _, _ := metrics.NewLoggingScope(logger, \"null\")\n\t\t\tec := &events_controllers.VCSEventsController{\n\t\t\t\tPullCleaner: pullCleaner,\n\t\t\t\tParser: &events.EventParser{\n\t\t\t\t\tBitbucketUser: \"bb-user\",\n\t\t\t\t\tBitbucketToken: \"bb-token\",\n\t\t\t\t\tBitbucketServerURL: \"https://bbserver.com\",\n\t\t\t\t},\n\t\t\t\tRepoAllowlistChecker: allowlist,\n\t\t\t\tSupportedVCSHosts: []models.VCSHostType{models.BitbucketServer},\n\t\t\t\tVCSClient: nil,\n\t\t\t\tLogger: logger,\n\t\t\t\tScope: scope,\n\t\t\t}\n\n\t\t\t// Build HTTP request.\n\t\t\trequestBytes, err := os.ReadFile(filepath.Join(\"testdata\", \"bb-server-pull-deleted-event.json\"))\n\t\t\t// Replace the eventKey field with our event type.\n\t\t\trequestJSON := strings.Replace(string(requestBytes), `\"eventKey\":\"pr:deleted\",`, fmt.Sprintf(`\"eventKey\":\"%s\",`, c.header), -1)\n\t\t\tOk(t, err)\n\t\t\treq, err := http.NewRequest(\"POST\", \"/events\", bytes.NewBuffer([]byte(requestJSON)))\n\t\t\tOk(t, err)\n\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\treq.Header.Set(\"X-Event-Key\", c.header)\n\t\t\treq.Header.Set(\"X-Request-ID\", \"request-id\")\n\n\t\t\t// Send the request.\n\t\t\tw := httptest.NewRecorder()\n\t\t\tec.Post(w, req)\n\n\t\t\t// Make our assertions.\n\t\t\tResponseContains(t, w, 200, \"Pull request cleaned successfully\")\n\n\t\t\texpRepo := models.Repo{\n\t\t\t\tFullName: \"project/repository\",\n\t\t\t\tOwner: \"project\",\n\t\t\t\tName: \"repository\",\n\t\t\t\tCloneURL: \"https://bb-user:[email protected]/scm/proj/repository.git\",\n\t\t\t\tSanitizedCloneURL: \"https://bb-user:<redacted>@bbserver.com/scm/proj/repository.git\",\n\t\t\t\tVCSHost: models.VCSHost{\n\t\t\t\t\tHostname: \"bbserver.com\",\n\t\t\t\t\tType: models.BitbucketServer,\n\t\t\t\t},\n\t\t\t}\n\t\t\tpullCleaner.VerifyWasCalledOnce().CleanUpPull(expRepo, models.PullRequest{\n\t\t\t\tNum: 10,\n\t\t\t\tHeadCommit: \"2d9fb6b9a46eafb1dcef7b008d1a429d45ca742c\",\n\t\t\t\tURL: \"https://bbserver.com/projects/PROJ/repos/repository/pull-requests/10\",\n\t\t\t\tHeadBranch: \"decline-me\",\n\t\t\t\tBaseBranch: \"main\",\n\t\t\t\tAuthor: \"admin\",\n\t\t\t\tState: models.OpenPullState,\n\t\t\t\tBaseRepo: expRepo,\n\t\t\t})\n\t\t})\n\t}\n}", "func (m *MockClient) UnrequestReview(org, repo string, number int, logins []string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UnrequestReview\", org, repo, number, logins)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *FakeScheduleService) Unpause() error {\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}", "func (mock *MailgunMock) PollEventsCalls() []struct {\n\tIn1 *mailgun.EventsOptions\n} {\n\tvar calls []struct {\n\t\tIn1 *mailgun.EventsOptions\n\t}\n\tlockMailgunMockPollEvents.RLock()\n\tcalls = mock.calls.PollEvents\n\tlockMailgunMockPollEvents.RUnlock()\n\treturn calls\n}", "func (c *Call) Unset() *Call {\n\tvar unlockOnce sync.Once\n\n\tfor _, arg := range c.Arguments {\n\t\tif v := reflect.ValueOf(arg); v.Kind() == reflect.Func {\n\t\t\tpanic(fmt.Sprintf(\"cannot use Func in expectations. Use mock.AnythingOfType(\\\"%T\\\")\", arg))\n\t\t}\n\t}\n\n\tc.lock()\n\tdefer unlockOnce.Do(c.unlock)\n\n\tfoundMatchingCall := false\n\n\t// in-place filter slice for calls to be removed - iterate from 0'th to last skipping unnecessary ones\n\tvar index int // write index\n\tfor _, call := range c.Parent.ExpectedCalls {\n\t\tif call.Method == c.Method {\n\t\t\t_, diffCount := call.Arguments.Diff(c.Arguments)\n\t\t\tif diffCount == 0 {\n\t\t\t\tfoundMatchingCall = true\n\t\t\t\t// Remove from ExpectedCalls - just skip it\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tc.Parent.ExpectedCalls[index] = call\n\t\tindex++\n\t}\n\t// trim slice up to last copied index\n\tc.Parent.ExpectedCalls = c.Parent.ExpectedCalls[:index]\n\n\tif !foundMatchingCall {\n\t\tunlockOnce.Do(c.unlock)\n\t\tc.Parent.fail(\"\\n\\nmock: Could not find expected call\\n-----------------------------\\n\\n%s\\n\\n\",\n\t\t\tcallString(c.Method, c.Arguments, true),\n\t\t)\n\t}\n\n\treturn c\n}", "func (mock *MailgunMock) RemoveUnsubscribeCalls() []struct {\n\tIn1 string\n} {\n\tvar calls []struct {\n\t\tIn1 string\n\t}\n\tlockMailgunMockRemoveUnsubscribe.RLock()\n\tcalls = mock.calls.RemoveUnsubscribe\n\tlockMailgunMockRemoveUnsubscribe.RUnlock()\n\treturn calls\n}", "func (m *MockWebsocketClientStore) Unset(clientID wspubsub.UUID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Unset\", clientID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *ICacheInteractor) Flush() error {\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}", "func GetEventListMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/events\").Return(dIn, 200, nil)\n\teventsOut, err := ds.GetEventList()\n\tassert.Nil(err, \"Error getting event list\")\n\tassert.Equal(eventsIn, eventsOut, \"GetEventList returned different events\")\n\n\treturn eventsOut\n}", "func (_m *ORM) Clear(chainID *big.Int, key string) error {\n\tret := _m.Called(chainID, key)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*big.Int, string) error); ok {\n\t\tr0 = rf(chainID, key)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockEventBus) DispatchEvent(arg0 members.Event) error {\n\tret := m.ctrl.Call(m, \"DispatchEvent\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (l *MockLogger) Flush() {}", "func (m *MockWebsocketClientStore) UnsetChannels(clientID wspubsub.UUID, channels ...string) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{clientID}\n\tfor _, a := range channels {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UnsetChannels\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockSQSAPI) UntagQueueRequest(arg0 *sqs.UntagQueueInput) (*request.Request, *sqs.UntagQueueOutput) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UntagQueueRequest\", arg0)\n\tret0, _ := ret[0].(*request.Request)\n\tret1, _ := ret[1].(*sqs.UntagQueueOutput)\n\treturn ret0, ret1\n}", "func (m *InviteeMutation) ResetEvents() {\n\tm.events = nil\n\tm.clearedevents = false\n\tm.removedevents = nil\n}", "func (_m *MockCompletableFuture[T]) Cancel() {\n\t_m.Called()\n}", "func (_m *MockORM) Commit() ORM {\n\tret := _m.Called()\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func() ORM); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func MockConsensusEvent(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, i ...int) consensus.Event {\n\taev := MockAgreementEvent(hash, round, step, keys, p, i...)\n\thdr := aev.Header\n\n\tbuf := new(bytes.Buffer)\n\t_ = Marshal(buf, *aev)\n\n\treturn consensus.Event{\n\t\tHeader: hdr,\n\t\tPayload: *buf,\n\t}\n}", "func (_m *ChannelRepository) RemovePrivateChannelMembers(memberIds []string, channelId string) error {\n\tret := _m.Called(memberIds, channelId)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func([]string, string) error); ok {\n\t\tr0 = rf(memberIds, channelId)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *RunInterface) GetEvents(lastID string) (*apiclient.EventIterator, error) {\n\tret := _m.Called(lastID)\n\n\tvar r0 *apiclient.EventIterator\n\tif rf, ok := ret.Get(0).(func(string) *apiclient.EventIterator); ok {\n\t\tr0 = rf(lastID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*apiclient.EventIterator)\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(lastID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockSocketClient) Ack(req socketmode.Request, payload ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{req}\n\tfor _, a := range payload {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Ack\", varargs...)\n}", "func (_m *Subscription) Events() <-chan ari.Event {\n\tret := _m.Called()\n\n\tvar r0 <-chan ari.Event\n\tif rf, ok := ret.Get(0).(func() <-chan ari.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(<-chan ari.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *MockTx) MarkPatientsInactiveByClient(_a0 uint) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(uint) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}" ]
[ "0.70760024", "0.6043022", "0.5928685", "0.5716477", "0.55757356", "0.5526177", "0.54580176", "0.54382396", "0.53673023", "0.53628206", "0.53532636", "0.5341673", "0.53009766", "0.5300278", "0.52957547", "0.52558625", "0.5241087", "0.5238653", "0.5225781", "0.51996076", "0.51993096", "0.5185294", "0.51719964", "0.51646924", "0.5145164", "0.5134102", "0.5127098", "0.51236635", "0.5101121", "0.5094388", "0.5086606", "0.5065102", "0.50531226", "0.50232905", "0.5008365", "0.49847648", "0.49818864", "0.49616805", "0.49444494", "0.49315253", "0.4918022", "0.49177822", "0.49147537", "0.4895149", "0.4882904", "0.48811656", "0.48772624", "0.48772416", "0.48750326", "0.48742786", "0.48718837", "0.48705798", "0.4865268", "0.48639673", "0.48473832", "0.4840619", "0.48330662", "0.4831921", "0.48289087", "0.48255482", "0.48122033", "0.4804021", "0.47991034", "0.47922322", "0.47899917", "0.47891062", "0.47815955", "0.47760284", "0.47693878", "0.47663602", "0.4764655", "0.47601336", "0.47596642", "0.47585016", "0.47550792", "0.47504827", "0.47496653", "0.474962", "0.47427785", "0.47412252", "0.47316018", "0.47294852", "0.47279984", "0.47206098", "0.4718136", "0.47171426", "0.47157642", "0.47096163", "0.47081074", "0.47072294", "0.4695458", "0.4687789", "0.46874353", "0.4683703", "0.46792588", "0.46739942", "0.46728262", "0.46710783", "0.46677557", "0.46669808" ]
0.78784215
0
getUncommittedEvents provides a mock function with given fields:
func (_m *MockAggregate) getUncommittedEvents() []Event { ret := _m.Called() var r0 []Event if rf, ok := ret.Get(0).(func() []Event); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]Event) } } return r0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockAggregate) clearUncommittedEvents() {\n\t_m.Called()\n}", "func (_m *LogPollerWrapper) LatestEvents() ([]types.OracleRequest, []types.OracleResponse, error) {\n\tret := _m.Called()\n\n\tvar r0 []types.OracleRequest\n\tvar r1 []types.OracleResponse\n\tvar r2 error\n\tif rf, ok := ret.Get(0).(func() ([]types.OracleRequest, []types.OracleResponse, error)); ok {\n\t\treturn rf()\n\t}\n\tif rf, ok := ret.Get(0).(func() []types.OracleRequest); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]types.OracleRequest)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func() []types.OracleResponse); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).([]types.OracleResponse)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(2).(func() error); ok {\n\t\tr2 = rf()\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (_m *EventProviderMock) GetStorageEvents(meta *types.Metadata, blockHash types.Hash) (*types.StorageDataRaw, error) {\n\tret := _m.Called(meta, blockHash)\n\n\tvar r0 *types.StorageDataRaw\n\tif rf, ok := ret.Get(0).(func(*types.Metadata, types.Hash) *types.StorageDataRaw); ok {\n\t\tr0 = rf(meta, blockHash)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*types.StorageDataRaw)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*types.Metadata, types.Hash) error); ok {\n\t\tr1 = rf(meta, blockHash)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func MockEvents() []optic.Event {\n\tevents := make([]optic.Event, 0)\n\tevents = append(events, TestRaw([]byte(\"raw\")))\n\tevents = append(events, TestMetric(1.0))\n\tevents = append(events, TestLogLine(\"logline\"))\n\treturn events\n}", "func (m *MockGeneralRepository) GetEvents(arg0 []models.SubscriptionRequest, arg1, arg2 int64) ([]models.Event, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetEvents\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]models.Event)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *RepositoryMock) GetEventsFromCalls() []struct {\n\tCtx context.Context\n\tFrom uint64\n\tLimit uint64\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tFrom uint64\n\t\tLimit uint64\n\t}\n\tmock.lockGetEventsFrom.RLock()\n\tcalls = mock.calls.GetEventsFrom\n\tmock.lockGetEventsFrom.RUnlock()\n\treturn calls\n}", "func GetEventListMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/events\").Return(dIn, 200, nil)\n\teventsOut, err := ds.GetEventList()\n\tassert.Nil(err, \"Error getting event list\")\n\tassert.Equal(eventsIn, eventsOut, \"GetEventList returned different events\")\n\n\treturn eventsOut\n}", "func (_m *Entity) Events() []core.Event {\n\tret := _m.Called()\n\n\tvar r0 []core.Event\n\tif rf, ok := ret.Get(0).(func() []core.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]core.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mock *RepositoryMock) GetUnprocessedEventsCalls() []struct {\n\tCtx context.Context\n\tLimit uint64\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tLimit uint64\n\t}\n\tmock.lockGetUnprocessedEvents.RLock()\n\tcalls = mock.calls.GetUnprocessedEvents\n\tmock.lockGetUnprocessedEvents.RUnlock()\n\treturn calls\n}", "func (_m *RunInterface) GetEvents(lastID string) (*apiclient.EventIterator, error) {\n\tret := _m.Called(lastID)\n\n\tvar r0 *apiclient.EventIterator\n\tif rf, ok := ret.Get(0).(func(string) *apiclient.EventIterator); ok {\n\t\tr0 = rf(lastID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*apiclient.EventIterator)\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(lastID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *RepositoryMock) GetLastEventsCalls() []struct {\n\tCtx context.Context\n\tLimit uint64\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tLimit uint64\n\t}\n\tmock.lockGetLastEvents.RLock()\n\tcalls = mock.calls.GetLastEvents\n\tmock.lockGetLastEvents.RUnlock()\n\treturn calls\n}", "func (m *MockEventDao) UnfinishedEvents(target, targetID string, optTypes ...string) ([]*model.ServiceEvent, error) {\n\tvarargs := []interface{}{target, targetID}\n\tfor _, a := range optTypes {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"UnfinishedEvents\", varargs...)\n\tret0, _ := ret[0].([]*model.ServiceEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *mockStateBuilder) applyEvents(domainID string, requestID string, execution shared.WorkflowExecution, _a3 []*shared.HistoryEvent,\n\tnewRunHistory []*shared.HistoryEvent, eventStoreVersion, newRunEventStoreVersion int32, newRunNDC bool) (*shared.HistoryEvent, *decisionInfo, mutableState, error) {\n\n\tret := _m.Called(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\n\tvar r0 *shared.HistoryEvent\n\tif rf, ok := ret.Get(0).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *shared.HistoryEvent); ok {\n\t\tr0 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*shared.HistoryEvent)\n\t\t}\n\t}\n\n\tvar r1 *decisionInfo\n\tif rf, ok := ret.Get(1).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) *decisionInfo); ok {\n\t\tr1 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*decisionInfo)\n\t\t}\n\t}\n\n\tvar r2 mutableState\n\tif rf, ok := ret.Get(2).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) mutableState); ok {\n\t\tr2 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tif ret.Get(2) != nil {\n\t\t\tr2 = ret.Get(2).(mutableState)\n\t\t}\n\t}\n\n\tvar r3 error\n\tif rf, ok := ret.Get(3).(func(string, string, shared.WorkflowExecution, []*shared.HistoryEvent, []*shared.HistoryEvent, int32, int32, bool) error); ok {\n\t\tr3 = rf(domainID, requestID, execution, _a3, newRunHistory, eventStoreVersion, newRunEventStoreVersion, newRunNDC)\n\t} else {\n\t\tr3 = ret.Error(3)\n\t}\n\n\treturn r0, r1, r2, r3\n}", "func (c *gitlabClient) GetEvents(ctx context.Context, repo string, dateRef time.Time) ([]interface{}, time.Duration, error) {\n\treturn nil, 0.0, fmt.Errorf(\"Not implemented on Gitlab\")\n}", "func (_m *Blockchain) OnCommit(b api.Block) ([]api.Block, *treemap.Map, error) {\n\tret := _m.Called(b)\n\n\tvar r0 []api.Block\n\tif rf, ok := ret.Get(0).(func(api.Block) []api.Block); ok {\n\t\tr0 = rf(b)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]api.Block)\n\t\t}\n\t}\n\n\tvar r1 *treemap.Map\n\tif rf, ok := ret.Get(1).(func(api.Block) *treemap.Map); ok {\n\t\tr1 = rf(b)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*treemap.Map)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(api.Block) error); ok {\n\t\tr2 = rf(b)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (mock *MailgunMock) ListEventsCalls() []struct {\n\tIn1 *mailgun.EventsOptions\n} {\n\tvar calls []struct {\n\t\tIn1 *mailgun.EventsOptions\n\t}\n\tlockMailgunMockListEvents.RLock()\n\tcalls = mock.calls.ListEvents\n\tlockMailgunMockListEvents.RUnlock()\n\treturn calls\n}", "func (m *MockHandler) GetEvents(clusterID strfmt.UUID, hostID *strfmt.UUID, categories ...string) ([]*common.Event, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{clusterID, hostID}\n\tfor _, a := range categories {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"GetEvents\", varargs...)\n\tret0, _ := ret[0].([]*common.Event)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *MailgunMock) PollEventsCalls() []struct {\n\tIn1 *mailgun.EventsOptions\n} {\n\tvar calls []struct {\n\t\tIn1 *mailgun.EventsOptions\n\t}\n\tlockMailgunMockPollEvents.RLock()\n\tcalls = mock.calls.PollEvents\n\tlockMailgunMockPollEvents.RUnlock()\n\treturn calls\n}", "func GetSysEventListMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/system_events\").Return(dIn, 200, nil)\n\teventsOut, err := ds.GetSysEventList()\n\tassert.Nil(err, \"Error getting event list\")\n\tassert.Equal(eventsIn, eventsOut, \"GetSysEventList returned different events\")\n\n\treturn eventsOut\n}", "func (_m *MockHistoryEngine) ReapplyEvents(ctx context.Context, domainUUID string, workflowID string, events []*shared.HistoryEvent) error {\n\tret := _m.Called(domainUUID, workflowID, events)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, string, []*shared.HistoryEvent) error); ok {\n\t\tr0 = rf(domainUUID, workflowID, events)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockClient) ListIssueEvents(org, repo string, num int) ([]github.ListedIssueEvent, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListIssueEvents\", org, repo, num)\n\tret0, _ := ret[0].([]github.ListedIssueEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHandler) V2GetEvents(clusterID, hostID, infraEnvID *strfmt.UUID, categories ...string) ([]*common.Event, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{clusterID, hostID, infraEnvID}\n\tfor _, a := range categories {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"V2GetEvents\", varargs...)\n\tret0, _ := ret[0].([]*common.Event)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockEventsSource) GetEvents() (*events0.EventListener, error) {\n\tret := m.ctrl.Call(m, \"GetEvents\")\n\tret0, _ := ret[0].(*events0.EventListener)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIssueClient) ListIssueEvents(org, repo string, num int) ([]github.ListedIssueEvent, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListIssueEvents\", org, repo, num)\n\tret0, _ := ret[0].([]github.ListedIssueEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client BaseClient) GetExpectationEvents(ctx context.Context, pathParameter string, top *float64, skip *float64) (result ListEvent, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: pathParameter,\n\t\t\tConstraints: []validation.Constraint{{Target: \"pathParameter\", Name: validation.Pattern, Rule: `.*`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"beacon.BaseClient\", \"GetExpectationEvents\", err.Error())\n\t}\n\n\treq, err := client.GetExpectationEventsPreparer(ctx, pathParameter, top, skip)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetExpectationEvents\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetExpectationEventsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetExpectationEvents\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetExpectationEventsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetExpectationEvents\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (_m *MockMessageProducer) Events() chan kafka.Event {\n\tret := _m.Called()\n\n\tvar r0 chan kafka.Event\n\tif rf, ok := ret.Get(0).(func() chan kafka.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan kafka.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockEventDao) GetEventsByTarget(target, targetID string, offset, liimt int) ([]*model.ServiceEvent, int, error) {\n\tret := m.ctrl.Call(m, \"GetEventsByTarget\", target, targetID, offset, liimt)\n\tret0, _ := ret[0].([]*model.ServiceEvent)\n\tret1, _ := ret[1].(int)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (_m *Consumer) Events() chan kafka.Event {\n\tret := _m.Called()\n\n\tvar r0 chan kafka.Event\n\tif rf, ok := ret.Get(0).(func() chan kafka.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan kafka.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockNotificationEventDao) GetNotificationEventNotHandle() ([]*model.NotificationEvent, error) {\n\tret := m.ctrl.Call(m, \"GetNotificationEventNotHandle\")\n\tret0, _ := ret[0].([]*model.NotificationEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockEventDao) GetEventByEventIDs(eventIDs []string) ([]*model.ServiceEvent, error) {\n\tret := m.ctrl.Call(m, \"GetEventByEventIDs\", eventIDs)\n\tret0, _ := ret[0].([]*model.ServiceEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetEventListFailJSONMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// wrong json\n\tdIn := []byte{10, 20, 30}\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/events\").Return(dIn, 200, nil)\n\teventsOut, err := ds.GetEventList()\n\n\tassert.NotNil(err, \"We are expecting a marshalling error\")\n\tassert.Nil(eventsOut, \"Expecting nil output\")\n\tassert.Contains(err.Error(), \"invalid character\", \"Error message should include the string 'invalid character'\")\n\n\treturn eventsOut\n}", "func (m *MockEventDao) GetEventsByTenantID(tenantID string, offset, limit int) ([]*model.ServiceEvent, int, error) {\n\tret := m.ctrl.Call(m, \"GetEventsByTenantID\", tenantID, offset, limit)\n\tret0, _ := ret[0].([]*model.ServiceEvent)\n\tret1, _ := ret[1].(int)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *Mockapi) DescribeStackEvents(arg0 *cloudformation.DescribeStackEventsInput) (*cloudformation.DescribeStackEventsOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DescribeStackEvents\", arg0)\n\tret0, _ := ret[0].(*cloudformation.DescribeStackEventsOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Watcher) Events() chan fsnotify.Event {\n\tret := _m.Called()\n\n\tvar r0 chan fsnotify.Event\n\tif rf, ok := ret.Get(0).(func() chan fsnotify.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan fsnotify.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockContext) AppendHistoryEvents(request *persistence.AppendHistoryNodesRequest, namespaceID string, execution v1.WorkflowExecution) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AppendHistoryEvents\", request, namespaceID, execution)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mock *ClienterMock) GetReleaseCalendarEntriesCalls() []struct {\n\tCtx context.Context\n\tOptions sdk.Options\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tOptions sdk.Options\n\t}\n\tmock.lockGetReleaseCalendarEntries.RLock()\n\tcalls = mock.calls.GetReleaseCalendarEntries\n\tmock.lockGetReleaseCalendarEntries.RUnlock()\n\treturn calls\n}", "func (_m *SlackRTMInterface) GetIncomingEvents() chan slack.RTMEvent {\n\tret := _m.Called()\n\n\tvar r0 chan slack.RTMEvent\n\tif rf, ok := ret.Get(0).(func() chan slack.RTMEvent); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(chan slack.RTMEvent)\n\t\t}\n\t}\n\n\treturn r0\n}", "func GetEventListFailStatusMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/events\").Return(dIn, 499, nil)\n\teventsOut, err := ds.GetEventList()\n\n\tassert.NotNil(err, \"We are expecting an status code error\")\n\tassert.Nil(eventsOut, \"Expecting nil output\")\n\tassert.Contains(err.Error(), \"499\", \"Error should contain http code 499\")\n\n\treturn eventsOut\n}", "func (mock *PluginerMock) CommitIDCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockCommitID.RLock()\n\tcalls = mock.calls.CommitID\n\tmock.lockCommitID.RUnlock()\n\treturn calls\n}", "func TestActiveMultiEvent_Deactivate(t *testing.T) {\r\n\tnumber := 10\r\n\tvar events []*ActiveEvent\r\n\tvar mock []*mockUnixHelper\r\n\r\n\tfor i := 0; i < number; i++ {\r\n\t\tunixMock := &mockUnixHelper{}\r\n\t\tnewActive := &ActiveEvent{FileDescriptor: i, unix: unixMock}\r\n\t\tunixMock.On(\"close\", i).Return(nil).Once()\r\n\t\tevents = append(events, newActive)\r\n\t\tmock = append(mock, unixMock)\r\n\t}\r\n\r\n\tnewActiveMulti := ActiveMultiEvent{events: events}\r\n\tnewActiveMulti.Deactivate()\r\n\r\n\trequire.Nil(t, newActiveMulti.events)\r\n\tfor _, event := range events {\r\n\t\trequire.Nil(t, event)\r\n\t}\r\n\tfor _, m := range mock {\r\n\t\tm.AssertExpectations(t)\r\n\t}\r\n}", "func (mock *PublisherMock) PublishCalls() []struct {\n\tCtx context.Context\n\tEvents []Event\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tEvents []Event\n\t}\n\tmock.lockPublish.RLock()\n\tcalls = mock.calls.Publish\n\tmock.lockPublish.RUnlock()\n\treturn calls\n}", "func (_m *RunInterface) CreateLastEvent() (int, error) {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func MockConsensusEvent(hash []byte, round uint64, step uint8, keys []key.ConsensusKeys, p *user.Provisioners, i ...int) consensus.Event {\n\taev := MockAgreementEvent(hash, round, step, keys, p, i...)\n\thdr := aev.Header\n\n\tbuf := new(bytes.Buffer)\n\t_ = Marshal(buf, *aev)\n\n\treturn consensus.Event{\n\t\tHeader: hdr,\n\t\tPayload: *buf,\n\t}\n}", "func GetServerEventListMocked(t *testing.T, eventsIn []*types.Event, serverID string) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewServerService(cs)\n\tassert.Nil(err, \"Couldn't load server service\")\n\tassert.NotNil(ds, \"Server service not instanced\")\n\n\t// to json\n\tevIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Server event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", fmt.Sprintf(\"/cloud/servers/%s/events\", serverID)).Return(evIn, 200, nil)\n\tevOut, err := ds.GetEventsList(serverID)\n\tassert.Nil(err, \"Error getting server event list\")\n\tassert.Equal(eventsIn, evOut, \"GetServerEventList returned different server events\")\n\n\treturn evOut\n}", "func (_m *MockStorage) GetLastRequestTimeInWindow(user string, timeStamp int64) (int64, error) {\n\tret := _m.Called(user, timeStamp)\n\n\tvar r0 int64\n\tif rf, ok := ret.Get(0).(func(string, int64) int64); ok {\n\t\tr0 = rf(user, timeStamp)\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, int64) error); ok {\n\t\tr1 = rf(user, timeStamp)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockEventDao) GetLastASyncEvent(target, targetID string) (*model.ServiceEvent, error) {\n\tret := m.ctrl.Call(m, \"GetLastASyncEvent\", target, targetID)\n\tret0, _ := ret[0].(*model.ServiceEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockHandler) EventQuery() (*models.SearchQuery, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"EventQuery\")\n\tret0, _ := ret[0].(*models.SearchQuery)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *DB) SaveEvent(topic string, eventData interface{}, inTx func() error) error {\n\tret := _m.Called(topic, eventData, inTx)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, interface{}, func() error) error); ok {\n\t\tr0 = rf(topic, eventData, inTx)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Subscription) Events() <-chan ari.Event {\n\tret := _m.Called()\n\n\tvar r0 <-chan ari.Event\n\tif rf, ok := ret.Get(0).(func() <-chan ari.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(<-chan ari.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func GetEventListFailErrMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/events\").Return(dIn, 200, fmt.Errorf(\"mocked error\"))\n\teventsOut, err := ds.GetEventList()\n\n\tassert.NotNil(err, \"We are expecting an error\")\n\tassert.Nil(eventsOut, \"Expecting nil output\")\n\tassert.Equal(err.Error(), \"mocked error\", \"Error should be 'mocked error'\")\n\n\treturn eventsOut\n}", "func (_m *Route53API) WaitUntilResourceRecordSetsChanged(_a0 *route53.GetChangeInput) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*route53.GetChangeInput) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func MockRaw() []optic.Raw {\n\trawEvents := make([]optic.Raw, 0)\n\trawEvents = append(rawEvents, TestRaw([]byte(\"raw\")))\n\treturn rawEvents\n}", "func (mock *GitModuleControllerMock) OnRemoveCalls() []struct {\n\tCtx context.Context\n\tName string\n\tSync v1.GitModuleHandler\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tName string\n\t\tSync v1.GitModuleHandler\n\t}\n\tlockGitModuleControllerMockOnRemove.RLock()\n\tcalls = mock.calls.OnRemove\n\tlockGitModuleControllerMockOnRemove.RUnlock()\n\treturn calls\n}", "func (m *MockEventsSourceProvider) Events(arg0 string, arg1 *cert.Info) (events.Client, events.EventsSource, error) {\n\tret := m.ctrl.Call(m, \"Events\", arg0, arg1)\n\tret0, _ := ret[0].(events.Client)\n\tret1, _ := ret[1].(events.EventsSource)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (_m *SinkEventer) Events() <-chan frizzle.Event {\n\tret := _m.Called()\n\n\tvar r0 <-chan frizzle.Event\n\tif rf, ok := ret.Get(0).(func() <-chan frizzle.Event); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(<-chan frizzle.Event)\n\t\t}\n\t}\n\n\treturn r0\n}", "func TestGetStartTimeOfInterestCommits(t *testing.T) {\n\tunittest.SmallTest(t)\n\t// We have to provide NewIngester non-nil eventbus and ingestionstore.\n\tmeb := &mockeventbus.EventBus{}\n\tmis := &mocks.IngestionStore{}\n\tmvs := &mockvcs.VCS{}\n\n\tdefer meb.AssertExpectations(t)\n\tdefer mis.AssertExpectations(t)\n\tdefer mvs.AssertExpectations(t)\n\n\t// arbitrary date\n\tnow := time.Date(2019, 8, 5, 11, 20, 0, 0, time.UTC)\n\tthreeDaysAgo := now.Add(-3 * 24 * time.Hour)\n\tsixDaysAgo := now.Add(-6 * 24 * time.Hour)\n\tbetaTime := time.Date(2019, 8, 1, 17, 35, 0, 0, time.UTC)\n\n\thashes := []string{\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\"}\n\n\tmvs.On(\"Update\", testutils.AnyContext, true, false).Return(nil)\n\tmvs.On(\"From\", threeDaysAgo).Return(hashes[3:])\n\tmvs.On(\"From\", sixDaysAgo).Return(hashes)\n\t// Since we retrieve 5 commits, the algorithm trims it to NCommits\n\t// when it has to query more.\n\tmvs.On(\"Details\", testutils.AnyContext, \"beta\", false).Return(&vcsinfo.LongCommit{\n\t\t// The function only cares about the timestamp\n\t\tTimestamp: betaTime,\n\t}, nil)\n\n\tconf := &sharedconfig.IngesterConfig{\n\t\tNCommits: 4,\n\t\tMinDays: 3,\n\t}\n\n\ti, err := NewIngester(\"test-ingester-2\", conf, mvs, nil, nil, mis, meb)\n\trequire.NoError(t, err)\n\n\tts, err := i.getStartTimeOfInterest(context.Background(), now)\n\trequire.NoError(t, err)\n\trequire.Equal(t, betaTime, ts)\n}", "func (m *MockUsecase) ListenEvents(userID int) (chan map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListenEvents\", userID)\n\tret0, _ := ret[0].(chan map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *Entity) ClearEvents() {\n\t_m.Called()\n}", "func (_m *MockHistoryEngine) ReplicateRawEvents(ctx context.Context, request *gohistory.ReplicateRawEventsRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.ReplicateRawEventsRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *Client) GetChangesBetweenBuilds(_a0 context.Context, _a1 build.GetChangesBetweenBuildsArgs) (*[]build.Change, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *[]build.Change\n\tif rf, ok := ret.Get(0).(func(context.Context, build.GetChangesBetweenBuildsArgs) *[]build.Change); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*[]build.Change)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.GetChangesBetweenBuildsArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func GetSysEventListFailJSONMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// wrong json\n\tdIn := []byte{10, 20, 30}\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/system_events\").Return(dIn, 200, nil)\n\teventsOut, err := ds.GetSysEventList()\n\n\tassert.NotNil(err, \"We are expecting a marshalling error\")\n\tassert.Nil(eventsOut, \"Expecting nil output\")\n\tassert.Contains(err.Error(), \"invalid character\", \"Error message should include the string 'invalid character'\")\n\n\treturn eventsOut\n}", "func encodeMockEvent(e models.Event) ([]byte, error) {\n\tbyteBuffer, err := cbor.Marshal(e)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn byteBuffer, nil\n}", "func (c *TestCase) ThenInspectEvents(f func(t *testing.T, events []rangedb.Event)) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Helper()\n\n\t\tctx := rangedbtest.TimeoutContext(t)\n\t\tstreamPreviousEventCounts := make(map[string]uint64)\n\t\tfor _, event := range c.previousEvents {\n\t\t\tstreamPreviousEventCounts[rangedb.GetEventStream(event)]++\n\t\t\tstreamName := rangedb.GetEventStream(event)\n\t\t\trangedbtest.BlockingSaveEvents(t, c.store, streamName, &rangedb.EventRecord{Event: event})\n\t\t}\n\n\t\tc.dispatch(c.command)\n\n\t\tvar events []rangedb.Event\n\t\tfor _, stream := range getStreamsFromStore(c.store) {\n\t\t\tstreamSequenceNumber := streamPreviousEventCounts[stream] + 1\n\t\t\tactualEvents, err := recordIteratorToSlice(c.store.EventsByStream(ctx, streamSequenceNumber, stream))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tevents = append(events, actualEvents...)\n\t\t}\n\n\t\tf(t, events)\n\t}\n}", "func (m *MockNotificationEventDao) GetNotificationEventByTime(start, end time.Time) ([]*model.NotificationEvent, error) {\n\tret := m.ctrl.Call(m, \"GetNotificationEventByTime\", start, end)\n\tret0, _ := ret[0].([]*model.NotificationEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *FileRepository) GetExpiredFiles() ([]*models.File, error) {\n\tret := _m.Called()\n\n\tvar r0 []*models.File\n\tif rf, ok := ret.Get(0).(func() []*models.File); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*models.File)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Client) LeaseEvents(_a0 context.Context, _a1 v1beta2.LeaseID, _a2 string, _a3 bool) (cluster.EventsWatcher, error) {\n\tret := _m.Called(_a0, _a1, _a2, _a3)\n\n\tvar r0 cluster.EventsWatcher\n\tif rf, ok := ret.Get(0).(func(context.Context, v1beta2.LeaseID, string, bool) cluster.EventsWatcher); ok {\n\t\tr0 = rf(_a0, _a1, _a2, _a3)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(cluster.EventsWatcher)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, v1beta2.LeaseID, string, bool) error); ok {\n\t\tr1 = rf(_a0, _a1, _a2, _a3)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func MockChangesetSyncState(repo *protocol.RepoInfo) *MockedChangesetSyncState {\n\tstate := &MockedChangesetSyncState{\n\t\t// This diff.Stat matches the testGitHubDiff below\n\t\tDiffStat: &diff.Stat{Added: 1, Changed: 1, Deleted: 3},\n\n\t\texecReader: git.Mocks.ExecReader,\n\t\tmockRepoLookup: repoupdater.MockRepoLookup,\n\t\tresolveRevision: git.Mocks.ResolveRevision,\n\t}\n\n\trepoupdater.MockRepoLookup = func(args protocol.RepoLookupArgs) (*protocol.RepoLookupResult, error) {\n\t\treturn &protocol.RepoLookupResult{\n\t\t\tRepo: repo,\n\t\t}, nil\n\t}\n\n\tgit.Mocks.ExecReader = func(args []string) (io.ReadCloser, error) {\n\t\t// This provides a diff that will resolve to 1 added line, 1 changed\n\t\t// line, and 3 deleted lines.\n\t\tconst testGitHubDiff = `\ndiff --git a/test.py b/test.py\nindex 884601b..c4886d5 100644\n--- a/test.py\n+++ b/test.py\n@@ -1,6 +1,4 @@\n+# square makes a value squarer.\n def square(a):\n- \"\"\"\n- square makes a value squarer.\n- \"\"\"\n\n- return a * a\n+ return pow(a, 2)\n\n`\n\n\t\tif len(args) < 1 && args[0] != \"diff\" {\n\t\t\tif state.execReader != nil {\n\t\t\t\treturn state.execReader(args)\n\t\t\t}\n\t\t\treturn nil, errors.New(\"cannot handle non-diff command in mock ExecReader\")\n\t\t}\n\t\treturn io.NopCloser(strings.NewReader(testGitHubDiff)), nil\n\t}\n\n\tgit.Mocks.ResolveRevision = func(spec string, opt git.ResolveRevisionOptions) (api.CommitID, error) {\n\t\treturn \"mockcommitid\", nil\n\t}\n\n\treturn state\n}", "func (m *JetReleaserMock) MinimockCloseAllUntilInspect() {\n\tfor _, e := range m.CloseAllUntilMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\tm.t.Errorf(\"Expected call to JetReleaserMock.CloseAllUntil with params: %#v\", *e.params)\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.CloseAllUntilMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterCloseAllUntilCounter) < 1 {\n\t\tif m.CloseAllUntilMock.defaultExpectation.params == nil {\n\t\t\tm.t.Error(\"Expected call to JetReleaserMock.CloseAllUntil\")\n\t\t} else {\n\t\t\tm.t.Errorf(\"Expected call to JetReleaserMock.CloseAllUntil with params: %#v\", *m.CloseAllUntilMock.defaultExpectation.params)\n\t\t}\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcCloseAllUntil != nil && mm_atomic.LoadUint64(&m.afterCloseAllUntilCounter) < 1 {\n\t\tm.t.Error(\"Expected call to JetReleaserMock.CloseAllUntil\")\n\t}\n}", "func (_m *CloudWatchEventsModelAPI) UpdateCloudWatchEvents(event types.Event) error {\n\tret := _m.Called(event)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(types.Event) error); ok {\n\t\tr0 = rf(event)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (mock *FilterStoreMock) PutStateAsEmptyCalls() []struct {\n\tCtx context.Context\n\tFilterJobID string\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tFilterJobID string\n\t}\n\tmock.lockPutStateAsEmpty.RLock()\n\tcalls = mock.calls.PutStateAsEmpty\n\tmock.lockPutStateAsEmpty.RUnlock()\n\treturn calls\n}", "func (m *MockProduct) ListDeployedAndAcquiredEditors(arg0 context.Context, arg1 string) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListDeployedAndAcquiredEditors\", arg0, arg1)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockEventsService) SearchEvents(arg0 domain.SearchEventsInput) (*[]domain.Event, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"SearchEvents\", arg0)\n\tret0, _ := ret[0].(*[]domain.Event)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) ListFileCommits(org, repo, path string) ([]github.RepositoryCommit, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListFileCommits\", org, repo, path)\n\tret0, _ := ret[0].([]github.RepositoryCommit)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetSysEventListFailStatusMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/system_events\").Return(dIn, 499, nil)\n\teventsOut, err := ds.GetSysEventList()\n\n\tassert.NotNil(err, \"We are expecting an status code error\")\n\tassert.Nil(eventsOut, \"Expecting nil output\")\n\tassert.Contains(err.Error(), \"499\", \"Error should contain http code 499\")\n\n\treturn eventsOut\n}", "func TestLastEvents(t *testing.T) {\n\tclient, err := cutils.SetupRinkebyClient()\n\tif err != nil {\n\t\tt.Logf(\"Error connecting to rinkeby: %v\", err)\n\t\treturn\n\t}\n\tfilterers := []model.ContractFilterers{\n\t\tfilterer.NewCivilTCRContractFilterers(common.HexToAddress(testTCRAddress)),\n\t}\n\tretrieve := retriever.NewEventRetriever(client, filterers)\n\tif len(filterers[0].LastEvents()) != 0 {\n\t\tt.Error(\"LastEvents should be empty\")\n\t}\n\terr = retrieve.Retrieve()\n\tif err != nil {\n\t\tt.Errorf(\"Error retrieving events: %v\", err)\n\t}\n\tif len(filterers[0].LastEvents()) == 0 {\n\t\tt.Error(\"LastEvents should not be empty\")\n\t}\n}", "func (m *MockEventRepository) FindAll() map[sweeper.Snowflake]*sweeper.Event {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FindAll\")\n\tret0, _ := ret[0].(map[sweeper.Snowflake]*sweeper.Event)\n\treturn ret0\n}", "func (mock *TransactionsStorageMock) GetLastTransactionDateCalls() []struct {\n\tCtx context.Context\n\tAccountID string\n} {\n\tvar calls []struct {\n\t\tCtx context.Context\n\t\tAccountID string\n\t}\n\tmock.lockGetLastTransactionDate.RLock()\n\tcalls = mock.calls.GetLastTransactionDate\n\tmock.lockGetLastTransactionDate.RUnlock()\n\treturn calls\n}", "func (m *MockEventLogger) AppendMulti(events ...eventlog.EventData) (uint64, uint64, uint64, time.Time, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range events {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"AppendMulti\", varargs...)\n\tret0, _ := ret[0].(uint64)\n\tret1, _ := ret[1].(uint64)\n\tret2, _ := ret[2].(uint64)\n\tret3, _ := ret[3].(time.Time)\n\tret4, _ := ret[4].(error)\n\treturn ret0, ret1, ret2, ret3, ret4\n}", "func (_m *TeamStore) GetNewTeamMembersSince(teamID string, since int64, offset int, limit int) (*model.NewTeamMembersList, int64, error) {\n\tret := _m.Called(teamID, since, offset, limit)\n\n\tvar r0 *model.NewTeamMembersList\n\tif rf, ok := ret.Get(0).(func(string, int64, int, int) *model.NewTeamMembersList); ok {\n\t\tr0 = rf(teamID, since, offset, limit)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*model.NewTeamMembersList)\n\t\t}\n\t}\n\n\tvar r1 int64\n\tif rf, ok := ret.Get(1).(func(string, int64, int, int) int64); ok {\n\t\tr1 = rf(teamID, since, offset, limit)\n\t} else {\n\t\tr1 = ret.Get(1).(int64)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string, int64, int, int) error); ok {\n\t\tr2 = rf(teamID, since, offset, limit)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (mock *HarborRepositoryListerMock) GetCalls() []struct {\n\tNamespace string\n\tName string\n} {\n\tvar calls []struct {\n\t\tNamespace string\n\t\tName string\n\t}\n\tlockHarborRepositoryListerMockGet.RLock()\n\tcalls = mock.calls.Get\n\tlockHarborRepositoryListerMockGet.RUnlock()\n\treturn calls\n}", "func (_m *RunInterface) CreateLogEvent(stage string, stream string, text string) (int, error) {\n\tret := _m.Called(stage, stream, text)\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func(string, string, string) int); ok {\n\t\tr0 = rf(stage, stream, text)\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string, string) error); ok {\n\t\tr1 = rf(stage, stream, text)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockNotificationEventDao) GetNotificationEventByHash(hash string) (*model.NotificationEvent, error) {\n\tret := m.ctrl.Call(m, \"GetNotificationEventByHash\", hash)\n\tret0, _ := ret[0].(*model.NotificationEvent)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetSysEventListFailErrMocked(t *testing.T, eventsIn []*types.Event) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewEventService(cs)\n\tassert.Nil(err, \"Couldn't load event service\")\n\tassert.NotNil(ds, \"Event service not instanced\")\n\n\t// to json\n\tdIn, err := json.Marshal(eventsIn)\n\tassert.Nil(err, \"Event test data corrupted\")\n\n\t// call service\n\tcs.On(\"Get\", \"/audit/system_events\").Return(dIn, 200, fmt.Errorf(\"mocked error\"))\n\teventsOut, err := ds.GetSysEventList()\n\n\tassert.NotNil(err, \"We are expecting an error\")\n\tassert.Nil(eventsOut, \"Expecting nil output\")\n\tassert.Equal(err.Error(), \"mocked error\", \"Error should be 'mocked error'\")\n\n\treturn eventsOut\n}", "func (_m *MockStorage) GetRequestCountInWindow(user string, timeStamp int64) (int64, error) {\n\tret := _m.Called(user, timeStamp)\n\n\tvar r0 int64\n\tif rf, ok := ret.Get(0).(func(string, int64) int64); ok {\n\t\tr0 = rf(user, timeStamp)\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, int64) error); ok {\n\t\tr1 = rf(user, timeStamp)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *FilterStoreMock) PutStateAsEmptyCalls() []struct {\n\tFilterJobID string\n} {\n\tvar calls []struct {\n\t\tFilterJobID string\n\t}\n\tlockFilterStoreMockPutStateAsEmpty.RLock()\n\tcalls = mock.calls.PutStateAsEmpty\n\tlockFilterStoreMockPutStateAsEmpty.RUnlock()\n\treturn calls\n}", "func (_m *Repository) CommitObjects() (object.CommitIter, error) {\n\tret := _m.Called()\n\n\tvar r0 object.CommitIter\n\tif rf, ok := ret.Get(0).(func() object.CommitIter); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(object.CommitIter)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *MockHistoryEngine) ReplicateEvents(ctx context.Context, request *gohistory.ReplicateEventsRequest) error {\n\tret := _m.Called(request)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*gohistory.ReplicateEventsRequest) error); ok {\n\t\tr0 = rf(request)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *MockTx) Commit() error {\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}", "func (_m *MockRepository) GetJobsByUpdateTimeAndStatus(ctx context.Context, lowerBound time.Time, upperBound time.Time, statuses ...JobStatus) ([]*Job, error) {\n\t_va := make([]interface{}, len(statuses))\n\tfor _i := range statuses {\n\t\t_va[_i] = statuses[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, ctx, lowerBound, upperBound)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 []*Job\n\tif rf, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, ...JobStatus) []*Job); ok {\n\t\tr0 = rf(ctx, lowerBound, upperBound, statuses...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]*Job)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, time.Time, time.Time, ...JobStatus) error); ok {\n\t\tr1 = rf(ctx, lowerBound, upperBound, statuses...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockSession) GetOnCloseCallbacks() []func() {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetOnCloseCallbacks\")\n\tret0, _ := ret[0].([]func())\n\treturn ret0\n}", "func (m *MockRDSAPI) DescribeEvents(arg0 *rds.DescribeEventsInput) (*rds.DescribeEventsOutput, error) {\n\tret := m.ctrl.Call(m, \"DescribeEvents\", arg0)\n\tret0, _ := ret[0].(*rds.DescribeEventsOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) GetTransactionHistory(arg0 int, arg1, arg2 string, arg3 int) ([]models.Transaction, *models.CustomErr) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetTransactionHistory\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([]models.Transaction)\n\tret1, _ := ret[1].(*models.CustomErr)\n\treturn ret0, ret1\n}", "func (_m *MockORM) Commit() ORM {\n\tret := _m.Called()\n\n\tvar r0 ORM\n\tif rf, ok := ret.Get(0).(func() ORM); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(ORM)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (_m *CognitoIdentityProviderAPI) AdminListUserAuthEvents(_a0 *cognitoidentityprovider.AdminListUserAuthEventsInput) (*cognitoidentityprovider.AdminListUserAuthEventsOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *cognitoidentityprovider.AdminListUserAuthEventsOutput\n\tif rf, ok := ret.Get(0).(func(*cognitoidentityprovider.AdminListUserAuthEventsInput) *cognitoidentityprovider.AdminListUserAuthEventsOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*cognitoidentityprovider.AdminListUserAuthEventsOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*cognitoidentityprovider.AdminListUserAuthEventsInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockCommitClient) ListFileCommits(org, repo, path string) ([]github.RepositoryCommit, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListFileCommits\", org, repo, path)\n\tret0, _ := ret[0].([]github.RepositoryCommit)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTasksInteractor) GetTasksHistory(ctx context.Context, from, to time.Time) ([]entities.ScheduledTasks, error) {\n\tret := m.ctrl.Call(m, \"GetTasksHistory\", ctx, from, to)\n\tret0, _ := ret[0].([]entities.ScheduledTasks)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockContext) GetEventsCache() events.Cache {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetEventsCache\")\n\tret0, _ := ret[0].(events.Cache)\n\treturn ret0\n}", "func GetServerEventListFailJSONMocked(t *testing.T, eventsIn []*types.Event, serverID string) []*types.Event {\n\n\tassert := assert.New(t)\n\n\t// wire up\n\tcs := &utils.MockConcertoService{}\n\tds, err := NewServerService(cs)\n\tassert.Nil(err, \"Couldn't load server service\")\n\tassert.NotNil(ds, \"Server service not instanced\")\n\n\t// wrong json\n\tevIn := []byte{10, 20, 30}\n\n\t// call service\n\tcs.On(\"Get\", fmt.Sprintf(\"/cloud/servers/%s/events\", serverID)).Return(evIn, 200, nil)\n\tevOut, err := ds.GetEventsList(serverID)\n\n\tassert.NotNil(err, \"We are expecting a marshalling error\")\n\tassert.Nil(evOut, \"Expecting nil output\")\n\tassert.Contains(err.Error(), \"invalid character\", \"Error message should include the string 'invalid character'\")\n\n\treturn evOut\n}", "func (_m *DBClient) GetTransmissionsByNotificationSlugAndStartEnd(slug string, start int64, end int64, limit int) ([]models.Transmission, error) {\n\tret := _m.Called(slug, start, end, limit)\n\n\tvar r0 []models.Transmission\n\tif rf, ok := ret.Get(0).(func(string, int64, int64, int) []models.Transmission); ok {\n\t\tr0 = rf(slug, start, end, limit)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]models.Transmission)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, int64, int64, int) error); ok {\n\t\tr1 = rf(slug, start, end, limit)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *DBClient) GetNotificationsByEnd(end int64, limit int) ([]models.Notification, error) {\n\tret := _m.Called(end, limit)\n\n\tvar r0 []models.Notification\n\tif rf, ok := ret.Get(0).(func(int64, int) []models.Notification); ok {\n\t\tr0 = rf(end, limit)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]models.Notification)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64, int) error); ok {\n\t\tr1 = rf(end, limit)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}" ]
[ "0.67549837", "0.6047971", "0.60382354", "0.5892229", "0.5887458", "0.588709", "0.5847266", "0.58460593", "0.58450013", "0.5806093", "0.5781316", "0.5730033", "0.5698806", "0.56369007", "0.56117475", "0.5567934", "0.55019575", "0.54096115", "0.5402011", "0.5381635", "0.53764844", "0.53676665", "0.53654337", "0.53568846", "0.5306836", "0.5292613", "0.5282262", "0.5257478", "0.52534837", "0.5238566", "0.52277434", "0.5209858", "0.51672846", "0.51516426", "0.5137311", "0.51181847", "0.5109021", "0.51017827", "0.5085204", "0.5083406", "0.50825185", "0.5080762", "0.5063512", "0.5055138", "0.5033257", "0.5025542", "0.5012162", "0.49997994", "0.49949655", "0.4985319", "0.4969653", "0.4963831", "0.49572816", "0.49392802", "0.49308676", "0.4894988", "0.48947433", "0.48813722", "0.48696515", "0.48669994", "0.48592636", "0.485816", "0.4852567", "0.4850089", "0.48481596", "0.48279434", "0.48150036", "0.4798258", "0.47980717", "0.47965032", "0.47943547", "0.4788486", "0.47781298", "0.4775132", "0.47638372", "0.47595295", "0.47413972", "0.47370112", "0.4728941", "0.47224423", "0.47161853", "0.47116345", "0.47098747", "0.47097367", "0.47025096", "0.4694632", "0.46883008", "0.46866688", "0.46813124", "0.46658465", "0.46610606", "0.46591148", "0.46556708", "0.4655405", "0.46538886", "0.46527442", "0.46455818", "0.464067", "0.46394157", "0.46394086" ]
0.78118217
0
incrementVersion provides a mock function with given fields:
func (_m *MockAggregate) incrementVersion() { _m.Called() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockAggregate) setVersion(_a0 int) {\n\t_m.Called(_a0)\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func (_m *MockAggregate) Version() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (m *MockEventLogger) Version() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockqueueTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockqueueTaskInfo) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockTask) SetVersion(version int64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetVersion\", version)\n}", "func (_m *MockAggregate) OriginalVersion() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func (m *MockFullNode) Version(arg0 context.Context) (types0.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\", arg0)\n\tret0, _ := ret[0].(types0.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockShootClients) Version() *version.Info {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(*version.Info)\n\treturn ret0\n}", "func TestSimpleIncrement(t *testing.T) {\n\tv := Version{\n\t\tMajor: 1,\n\t\tMinor: 9,\n\t}\n\tif v.String() != \"1.9.0\" {\n\t\tt.Fatalf(`Expected \"1.9.0\", got \"%s\"`, v.String())\n\t}\n\tv = v.NextMinor()\n\tif v.String() != \"1.10.0\" {\n\t\tt.Fatalf(`Expected \"1.10.0\", got \"%s\"`, v.String())\n\t}\n\tv = v.NextMinor()\n\tif v.String() != \"1.11.0\" {\n\t\tt.Fatalf(`Expected \"1.11.0\", got \"%s\"`, v.String())\n\t}\n}", "func newVersionCheckerMock(version string, tags []string) *VersionChecker {\n\n\tfixedAppVersion := fixVersion(version)\n\n\treturn &VersionChecker{\n\t\tfixedAppVersion: fixedAppVersion,\n\t\tversionSource: &versionCheckerMock{\n\t\t\ttags: tags,\n\t\t\tfixVersionStrFunc: fixVersion,\n\t\t\ttagFilterFunc: versionFilterFunc(fixedAppVersion),\n\t\t},\n\t}\n}", "func (m *MockMachine) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *U2FDevice) Version() (string, error) {\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\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockEventLogger) VersionInitial() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VersionInitial\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockRemotePeer) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockModuleService) UpdateModuleByVersion(arg0 *models.Module) (*models.Module, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateModuleByVersion\", arg0)\n\tret0, _ := ret[0].(*models.Module)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.Register(\"test\", \"json\", NewTestHandler(\"json\", assert))\n\tassert.Nil(err)\n\t// Perform test requests.\n\treq := restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\tresp := ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"1.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"2\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"2.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"3.0\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"4.0.0-alpha\")\n}", "func (r *MockRepoManager) mockUpdate() {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.updateCount++\n}", "func (m *MockClient) PublicVersion() msp.Identity {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublicVersion\")\n\tret0, _ := ret[0].(msp.Identity)\n\treturn ret0\n}", "func (m *MockVersion) UpdateVersion(keyName, newVersion string) error {\n\targs := m.Called()\n\treturn args.Error(0)\n}", "func (r *MockRepoManager) mockNextRollRev(hash string) {\n\tr.mtx.Lock()\n\tdefer r.mtx.Unlock()\n\tr.skiaHead = hash\n}", "func (m *MockPacketHandler) GetVersion() protocol.VersionNumber {\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(protocol.VersionNumber)\n\treturn ret0\n}", "func MockKernelVersion(version string) (restore func()) {\n\told := KernelVersion\n\tKernelVersion = func() string { return version }\n\treturn func() {\n\t\tKernelVersion = old\n\t}\n}", "func TestMakeUpVersion(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tmajor uint8\n\t\tminor uint8\n\t\tfix uint8\n\t\twant uint32\n\t}{\n\t\t{\n\t\t\tname: \"MakeUpversionTest\",\n\t\t\tmajor: FixVersion,\n\t\t\tminor: MinorVersion,\n\t\t\tfix: FixVersion,\n\t\t\twant: 16843008,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := makeUpVersion(tt.major, tt.minor, tt.fix); got != tt.want {\n\t\t\t\tt.Errorf(\"makeUpVersion() = %v, majorVersion %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (m *Mock) Version() string {\n\treturn defaultMockVersion\n}", "func (m *MockKernelData) PatchVersion(kernelFullVersion string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PatchVersion\", kernelFullVersion)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *System) Version() (types.Text, error) {\n\tret := _m.Called()\n\n\tvar r0 types.Text\n\tif rf, ok := ret.Get(0).(func() types.Text); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(types.Text)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestGetVersion(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(false, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\n\ttrustAgentService.router.HandleFunc(\"/version\", errorHandler(getVersion())).Methods(\"GET\")\n\n\t// test request\n\trequest, err := http.NewRequest(\"GET\", \"/version\", nil)\n\tassert.NoError(err)\n\n\trecorder := httptest.NewRecorder()\n\tresponse := recorder.Result()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tassert.Equal(http.StatusOK, response.StatusCode)\n\tfmt.Printf(\"Version: %s\\n\", recorder.Body.String())\n\tassert.NotEmpty(recorder.Body.String())\n}", "func (m *MockTenantServiceDao) UpdateDeployVersion(serviceID, deployversion string) error {\n\tret := m.ctrl.Call(m, \"UpdateDeployVersion\", serviceID, deployversion)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func IncrementStatisticVersion(settings *playfab.Settings, postData *IncrementStatisticVersionRequestModel, entityToken string) (*IncrementStatisticVersionResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/Statistic/IncrementStatisticVersion\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &IncrementStatisticVersionResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func (a *BaseAggregateSourced) IncrementVersion() {\n\ta.Version = a.Version + 1\n}", "func TestVersion(t *testing.T) {\n\t//fmt.Println(\"EliteProvision [\" + Version() + \"]\")\n}", "func (mock *PluginerMock) VersionCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockVersion.RLock()\n\tcalls = mock.calls.Version\n\tmock.lockVersion.RUnlock()\n\treturn calls\n}", "func (_m *CIPDClient) ResolveVersion(ctx context.Context, packageName string, version string) (common.Pin, error) {\n\tret := _m.Called(ctx, packageName, version)\n\n\tvar r0 common.Pin\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string) common.Pin); ok {\n\t\tr0 = rf(ctx, packageName, version)\n\t} else {\n\t\tr0 = ret.Get(0).(common.Pin)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {\n\t\tr1 = rf(ctx, packageName, version)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockMetricsProvider) IncreaseGithubCacheHits(method, handler string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"IncreaseGithubCacheHits\", method, handler)\n}", "func TestGetVersion(t *testing.T) {\n\ttests := []struct {\n\t\tversion string\n\t\tcommit string\n\t\tdate string\n\t\texpect string\n\t\tshortOutput bool\n\t}{\n\t\t{\n\t\t\t\"a\",\n\t\t\t\"b\",\n\t\t\t\"c\",\n\t\t\t\"waver version: a from commit b built on c\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4\",\n\t\t\t\"5b1a61f9b58e3778986c99b1282840ce64329614\",\n\t\t\t\"Thu May 21 16:48:18 PDT 2020\",\n\t\t\t\"waver version: v0.12.4 from commit 5b1a61f9b58e3778986c99b1282840ce64329614 built on Thu May 21 16:48:18 PDT 2020\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"waver version: v0.12.4-rc5 from commit 5b1a61f9b58 built on 1590105848\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\ttrue,\n\t\t},\n\t}\n\n\t// save the current global variables so they can be set back after testing\n\toldVal := version\n\toldCommit := commit\n\toldDate := date\n\n\tfor _, test := range tests {\n\t\t// run through each test, should not be run in parallel.\n\t\tversion = test.version\n\t\tcommit = test.commit\n\t\tdate = test.date\n\n\t\t// build the new Cobra command and configure stdout and args\n\t\tv := Get(test.shortOutput)\n\n\t\t// assert output string matches expectations\n\t\tassert.Equal(t, test.expect, v)\n\t}\n\n\t// put the original build values back after tests have run\n\tversion = oldVal\n\tcommit = oldCommit\n\tdate = oldDate\n}", "func (s *suite) Test_QueryNextVersion_happy_path(c *C) {\n\tserver := NewMockServer().WithBody(`1.0`).Start(c)\n\tdefer server.Stop()\n\n\tunit := NewRemoteInventory(server.URL, \"token\", \"\", \"\", false)\n\tversion, err := unit.QueryNextVersion(\"query-project\", \"name\", \"1.@\")\n\tserver.ExpectCalled(c, true, queryNextVersionURL)\n\tc.Assert(err, IsNil)\n\tc.Assert(version, Equals, \"1.0\")\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func (_m *LambdaAPI) PublishVersion(_a0 *lambda.PublishVersionInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestDaemon_Version(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\tv, err := d.Version(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif v != testVersion {\n\t\tt.Fatalf(\"Expected %v but got %v\", testVersion, v)\n\t}\n}", "func (_m *LambdaAPI) PublishVersionRequest(_a0 *lambda.PublishVersionInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func TestVersionStorage(openStorage func() storage.ChunkStorage, closeStorage func(storage.ChunkStorage),\n\tresetStorage func(), t *testing.T) {\n\tassert := testifyAssert.New(t)\n\n\tvar s storage.ChunkStorage = nil\n\n\ttest := func(name string, run func()) {\n\t\tt.Logf(\"subtest: %s\", name)\n\t\tresetStorage()\n\t\ts = openStorage()\n\t\tdefer func() {\n\t\t\tif s != nil {\n\t\t\t\tcloseStorage(s)\n\t\t\t\ts = nil\n\t\t\t}\n\t\t}()\n\t\trun()\n\t}\n\n\treopen := func() {\n\t\tcloseStorage(s)\n\t\t// no reset\n\t\ts = openStorage()\n\t}\n\n\ttest(\"empty by default\", func() {\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(chunks)\n\t})\n\n\ttest(\"cannot get nonexistent latest\", func() {\n\t\t_, err := s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"cannot delete nonexistent version\", func() {\n\t\terr := s.DeleteLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"write single version corrolaries\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\t_, err = s.GetLatestVersion(72)\n\t\tassert.Error(err)\n\n\t\t_, err = s.GetLatestVersion(70)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"updating versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"updating versions with durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"delete subset of versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete subset of versions with durabilitiy\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\treopen()\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\treopen()\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete all versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\t\tassert.NoError(s.DeleteLatestVersion(72))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(versions)\n\n\t\t_, err = s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n}", "func (t *targetrunner) increaseObjectVersion(fqn string) (newVersion string, errstr string) {\n\tconst initialVersion = \"1\"\n\tvar (\n\t\terr error\n\t\tvbytes []byte\n\t)\n\t_, err = os.Stat(fqn)\n\tif err != nil && os.IsNotExist(err) {\n\t\tnewVersion = initialVersion\n\t\treturn\n\t}\n\tif err != nil {\n\t\terrstr = fmt.Sprintf(\"Unexpected failure to read stats of file %s, err: %v\", fqn, err)\n\t\treturn\n\t}\n\n\tif vbytes, errstr = Getxattr(fqn, XattrObjVersion); errstr != \"\" {\n\t\treturn\n\t}\n\tif currValue, err := strconv.Atoi(string(vbytes)); err != nil {\n\t\tnewVersion = initialVersion\n\t} else {\n\t\tnewVersion = fmt.Sprintf(\"%d\", currValue+1)\n\t}\n\n\treturn\n}", "func (m *MockRelease) ReleaseMajor(push bool) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ReleaseMajor\", push)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestSuccessfullyUpdateVersion(t *testing.T) {\n\tids, err := helpers.GetIDsAndTimestamps()\n\tif err != nil {\n\t\tlog.ErrorC(\"unable to generate mongo timestamp\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tdatasetAPI := httpexpect.New(t, cfg.DatasetAPIURL)\n\n\tneo4JStore, err := neo4j.NewDatastore(cfg.Neo4jAddr, \"\", neo4j.GenericHierarchyCPIHTestData)\n\tif err != nil {\n\t\tt.Errorf(\"unable to connect to neo4j. error: [%v]\\n\", err)\n\t\tlog.ErrorC(\"unable to connect to neo4j\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tConvey(\"Given an unpublished dataset, edition and version\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceEditionConfirmed, ids.UniqueTimestamp, 1)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceEditionConfirmed)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update meta data against the version resource\", func() {\n\t\t\tConvey(\"Then version resource is updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionMetaDataJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.ReleaseDate, ShouldEqual, \"2018-11-11\")\n\t\t\t\tSo(len(*updatedVersion.UsageNotes), ShouldEqual, 2)\n\n\t\t\t\tSo((*updatedVersion.UsageNotes)[0].Title, ShouldEqual, \"Coefficients of variation\")\n\n\t\t\t\talert := mongo.Alert{\n\t\t\t\t\tDescription: \"All data entries (observations) for Plymouth have been updated\",\n\t\t\t\t\tDate: \"2017-04-05\",\n\t\t\t\t\tType: \"Correction\",\n\t\t\t\t}\n\n\t\t\t\talertList := &[]mongo.Alert{alert}\n\n\t\t\t\tSo(updatedVersion.Alerts, ShouldResemble, alertList)\n\n\t\t\t\tlatestChange := mongo.LatestChange{\n\t\t\t\t\tDescription: \"change to the period frequency from quarterly to monthly\",\n\t\t\t\t\tName: \"Changes to the period frequency\",\n\t\t\t\t\tType: \"Summary of Changes\",\n\t\t\t\t}\n\n\t\t\t\tlatestChangesList := []mongo.LatestChange{latestChange}\n\n\t\t\t\tSo(updatedVersion.LatestChanges, ShouldResemble, latestChangesList)\n\n\t\t\t\tSo(updatedVersion.Links.Spatial.HRef, ShouldEqual, \"http://ons.gov.uk/new-geography-list\")\n\n\t\t\t\t// Check self link does not update - the only link that can be updated is `spatial`\n\t\t\t\tSo(updatedVersion.Links.Self.HRef, ShouldNotEqual, \"http://bogus/bad-link\")\n\n\t\t\t\ttemporal := mongo.TemporalFrequency{\n\t\t\t\t\tStartDate: \"2014-11-11\",\n\t\t\t\t\tEndDate: \"2017-11-11\",\n\t\t\t\t\tFrequency: \"monthly\",\n\t\t\t\t}\n\n\t\t\t\ttemporalList := []mongo.TemporalFrequency{temporal}\n\n\t\t\t\tSo(updatedVersion.Temporal, ShouldResemble, temporalList)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of associated\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToAssociatedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"associated\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"associated\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedWithCollectionIDJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated, and CollectionID removed\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tlog.Debug(\"edition id\", log.Data{\"edition_id\": ids.EditionUnpublished})\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, and CollectionID removed\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tinstanceProps, err := neo4JStore.GetInstanceProperties(ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"failed to get properties from neo4j instance node\", err, nil)\n\t\t\t\t\tt.FailNow()\n\t\t\t\t}\n\n\t\t\t\tSo(instanceProps[\"is_published\"], ShouldBeTrue)\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceEditionConfirmed); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given an unpublished dataset, edition and a version that has been associated\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 2)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\t// TODO Remove skipped tests when code has been refactored (and hence fixed)\n\t\t// 1 test skipped\n\t\tSkipConvey(\"When a PUT request to update version resource to remove collection id\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated accordingly and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionFromAssociatedToEditionConfirmedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"edition-confirmed\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"edition-confirmed\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetAssociated+\"/editions/2018/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetAssociated, 0))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given a published dataset and edition, and a version that has been associated\", t, func() {\n\t\tedition := \"2017\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetPublished, ids.EditionPublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 3)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.Fail()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetPublished, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionPublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetPublished+\"/editions/2017/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetPublished)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetPublished, 1))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n}", "func (c *cachestub) RecordVersion(token, version string) (*cache.Record, error) {\n\treturn &cache.Record{}, nil\n}", "func (_m *MockBackend) ProtocolVersion() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (_m *Version) UpdateWarningVersion(_a0 string) (string, bool, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 bool\n\tif rf, ok := ret.Get(1).(func(string) bool); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Get(1).(bool)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(_a0)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockContext) UpdateNamespaceNotificationVersion(namespaceNotificationVersion int64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateNamespaceNotificationVersion\", namespaceNotificationVersion)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockPromMetrics) IncUpdate() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"IncUpdate\")\n}", "func (_m *ChannelStore) IncrementMentionCount(channelID string, userIDs []string, isRoot bool) error {\n\tret := _m.Called(channelID, userIDs, isRoot)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, []string, bool) error); ok {\n\t\tr0 = rf(channelID, userIDs, isRoot)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockProductCatalog) UpdateVersionForEditor(arg0 context.Context, arg1 db.UpdateVersionForEditorParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateVersionForEditor\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *FakeApiServer) Update(arg0 schema.GroupVersionResource, arg1 string, arg2 runtime.Object) (runtime.Object, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(runtime.Object)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProductCatalog) UpdateVersionCatalog(arg0 context.Context, arg1 db.UpdateVersionCatalogParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateVersionCatalog\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func (m *MockDeployedVersionFinder) OpenSourceVersion(ctx context.Context, installNamespace string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OpenSourceVersion\", ctx, installNamespace)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockContext) GetNamespaceNotificationVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetNamespaceNotificationVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockVersionInfoDao) GetVersionByDeployVersion(version, serviceID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByDeployVersion\", version, serviceID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeystore) Update(keyValues []keystoreregistry.KeyValueVersion) error {\n\tret := m.ctrl.Call(m, \"Update\", keyValues)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockChefIngesterServer) GetVersion(arg0 context.Context, arg1 *VersionRequest) (*Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\", arg0, arg1)\n\tret0, _ := ret[0].(*Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (v *Version) IncrementBasedOnLevel(level string) error {\n\tfailed := false\n\n\tswitch level {\n\tcase \"major\":\n\t\tv.NextMajor()\n\n\tcase \"minor\":\n\t\tv.NextMinor()\n\n\tcase \"patch\":\n\t\tv.NextPatch()\n\n\tcase \"suffix-only\":\n\t\t// do nothing with version itself\n\n\tdefault:\n\t\tfailed = true\n\t}\n\n\tif failed {\n\t\treturn errors.New(\"invalid level\")\n\t}\n\n\treturn nil\n}", "func (_m *URLRepository) IncreaseURLNoOfHits(ctx context.Context, shortCode string) error {\n\tret := _m.Called(ctx, shortCode)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, string) error); ok {\n\t\tr0 = rf(ctx, shortCode)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *VersionInterface) GetVersion(ctx context.Context, r *admin.GetVersionRequest) (*admin.GetVersionResponse, error) {\n\tret := _m.Called(ctx, r)\n\n\tvar r0 *admin.GetVersionResponse\n\tif rf, ok := ret.Get(0).(func(context.Context, *admin.GetVersionRequest) *admin.GetVersionResponse); ok {\n\t\tr0 = rf(ctx, r)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*admin.GetVersionResponse)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *admin.GetVersionRequest) error); ok {\n\t\tr1 = rf(ctx, r)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *Manager) Update(ctx context.Context, projectID int64, meta map[string]string) error {\n\tret := _m.Called(ctx, projectID, meta)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, int64, map[string]string) error); ok {\n\t\tr0 = rf(ctx, projectID, meta)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockVersion) GetVersion(keyName string) (string, error) {\n\targs := m.Called()\n\treturn args.String(0), args.Error(1)\n}", "func (m *MockKubernetesService) Upgrade(clusterID, versionSlug string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Upgrade\", clusterID, versionSlug)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestGetVersion(t *testing.T) {\n\tv := \"0.0.0\"\n\tmaj, min, patch := getVersion(v)\n\n\tif maj != 0 && min != 0 && patch != 0 {\n\t\tt.Error(\"maj, min or patch are not set to 0\", maj, min, patch)\n\t}\n\n\tv = \"1.2.4\"\n\n\tmaj, min, patch = getVersion(v)\n\n\tif maj != 1 && min != 2 && patch != 4 {\n\t\tt.Error(\"maj, min or patch are not set to 1, 2, 4\", maj, min, patch)\n\t}\n}", "func (_m *Repository) Upvote(userID int64, catItemID string, increment int) error {\n\tret := _m.Called(userID, catItemID, increment)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(int64, string, int) error); ok {\n\t\tr0 = rf(userID, catItemID, increment)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *ObjectVersioner) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error) {\n\tret := _m.Called(in, gv)\n\n\tvar r0 runtime.Object\n\tif rf, ok := ret.Get(0).(func(runtime.Object, runtime.GroupVersioner) runtime.Object); ok {\n\t\tr0 = rf(in, gv)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(runtime.Object)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(runtime.Object, runtime.GroupVersioner) error); ok {\n\t\tr1 = rf(in, gv)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func TestVersion(t *testing.T) {\n\tfor _, v := range versionTests {\n\t\tp, e := model.ParseVersion(v[0])\n\t\tassert.Nil(t, e, \"Should have parsed %s\", v)\n\t\tassert.Equal(t, p.String(), v[1], \"Should be equal %s==%s\", p.String(), v)\n\t}\n}", "func (m *MockFullNode) StateNetworkVersion(arg0 context.Context, arg1 types0.TipSetKey) (network.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateNetworkVersion\", arg0, arg1)\n\tret0, _ := ret[0].(network.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVersionInfoDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *Repository) Update(condition *entities.User, _a1 *entities.User) (uint, error) {\n\tret := _m.Called(condition, _a1)\n\n\tvar r0 uint\n\tif rf, ok := ret.Get(0).(func(*entities.User, *entities.User) uint); ok {\n\t\tr0 = rf(condition, _a1)\n\t} else {\n\t\tr0 = ret.Get(0).(uint)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*entities.User, *entities.User) error); ok {\n\t\tr1 = rf(condition, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockEKSServiceInterface) UpdateNodegroupVersion(input *eks.UpdateNodegroupVersionInput) (*eks.UpdateNodegroupVersionOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateNodegroupVersion\", input)\n\tret0, _ := ret[0].(*eks.UpdateNodegroupVersionOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConn) Set(path string, data []byte, version int32) (*zk.Stat, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Set\", path, data, version)\n\tret0, _ := ret[0].(*zk.Stat)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestVersion(t *testing.T) {\n\n\ttests := []struct {\n\t\tInput driver.Version\n\t\tMajor int\n\t\tMinor int\n\t\tSub string\n\t\tSubInt int\n\t\tSubIsInt bool\n\t}{\n\t\t{\"1.2.3\", 1, 2, \"3\", 3, true},\n\t\t{\"\", 0, 0, \"\", 0, false},\n\t\t{\"1.2.3a\", 1, 2, \"3a\", 0, false},\n\t\t{\"13.12\", 13, 12, \"\", 0, false},\n\t}\n\n\tfor _, test := range tests {\n\t\tif v := test.Input.Major(); v != test.Major {\n\t\t\tt.Errorf(\"Major failed for '%s', expected %d, got %d\", test.Input, test.Major, v)\n\t\t}\n\t\tif v := test.Input.Minor(); v != test.Minor {\n\t\t\tt.Errorf(\"Minor failed for '%s', expected %d, got %d\", test.Input, test.Minor, v)\n\t\t}\n\t\tif v := test.Input.Sub(); v != test.Sub {\n\t\t\tt.Errorf(\"Sub failed for '%s', expected '%s', got '%s'\", test.Input, test.Sub, v)\n\t\t}\n\t\tif v, vIsInt := test.Input.SubInt(); vIsInt != test.SubIsInt || v != test.SubInt {\n\t\t\tt.Errorf(\"SubInt failed for '%s', expected (%d,%v), got (%d,%v)\", test.Input, test.SubInt, test.SubIsInt, v, vIsInt)\n\t\t}\n\t}\n}", "func (m *MockRepository) Update(tag *models.RestTag) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Update\", tag)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestSwizzlerOffsetMetadataVersion(t *testing.T) {\n\tf, origMeta := createNewSwizzler(t)\n\n\tf.OffsetMetadataVersion(\"targets/a\", -2)\n\n\tfor role, metaBytes := range origMeta {\n\t\tnewMeta, err := f.MetadataCache.GetSized(role.String(), store.NoSizeLimit)\n\t\trequire.NoError(t, err)\n\n\t\tif role != \"targets/a\" {\n\t\t\trequire.True(t, bytes.Equal(metaBytes, newMeta), \"bytes have changed for role %s\", role)\n\t\t} else {\n\t\t\trequire.False(t, bytes.Equal(metaBytes, newMeta))\n\t\t\torigSigned, newSigned := &data.SignedMeta{}, &data.SignedMeta{}\n\t\t\trequire.NoError(t, json.Unmarshal(metaBytes, origSigned))\n\t\t\trequire.NoError(t, json.Unmarshal(newMeta, newSigned))\n\t\t\trequire.Equal(t, 1, origSigned.Signed.Version)\n\t\t\trequire.Equal(t, -1, newSigned.Signed.Version)\n\t\t}\n\t}\n}", "func (m *MockPodiumInterface) IncrementScore(arg0 context.Context, arg1, arg2 string, arg3, arg4 int) (*client.MemberList, error) {\n\tret := m.ctrl.Call(m, \"IncrementScore\", arg0, arg1, arg2, arg3, arg4)\n\tret0, _ := ret[0].(*client.MemberList)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockDraOp) IncRefCnt(id string) (*Ref, error) {\n\tret := _m.ctrl.Call(_m, \"IncRefCnt\", id)\n\tret0, _ := ret[0].(*Ref)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test4(t *testing.T) {\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection.Spec.RepositoryUrl = \"https://github.com/some/collection/alternate-kabanero-index.yaml\"\n\tnewCollection.Spec.Version = \"4.5.6\"\n\tnewCollection.Spec.DesiredState = \"inactive\"\n\terr := processUpdate(&mutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tRepositoryUrl: \"https://github.com/some/collection/alternate-kabanero-index.yaml\",\n\t\tVersion: \"4.5.6\",\n\t\tDesiredState: \"inactive\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n}", "func (m MockRepositoryStore) IncrementGeneration(ctx context.Context, repositoryID int64, primary string, secondaries []string) error {\n\tif m.IncrementGenerationFunc == nil {\n\t\treturn nil\n\t}\n\n\treturn m.IncrementGenerationFunc(ctx, repositoryID, primary, secondaries)\n}", "func (_m *Repository) Update(ctx context.Context, _a1 *models.Host) error {\n\tret := _m.Called(ctx, _a1)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, *models.Host) error); ok {\n\t\tr0 = rf(ctx, _a1)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockAPI) UpdateIgnitionEndpointToken(arg0 context.Context, arg1 *gorm.DB, arg2 *models.Host, arg3 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateIgnitionEndpointToken\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestVersion(t *testing.T) {\n\tvers := Version()\n\tif len(vers) == 0 {\n\t\tt.Error(\"version string is not present\")\n\t}\n}", "func NewObjectVersioner(t mockConstructorTestingTNewObjectVersioner) *ObjectVersioner {\n\tmock := &ObjectVersioner{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func TestHandleGetVersion(t *testing.T) {\n\tsv := ServerVersion{Version:\"v1\", IP:\"127.0.0.1\", Port:8080}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/version\", sv.handGetVersion)\n\n\twriter := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/version\", nil)\n\tmux.ServeHTTP(writer, req)\n\n\tfmt.Println(writer.Body.String())\n}", "func (m *MockManager) SerializeReleaseName(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeReleaseName\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *Mocklibrarian) AddToLibrary(binary autoupdatableBinary, currentVersion string, targetFilename string, targetMetadata data.TargetFileMeta) error {\n\tret := _m.Called(binary, currentVersion, targetFilename, targetMetadata)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(autoupdatableBinary, string, string, data.TargetFileMeta) error); ok {\n\t\tr0 = rf(binary, currentVersion, targetFilename, targetMetadata)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (rs *RedisService) IncrementVersion(system string, collection string) (int64, error) {\n\tconn := rs.pool.Get()\n\tdefer conn.Close()\n\n\tfield := system + \"_\" + collection\n\tnewVersion, err := redis.Int64(conn.Do(\"HINCRBY\", systemsCollectionVersionsKey, field, 1))\n\tnoticeError(err)\n\tif err != nil && err != redis.ErrNil {\n\t\treturn 0, err\n\t}\n\n\treturn newVersion, nil\n}", "func (m *MockQueueManager) UpdateAckLevel(ctx context.Context, messageID int64, clusterName string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateAckLevel\", ctx, messageID, clusterName)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantPluginBuildVersionDao) UpdateModel(arg0 model.Interface) error {\n\tret := m.ctrl.Call(m, \"UpdateModel\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *mockStore) GetCurrentVersion() (time.Time, error) {\n\treturn m.version, nil\n}", "func (_m *MockService) Update(ctx context.Context, clusterID uint, serviceName string, spec map[string]interface{}) (_result_0 error) {\n\tret := _m.Called(ctx, clusterID, serviceName, spec)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, uint, string, map[string]interface{}) error); ok {\n\t\tr0 = rf(ctx, clusterID, serviceName, spec)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockMetricsProvider) IncreaseGithubCacheMisses(method, handler string) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"IncreaseGithubCacheMisses\", method, handler)\n}", "func (_m *MutableNodeStatus) IncrementAttempts() uint32 {\n\tret := _m.Called()\n\n\tvar r0 uint32\n\tif rf, ok := ret.Get(0).(func() uint32); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(uint32)\n\t}\n\n\treturn r0\n}", "func (m *MockVersionInfoDao) GetVersionByEventID(eventID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByEventID\", eventID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockUserProvider) UpdateLastLoginAt(id int64) (int64, error) {\n\tret := _m.Called(id)\n\n\tvar r0 int64\n\tif rf, ok := ret.Get(0).(func(int64) int64); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tr0 = ret.Get(0).(int64)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(int64) error); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}" ]
[ "0.6878722", "0.6719195", "0.6694321", "0.66044044", "0.63764864", "0.6363949", "0.620103", "0.615884", "0.61135453", "0.6080862", "0.6059925", "0.60365295", "0.60349417", "0.5980796", "0.5962855", "0.5956764", "0.5921386", "0.591762", "0.58893186", "0.587819", "0.57154053", "0.56960267", "0.5691761", "0.56813055", "0.5673572", "0.5666076", "0.56628495", "0.56516546", "0.5649745", "0.5535436", "0.5529076", "0.55195475", "0.55193484", "0.54930454", "0.5469226", "0.54387057", "0.5433297", "0.54263324", "0.54038584", "0.53948796", "0.5370251", "0.536489", "0.5363703", "0.53601307", "0.5356414", "0.53456074", "0.53397626", "0.5328414", "0.53224313", "0.52850604", "0.52837837", "0.52647835", "0.5252409", "0.5251087", "0.5221571", "0.5218416", "0.5203277", "0.51836705", "0.516993", "0.5156524", "0.51336384", "0.51249784", "0.5124707", "0.51188576", "0.51179457", "0.5108931", "0.51082796", "0.5090787", "0.50785625", "0.5074368", "0.50654393", "0.50569636", "0.50428355", "0.50373256", "0.50316507", "0.5015651", "0.5015609", "0.5013738", "0.50083077", "0.49995282", "0.49963835", "0.49945104", "0.4991916", "0.49833816", "0.4977998", "0.49719313", "0.4967672", "0.49647552", "0.49590322", "0.495585", "0.4955046", "0.4954958", "0.4946128", "0.4945394", "0.49434096", "0.4942565", "0.49421713", "0.4939649", "0.4938345", "0.4938312" ]
0.8021044
0
setVersion provides a mock function with given fields: _a0
func (_m *MockAggregate) setVersion(_a0 int) { _m.Called(_a0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_m *MockAggregate) incrementVersion() {\n\t_m.Called()\n}", "func (_m *MockAggregate) Version() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func newVersionCheckerMock(version string, tags []string) *VersionChecker {\n\n\tfixedAppVersion := fixVersion(version)\n\n\treturn &VersionChecker{\n\t\tfixedAppVersion: fixedAppVersion,\n\t\tversionSource: &versionCheckerMock{\n\t\t\ttags: tags,\n\t\t\tfixVersionStrFunc: fixVersion,\n\t\t\ttagFilterFunc: versionFilterFunc(fixedAppVersion),\n\t\t},\n\t}\n}", "func (_m *U2FDevice) Version() (string, error) {\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\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockEventLogger) Version() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockManager) UpdateVersion() {\n\tm.ctrl.Call(m, \"UpdateVersion\")\n}", "func (m *MockShootClients) Version() *version.Info {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(*version.Info)\n\treturn ret0\n}", "func TestGetVersions4A(t *testing.T) {\n}", "func (m *Mock) Version() string {\n\treturn defaultMockVersion\n}", "func (m *MockFullNode) Version(arg0 context.Context) (types0.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\", arg0)\n\tret0, _ := ret[0].(types0.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *MockAggregate) OriginalVersion() int {\n\tret := _m.Called()\n\n\tvar r0 int\n\tif rf, ok := ret.Get(0).(func() int); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int)\n\t}\n\n\treturn r0\n}", "func TestVersion(t *testing.T) {\n\tassert := audit.NewTestingAssertion(t, true)\n\t// Setup the test server.\n\tmux := newMultiplexer(assert)\n\tts := restaudit.StartServer(mux, assert)\n\tdefer ts.Close()\n\terr := mux.Register(\"test\", \"json\", NewTestHandler(\"json\", assert))\n\tassert.Nil(err)\n\t// Perform test requests.\n\treq := restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\tresp := ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"1.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"2\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"2.0.0\")\n\n\treq = restaudit.NewRequest(\"GET\", \"/base/test/json/4711?foo=0815\")\n\treq.AddHeader(restaudit.HeaderAccept, restaudit.ApplicationJSON)\n\treq.AddHeader(\"Version\", \"3.0\")\n\tresp = ts.DoRequest(req)\n\tresp.AssertStatusEquals(200)\n\tresp.AssertHeaderEquals(\"Version\", \"4.0.0-alpha\")\n}", "func (m *MockqueueTaskInfo) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func (m *MockqueueTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func MockKernelVersion(version string) (restore func()) {\n\told := KernelVersion\n\tKernelVersion = func() string { return version }\n\treturn func() {\n\t\tKernelVersion = old\n\t}\n}", "func (_m *LambdaAPI) PublishVersion(_a0 *lambda.PublishVersionInput) (*lambda.FunctionConfiguration, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_m *System) Version() (types.Text, error) {\n\tret := _m.Called()\n\n\tvar r0 types.Text\n\tif rf, ok := ret.Get(0).(func() types.Text); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(types.Text)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockMachine) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockRemotePeer) Version() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Version\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *Version) UpdateWarningVersion(_a0 string) (string, bool, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 bool\n\tif rf, ok := ret.Get(1).(func(string) bool); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Get(1).(bool)\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string) error); ok {\n\t\tr2 = rf(_a0)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func TestGetVersion(t *testing.T) {\n\tassert := assert.New(t)\n\n\tmockedTpmProvider := new(tpmprovider.MockedTpmProvider)\n\tmockedTpmProvider.On(\"Close\").Return(nil)\n\tmockedTpmProvider.On(\"NvIndexExists\", mock.Anything).Return(false, nil)\n\tmockedTpmProvider.On(\"NvRelease\", mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvDefine\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\tmockedTpmProvider.On(\"NvWrite\", mock.Anything, mock.Anything, mock.Anything).Return(nil)\n\n\tmockedTpmFactory := tpmprovider.MockedTpmFactory{TpmProvider: mockedTpmProvider}\n\n\ttrustAgentService, err := CreateTrustAgentService(CreateTestConfig(), mockedTpmFactory)\n\n\ttrustAgentService.router.HandleFunc(\"/version\", errorHandler(getVersion())).Methods(\"GET\")\n\n\t// test request\n\trequest, err := http.NewRequest(\"GET\", \"/version\", nil)\n\tassert.NoError(err)\n\n\trecorder := httptest.NewRecorder()\n\tresponse := recorder.Result()\n\ttrustAgentService.router.ServeHTTP(recorder, request)\n\tassert.Equal(http.StatusOK, response.StatusCode)\n\tfmt.Printf(\"Version: %s\\n\", recorder.Body.String())\n\tassert.NotEmpty(recorder.Body.String())\n}", "func (_m *Version) VersionFormatter(_a0 string) (string, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string) string); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (mock *PluginerMock) VersionCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tmock.lockVersion.RLock()\n\tcalls = mock.calls.Version\n\tmock.lockVersion.RUnlock()\n\treturn calls\n}", "func (m *MockTask) SetVersion(version int64) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"SetVersion\", version)\n}", "func (m *MockTask) GetVersion() int64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(int64)\n\treturn ret0\n}", "func TestVersion(t *testing.T) {\n\t//fmt.Println(\"EliteProvision [\" + Version() + \"]\")\n}", "func (_m *LambdaAPI) PublishVersionRequest(_a0 *lambda.PublishVersionInput) (*request.Request, *lambda.FunctionConfiguration) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *request.Request\n\tif rf, ok := ret.Get(0).(func(*lambda.PublishVersionInput) *request.Request); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*request.Request)\n\t\t}\n\t}\n\n\tvar r1 *lambda.FunctionConfiguration\n\tif rf, ok := ret.Get(1).(func(*lambda.PublishVersionInput) *lambda.FunctionConfiguration); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*lambda.FunctionConfiguration)\n\t\t}\n\t}\n\n\treturn r0, r1\n}", "func (m *MockPacketHandler) GetVersion() protocol.VersionNumber {\n\tret := m.ctrl.Call(m, \"GetVersion\")\n\tret0, _ := ret[0].(protocol.VersionNumber)\n\treturn ret0\n}", "func (m *MockEventLogger) VersionInitial() uint64 {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"VersionInitial\")\n\tret0, _ := ret[0].(uint64)\n\treturn ret0\n}", "func (m *MockKernelData) FullVersion(arg0 *v1.NodeList) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"FullVersion\", arg0)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestGetVersion(t *testing.T) {\n\ttests := []struct {\n\t\tversion string\n\t\tcommit string\n\t\tdate string\n\t\texpect string\n\t\tshortOutput bool\n\t}{\n\t\t{\n\t\t\t\"a\",\n\t\t\t\"b\",\n\t\t\t\"c\",\n\t\t\t\"waver version: a from commit b built on c\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4\",\n\t\t\t\"5b1a61f9b58e3778986c99b1282840ce64329614\",\n\t\t\t\"Thu May 21 16:48:18 PDT 2020\",\n\t\t\t\"waver version: v0.12.4 from commit 5b1a61f9b58e3778986c99b1282840ce64329614 built on Thu May 21 16:48:18 PDT 2020\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"waver version: v0.12.4-rc5 from commit 5b1a61f9b58 built on 1590105848\",\n\t\t\tfalse,\n\t\t}, {\n\t\t\t\"v0.12.4-rc5\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\t\"1590105848\",\n\t\t\t\"5b1a61f9b58\",\n\t\t\ttrue,\n\t\t},\n\t}\n\n\t// save the current global variables so they can be set back after testing\n\toldVal := version\n\toldCommit := commit\n\toldDate := date\n\n\tfor _, test := range tests {\n\t\t// run through each test, should not be run in parallel.\n\t\tversion = test.version\n\t\tcommit = test.commit\n\t\tdate = test.date\n\n\t\t// build the new Cobra command and configure stdout and args\n\t\tv := Get(test.shortOutput)\n\n\t\t// assert output string matches expectations\n\t\tassert.Equal(t, test.expect, v)\n\t}\n\n\t// put the original build values back after tests have run\n\tversion = oldVal\n\tcommit = oldCommit\n\tdate = oldDate\n}", "func (_m *MockBackend) ProtocolVersion() 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\tr0 = ret.Get(0).(string)\n\t}\n\n\treturn r0\n}", "func (m *MockKernelData) PatchVersion(kernelFullVersion string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PatchVersion\", kernelFullVersion)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MockMinimalRelease(t *testing.T) *Release {\n\tvar r Release\n\terr := json.Unmarshal([]byte(`\n {\n \"release_id\": \"rr\",\n \"project_name\": \"project\",\n \"config_name\": \"config\",\n \"ami\": \"ami-123456\",\n \"subnets\": [\"subnet-1\"],\n \"user_data\": \"echo DATE\",\n \"services\": {\n \"web\": {\n \"instance_type\": \"t2.small\",\n \"security_groups\": [\"web-sg\"]\n }\n }\n }\n `), &r)\n\n\tassert.NoError(t, err)\n\tr.CreatedAt = to.Timep(time.Now())\n\n\treturn &r\n}", "func TestVersion(t *testing.T) {\n\tfor _, v := range versionTests {\n\t\tp, e := model.ParseVersion(v[0])\n\t\tassert.Nil(t, e, \"Should have parsed %s\", v)\n\t\tassert.Equal(t, p.String(), v[1], \"Should be equal %s==%s\", p.String(), v)\n\t}\n}", "func (_AggregatorV2V3Interface *AggregatorV2V3InterfaceCaller) Version(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _AggregatorV2V3Interface.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func TestVersionStorage(openStorage func() storage.ChunkStorage, closeStorage func(storage.ChunkStorage),\n\tresetStorage func(), t *testing.T) {\n\tassert := testifyAssert.New(t)\n\n\tvar s storage.ChunkStorage = nil\n\n\ttest := func(name string, run func()) {\n\t\tt.Logf(\"subtest: %s\", name)\n\t\tresetStorage()\n\t\ts = openStorage()\n\t\tdefer func() {\n\t\t\tif s != nil {\n\t\t\t\tcloseStorage(s)\n\t\t\t\ts = nil\n\t\t\t}\n\t\t}()\n\t\trun()\n\t}\n\n\treopen := func() {\n\t\tcloseStorage(s)\n\t\t// no reset\n\t\ts = openStorage()\n\t}\n\n\ttest(\"empty by default\", func() {\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(chunks)\n\t})\n\n\ttest(\"cannot get nonexistent latest\", func() {\n\t\t_, err := s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"cannot delete nonexistent version\", func() {\n\t\terr := s.DeleteLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"write single version corrolaries\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\t_, err = s.GetLatestVersion(72)\n\t\tassert.Error(err)\n\n\t\t_, err = s.GetLatestVersion(70)\n\t\tassert.Error(err)\n\t})\n\n\ttest(\"write single version durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{71}, chunks)\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\t})\n\n\ttest(\"updating versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"updating versions with durability\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 1))\n\t\tassert.NoError(s.SetLatestVersion(71, 3))\n\n\t\treopen()\n\n\t\tdata, err := s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(3), data)\n\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\n\t\tchunks, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tsortChunkNums(chunks)\n\t\tassert.Equal([]apis.ChunkNum{71, 72}, chunks)\n\n\t\tdata, err = s.GetLatestVersion(71)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(2), data)\n\n\t\tdata, err = s.GetLatestVersion(72)\n\t\tassert.NoError(err)\n\t\tassert.Equal(apis.Version(6), data)\n\t})\n\n\ttest(\"delete subset of versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete subset of versions with durabilitiy\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\treopen()\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\n\t\treopen()\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Equal([]apis.ChunkNum{72}, versions)\n\n\t\tassert.Error(s.DeleteLatestVersion(71))\n\t})\n\n\ttest(\"delete all versions\", func() {\n\t\tassert.NoError(s.SetLatestVersion(71, 2))\n\t\tassert.NoError(s.SetLatestVersion(72, 6))\n\n\t\tassert.NoError(s.DeleteLatestVersion(71))\n\t\tassert.NoError(s.DeleteLatestVersion(72))\n\n\t\tversions, err := s.ListChunksWithLatest()\n\t\tassert.NoError(err)\n\t\tassert.Empty(versions)\n\n\t\t_, err = s.GetLatestVersion(71)\n\t\tassert.Error(err)\n\t})\n}", "func TestDaemon_Version(t *testing.T) {\n\td, start, clean, _, _, _ := mockDaemon(t)\n\tstart()\n\tdefer clean()\n\n\tctx := context.Background()\n\tv, err := d.Version(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"Error: %s\", err.Error())\n\t}\n\tif v != testVersion {\n\t\tt.Fatalf(\"Expected %v but got %v\", testVersion, v)\n\t}\n}", "func TestVersion(t *testing.T) {\n\t// Get Vault client\n\tvaultClientConfig := vault.DefaultConfig()\n\tvaultClientConfig.Address = vaultAddress\n\tv, err := vault.NewClient(vaultClientConfig)\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tv.SetToken(\"root\")\n\tvl := v.Logical()\n\n\t// Get Pachyderm version from plugin\n\tsecret, err := vl.Read(\"/pachyderm/version\")\n\tif err != nil {\n\t\tt.Fatalf(err.Error())\n\t}\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; !ok {\n\t\tt.Fatalf(\"could not get server version from Pachyderm plugin\")\n\t}\n\n\t// Test client-only endpoint\n\tsecret, err = vl.Read(\"/pachyderm/version/client-only\")\n\tif _, ok := secret.Data[\"client-version\"]; !ok {\n\t\tt.Fatalf(\"could not get client version from Pachyderm plugin (client-only)\")\n\t}\n\tif _, ok := secret.Data[\"server-version\"]; ok {\n\t\tt.Fatalf(\"got unexpected server version from Pachyderm plugin (client-only)\")\n\t}\n}", "func TestGetVersion(t *testing.T) {\n\tv := \"0.0.0\"\n\tmaj, min, patch := getVersion(v)\n\n\tif maj != 0 && min != 0 && patch != 0 {\n\t\tt.Error(\"maj, min or patch are not set to 0\", maj, min, patch)\n\t}\n\n\tv = \"1.2.4\"\n\n\tmaj, min, patch = getVersion(v)\n\n\tif maj != 1 && min != 2 && patch != 4 {\n\t\tt.Error(\"maj, min or patch are not set to 1, 2, 4\", maj, min, patch)\n\t}\n}", "func (_BaseFactory *BaseFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockVersionInfoDao) GetVersionByDeployVersion(version, serviceID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByDeployVersion\", version, serviceID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test_LatestVersion(t *testing.T) {\n\tmockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"0.6.1\\n\"))\n\t}))\n\tdefer mockServer.Close()\n\n\tversion, err := latestVersion(mockServer.URL)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\ttestVersion := semver.New(\"0.6.1\")\n\tif !version.Equal(*testVersion) {\n\t\tt.Error(\"Version equality check failed.\")\n\t}\n}", "func (_BaseLibraryFactory *BaseLibraryFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibraryFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestVersion(t *testing.T) {\n\tvers := Version()\n\tif len(vers) == 0 {\n\t\tt.Error(\"version string is not present\")\n\t}\n}", "func NewObjectVersioner(t mockConstructorTestingTNewObjectVersioner) *ObjectVersioner {\n\tmock := &ObjectVersioner{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (m *MockVersion) UpdateVersion(keyName, newVersion string) error {\n\targs := m.Called()\n\treturn args.Error(0)\n}", "func TestGetVersion(t *testing.T) {\n\n\tversion, err := GetVersion()\n\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\n\tif version != \"v1\"{\n\t\tt.Errorf(\"app version not match: %s, expect: %s.\", version, \"v1\")\n\t}\n\n\tfmt.Println(version)\n}", "func (m *MockVersion) GetVersion(keyName string) (string, error) {\n\targs := m.Called()\n\treturn args.String(0), args.Error(1)\n}", "func (m *MockClient) PublicVersion() msp.Identity {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PublicVersion\")\n\tret0, _ := ret[0].(msp.Identity)\n\treturn ret0\n}", "func TestAlfredVersion(t *testing.T) {\n\ttests := []struct {\n\t\tdir string\n\t\tenvvar string\n\t\tx int\n\t\terr bool\n\t}{\n\t\t{rootDirV3, \"\", 3, false},\n\t\t{rootDirV3, \"3\", 3, false},\n\t\t{rootDirV3, \"4\", 4, false},\n\t\t{rootDirV4, \"\", 4, false},\n\t\t{rootDirV4, \"4\", 4, false},\n\t\t{\".\", \"\", 0, true},\n\t\t{\".\", \"four\", 0, true},\n\t}\n\n\tfor _, td := range tests {\n\t\ttd := td // pin variable\n\t\tt.Run(fmt.Sprintf(\"dir=%q, env=%q\", td.dir, td.envvar), func(t *testing.T) {\n\t\t\twithEnv(map[string]string{\n\t\t\t\t\"alfred_version\": td.envvar,\n\t\t\t\t// ensure defaults\n\t\t\t\t\"alfred_workflow_data\": \"\",\n\t\t\t\t\"alfred_workflow_cache\": \"\",\n\t\t\t}, func() {\n\t\t\t\tinfo, err := NewInfo(LibDir(td.dir), testPlist)\n\t\t\t\tif td.err {\n\t\t\t\t\tassert.NotNil(t, err, \"expected error\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trequire.Nil(t, err, \"unexpected error\")\n\t\t\t\tassert.Equal(t, td.x, info.AlfredMajorVersion, \"unexpected version\")\n\t\t\t})\n\t\t})\n\t}\n}", "func (_m *ObjectVersioner) ConvertToVersion(in runtime.Object, gv runtime.GroupVersioner) (runtime.Object, error) {\n\tret := _m.Called(in, gv)\n\n\tvar r0 runtime.Object\n\tif rf, ok := ret.Get(0).(func(runtime.Object, runtime.GroupVersioner) runtime.Object); ok {\n\t\tr0 = rf(in, gv)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(runtime.Object)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(runtime.Object, runtime.GroupVersioner) error); ok {\n\t\tr1 = rf(in, gv)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func GetMockAppVersionList() []models.Version {\n\tversions := []models.Version{\n\t\tmodels.Version{\n\t\t\tID: \"55ebd387-9c68-4137-a367-a12025cc2cdb\",\n\t\t\tVersion: \"1.0\",\n\t\t\tAppID: \"com.aerogear.mobile_app_one\",\n\t\t\tDisabledMessage: \"Please contact an administrator\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 1,\n\t\t\tNumOfAppLaunches: 2,\n\t\t},\n\t\tmodels.Version{\n\t\t\tID: \"59ebd387-9c68-4137-a367-a12025cc1cdb\",\n\t\t\tVersion: \"1.1\",\n\t\t\tAppID: \"com.aerogear.mobile_app_one\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 0,\n\t\t\tNumOfAppLaunches: 0,\n\t\t},\n\t\tmodels.Version{\n\t\t\tID: \"59dbd387-9c68-4137-a367-a12025cc2cdb\",\n\t\t\tVersion: \"1.0\",\n\t\t\tAppID: \"com.aerogear.mobile_app_two\",\n\t\t\tDisabled: false,\n\t\t\tNumOfCurrentInstalls: 0,\n\t\t\tNumOfAppLaunches: 0,\n\t\t},\n\t}\n\n\treturn versions\n}", "func TestHandleGetVersion(t *testing.T) {\n\tsv := ServerVersion{Version:\"v1\", IP:\"127.0.0.1\", Port:8080}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/version\", sv.handGetVersion)\n\n\twriter := httptest.NewRecorder()\n\treq, _ := http.NewRequest(\"GET\", \"/version\", nil)\n\tmux.ServeHTTP(writer, req)\n\n\tfmt.Println(writer.Body.String())\n}", "func (_BaseGroupFactory *BaseGroupFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseGroupFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_m *LambdaAPI) ListVersionsByFunction(_a0 *lambda.ListVersionsByFunctionInput) (*lambda.ListVersionsByFunctionOutput, error) {\n\tret := _m.Called(_a0)\n\n\tvar r0 *lambda.ListVersionsByFunctionOutput\n\tif rf, ok := ret.Get(0).(func(*lambda.ListVersionsByFunctionInput) *lambda.ListVersionsByFunctionOutput); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*lambda.ListVersionsByFunctionOutput)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*lambda.ListVersionsByFunctionInput) error); ok {\n\t\tr1 = rf(_a0)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_BaseAccessWalletFactory *BaseAccessWalletFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWalletFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (a *Action) SetVersion(version interface{}) { a.version = version }", "func (_MetaObject *MetaObjectCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _MetaObject.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestVersion(t *testing.T) {\n\tt.Parallel()\n\n\ttree := writeTree(t, \"\")\n\n\t// There's not much we can robustly assert about the actual version.\n\twant := debug.Version() // e.g. \"master\"\n\n\t// basic\n\t{\n\t\tres := gopls(t, tree, \"version\")\n\t\tres.checkExit(true)\n\t\tres.checkStdout(want)\n\t}\n\n\t// -json flag\n\t{\n\t\tres := gopls(t, tree, \"version\", \"-json\")\n\t\tres.checkExit(true)\n\t\tvar v debug.ServerVersion\n\t\tif res.toJSON(&v) {\n\t\t\tif v.Version != want {\n\t\t\t\tt.Errorf(\"expected Version %q, got %q (%v)\", want, v.Version, res)\n\t\t\t}\n\t\t}\n\t}\n}", "func (_m *CIPDClient) ResolveVersion(ctx context.Context, packageName string, version string) (common.Pin, error) {\n\tret := _m.Called(ctx, packageName, version)\n\n\tvar r0 common.Pin\n\tif rf, ok := ret.Get(0).(func(context.Context, string, string) common.Pin); ok {\n\t\tr0 = rf(ctx, packageName, version)\n\t} else {\n\t\tr0 = ret.Get(0).(common.Pin)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string, string) error); ok {\n\t\tr1 = rf(ctx, packageName, version)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *ManagedAppPolicy) SetVersion(value *string)() {\n m.version = value\n}", "func ReleaseMock(opts *MockReleaseOptions) *release.Release {\n\tdate := time.Unix(242085845, 0).UTC()\n\n\tname := opts.Name\n\tif name == \"\" {\n\t\tname = \"testrelease-\" + string(rand.Intn(100))\n\t}\n\n\tversion := 1\n\tif opts.Version != 0 {\n\t\tversion = opts.Version\n\t}\n\n\tnamespace := opts.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = \"default\"\n\t}\n\n\tch := opts.Chart\n\tif opts.Chart == nil {\n\t\tch = &chart.Chart{\n\t\t\tMetadata: &chart.Metadata{\n\t\t\t\tName: \"foo\",\n\t\t\t\tVersion: \"0.1.0-beta.1\",\n\t\t\t},\n\t\t\tTemplates: []*chart.File{\n\t\t\t\t{Name: \"templates/foo.tpl\", Data: []byte(MockManifest)},\n\t\t\t},\n\t\t}\n\t}\n\n\tscode := release.StatusDeployed\n\tif len(opts.Status) > 0 {\n\t\tscode = opts.Status\n\t}\n\n\treturn &release.Release{\n\t\tName: name,\n\t\tInfo: &release.Info{\n\t\t\tFirstDeployed: date,\n\t\t\tLastDeployed: date,\n\t\t\tStatus: scode,\n\t\t\tDescription: \"Release mock\",\n\t\t},\n\t\tChart: ch,\n\t\tConfig: map[string]interface{}{\"name\": \"value\"},\n\t\tVersion: version,\n\t\tNamespace: namespace,\n\t\tHooks: []*release.Hook{\n\t\t\t{\n\t\t\t\tName: \"pre-install-hook\",\n\t\t\t\tKind: \"Job\",\n\t\t\t\tPath: \"pre-install-hook.yaml\",\n\t\t\t\tManifest: MockHookTemplate,\n\t\t\t\tLastRun: date,\n\t\t\t\tEvents: []release.HookEvent{release.HookPreInstall},\n\t\t\t},\n\t\t},\n\t\tManifest: MockManifest,\n\t}\n}", "func (m *MockModuleService) UpdateModuleByVersion(arg0 *models.Module) (*models.Module, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateModuleByVersion\", arg0)\n\tret0, _ := ret[0].(*models.Module)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test4(t *testing.T) {\n\tnewCollection := mutatingBaseCollectionVersions.DeepCopy()\n\tnewCollection.Spec.RepositoryUrl = \"https://github.com/some/collection/alternate-kabanero-index.yaml\"\n\tnewCollection.Spec.Version = \"4.5.6\"\n\tnewCollection.Spec.DesiredState = \"inactive\"\n\terr := processUpdate(&mutatingBaseCollection, newCollection)\n\tif err != nil {\n\t\tt.Fatal(\"Unexpected error during mutation.\", err)\n\t}\n\n\texpectedversion0 := kabanerov1alpha1.CollectionVersion{\n\t\tRepositoryUrl: \"https://github.com/some/collection/alternate-kabanero-index.yaml\",\n\t\tVersion: \"4.5.6\",\n\t\tDesiredState: \"inactive\"}\n\n\tif newCollection.Spec.Versions[0] != expectedversion0 {\n\t\tt.Fatal(\"New collection.Spec.Versions[0] values do not match expected collection.Spec.Versions[0] values. New versions[0]: \", newCollection.Spec.Versions[0], \"Expected versions[0]: \", expectedversion0)\n\t}\n}", "func (m *MockVersionInfoDao) GetVersionByEventID(eventID string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetVersionByEventID\", eventID)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *WorkforceIntegration) SetApiVersion(value *int32)() {\n m.apiVersion = value\n}", "func (_Ownable *OwnableCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Ownable.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestSetGetGoodArgsFull(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGetGoodArgsFull\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2017-11-21T10:29:49.816Z\"),\n\t[]byte(\"digest1\"),[]byte(\"E0nioxbCYD5AlzGWXDDDl0Gt5AAKv3ppKt4XMhE1rfo\"),\n\t[]byte(\"digest2\"),[]byte(\"xLrbWN5QJBJUAsdevfrxGlN3o0p8VZMnFFnV9iMll5o\"),\n\t[]byte(\"digest3\"),[]byte(\"THIS_IS_DIGEST_3\"),\n\t[]byte(\"digest4\"),[]byte(\"THIS_IS_DIGEST_4\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n\tresGet := stub.MockInvoke(\"1\", [][]byte{[]byte(\"get\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\")})\n\tif resGet.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(resGet.Message))\n\t\tt.FailNow()\n\t}\n}", "func (av *AppVersion) SetVersion(rw http.ResponseWriter, r *http.Request) {\n\tvar passwd, version, downloadURL string\n\n\tif len(r.URL.Query()[\"passwd\"]) > 0 {\n\t\tpasswd = r.URL.Query()[\"passwd\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get passwd\")\n\t\treturn\n\t}\n\tif len(r.URL.Query()[\"version\"]) > 0 {\n\t\tversion = r.URL.Query()[\"version\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get version\")\n\t\treturn\n\t}\n\tif len(r.URL.Query()[\"downloadurl\"]) > 0 {\n\t\tdownloadURL = r.URL.Query()[\"downloadurl\"][0]\n\t} else {\n\t\tav.l.Printf(\"failed to get downloadurl\")\n\t\treturn\n\t}\n\t//fmt.Println(passwd, version, downloadURL)\n\n\tappVersion, _ := av.db.QueryAppVersion()\n\tif appVersion.ID == 0 {\n\t\tappVersion.Passwd = passwd\n\t\tappVersion.Version = version\n\t\tappVersion.DownloadURL = downloadURL\n\t\terr := av.db.InsertAppVerion(&appVersion)\n\t\tif err != nil {\n\t\t\tav.l.Printf(\"failed to insert AppVersion : %s\", err)\n\t\t\treturn\n\t\t}\n\t\tutils.Respond(rw, true)\n\t\treturn\n\t} else if appVersion.Passwd != passwd {\n\t\tav.l.Printf(\"failed to set AppVersion : passwd wrong\")\n\t\treturn\n\t}\n\tappVersion.Version = version\n\tappVersion.DownloadURL = downloadURL\n\terr := av.db.UpdateAppVerion(&appVersion)\n\tif err != nil {\n\t\tav.l.Printf(\"failed to insert AppVersion : %s\", err)\n\t\treturn\n\t}\n\n\tutils.Respond(rw, true)\n\treturn\n}", "func (_Upgradeable *UpgradeableCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _Upgradeable.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func (_PlasmaFramework *PlasmaFrameworkCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _PlasmaFramework.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func TestSetGoodArgs(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgs\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func (m *MockFullNode) StateNetworkVersion(arg0 context.Context, arg1 types0.TipSetKey) (network.Version, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"StateNetworkVersion\", arg0, arg1)\n\tret0, _ := ret[0].(network.Version)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_BaseLibrary *BaseLibraryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_m *VersionInterface) GetVersion(ctx context.Context, r *admin.GetVersionRequest) (*admin.GetVersionResponse, error) {\n\tret := _m.Called(ctx, r)\n\n\tvar r0 *admin.GetVersionResponse\n\tif rf, ok := ret.Get(0).(func(context.Context, *admin.GetVersionRequest) *admin.GetVersionResponse); ok {\n\t\tr0 = rf(ctx, r)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*admin.GetVersionResponse)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, *admin.GetVersionRequest) error); ok {\n\t\tr1 = rf(ctx, r)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (_Accessible *AccessibleCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Accessible.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_BaseContentFactory *BaseContentFactoryCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactory.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (s *suite) Test_QueryNextVersion_happy_path(c *C) {\n\tserver := NewMockServer().WithBody(`1.0`).Start(c)\n\tdefer server.Stop()\n\n\tunit := NewRemoteInventory(server.URL, \"token\", \"\", \"\", false)\n\tversion, err := unit.QueryNextVersion(\"query-project\", \"name\", \"1.@\")\n\tserver.ExpectCalled(c, true, queryNextVersionURL)\n\tc.Assert(err, IsNil)\n\tc.Assert(version, Equals, \"1.0\")\n}", "func TestSetGoodArgsFull(t *testing.T) {\n\tfmt.Println(\"Entering the test method for SetGoodArgsFull\")\n\tprovcc := new(SimpleAsset)\n\tstub := shim.NewMockStub(\"ANY_PARAM\", provcc)\n\n\t// Testing the init. It always return true. No parameters in init. \n\t\n\tcheckInit(t, stub, [][]byte{[]byte(\"init\")})\n\n\tres := stub.MockInvoke(\"1\", [][]byte{[]byte(\"set\"), []byte(\"S52fkpF2rCEArSuwqyDA9tVjawUdrkGzbNQLaa7xJfA=\"),\n\t[]byte(\"agentInfo.atype\"),[]byte(\"1.2.3.4\"),\n\t[]byte(\"agentInfo.id\"),[]byte(\"agentidentifier\"),\n\t[]byte(\"agentinfo.name\"),[]byte(\"7.8.9\"),\n\t[]byte(\"agentinfo.idp\"),[]byte(\"urn:tiani-spirit:sts\"),\n\t[]byte(\"locationInfo.id\"),[]byte(\"urn:oid:1.2.3\"),\n\t[]byte(\"locationInfo.name\"),[]byte(\"General Hospital\"),\n\t[]byte(\"locationInfo.locality\"),[]byte(\"Nashville, TN\"),\n\t[]byte(\"locationInfo.docid\"),[]byte(\"1.2.3\"),\n\t[]byte(\"action\"),[]byte(\"ex:CREATE\"),\n\t[]byte(\"date\"),[]byte(\"2018-11-10T12:15:55.028Z\"),\n\t[]byte(\"digest1\"),[]byte(\"E0nioxbCYD5AlzGWXDDDl0Gt5AAKv3ppKt4XMhE1rfo\"),\n\t[]byte(\"digest3\"),[]byte(\"xLrbWN5QJBJUAsdevfrxGlN3o0p8VZMnFFnV9iMll5o\")})\n\n\tif res.Status != shim.OK {\n\t\tfmt.Println(\"Invoke failed\", string(res.Message))\n\t\tt.FailNow()\n\t}\n\t\n}", "func (_AggregatorV2V3Interface *AggregatorV2V3InterfaceCallerSession) Version() (*big.Int, error) {\n\treturn _AggregatorV2V3Interface.Contract.Version(&_AggregatorV2V3Interface.CallOpts)\n}", "func TestVersion(t *testing.T) {\n\n\ttests := []struct {\n\t\tInput driver.Version\n\t\tMajor int\n\t\tMinor int\n\t\tSub string\n\t\tSubInt int\n\t\tSubIsInt bool\n\t}{\n\t\t{\"1.2.3\", 1, 2, \"3\", 3, true},\n\t\t{\"\", 0, 0, \"\", 0, false},\n\t\t{\"1.2.3a\", 1, 2, \"3a\", 0, false},\n\t\t{\"13.12\", 13, 12, \"\", 0, false},\n\t}\n\n\tfor _, test := range tests {\n\t\tif v := test.Input.Major(); v != test.Major {\n\t\t\tt.Errorf(\"Major failed for '%s', expected %d, got %d\", test.Input, test.Major, v)\n\t\t}\n\t\tif v := test.Input.Minor(); v != test.Minor {\n\t\t\tt.Errorf(\"Minor failed for '%s', expected %d, got %d\", test.Input, test.Minor, v)\n\t\t}\n\t\tif v := test.Input.Sub(); v != test.Sub {\n\t\t\tt.Errorf(\"Sub failed for '%s', expected '%s', got '%s'\", test.Input, test.Sub, v)\n\t\t}\n\t\tif v, vIsInt := test.Input.SubInt(); vIsInt != test.SubIsInt || v != test.SubInt {\n\t\t\tt.Errorf(\"SubInt failed for '%s', expected (%d,%v), got (%d,%v)\", test.Input, test.SubInt, test.SubIsInt, v, vIsInt)\n\t\t}\n\t}\n}", "func (_LvRecording *LvRecordingCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _LvRecording.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func TestVersionSemVer(t *testing.T) {\n\tt.Logf(\"Testing version semantic (%s)\", Version)\n\tdetails := strings.Split(Version, \".\")\n\tif len(details) != 3 {\n\t\tt.Errorf(\"Version should provide major, minor and path informations: %s\", Version)\n\t}\n\tif _, err := strconv.ParseInt(details[0], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif _, err := strconv.ParseInt(details[1], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\n\tpatch := strings.Split(details[2], \"-\")\n\tif _, err := strconv.ParseInt(patch[0], 2, 0); err != nil {\n\t\tt.Errorf(err.Error())\n\t}\n\tif len(patch) > 2 {\n\t\tt.Error(\"last version part only provides patch number and pre-release info\")\n\n\t}\n}", "func TestSuccessfullyUpdateVersion(t *testing.T) {\n\tids, err := helpers.GetIDsAndTimestamps()\n\tif err != nil {\n\t\tlog.ErrorC(\"unable to generate mongo timestamp\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tdatasetAPI := httpexpect.New(t, cfg.DatasetAPIURL)\n\n\tneo4JStore, err := neo4j.NewDatastore(cfg.Neo4jAddr, \"\", neo4j.GenericHierarchyCPIHTestData)\n\tif err != nil {\n\t\tt.Errorf(\"unable to connect to neo4j. error: [%v]\\n\", err)\n\t\tlog.ErrorC(\"unable to connect to neo4j\", err, nil)\n\t\tt.FailNow()\n\t}\n\n\tConvey(\"Given an unpublished dataset, edition and version\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceEditionConfirmed, ids.UniqueTimestamp, 1)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tt.FailNow()\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceEditionConfirmed)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update meta data against the version resource\", func() {\n\t\t\tConvey(\"Then version resource is updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionMetaDataJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.ReleaseDate, ShouldEqual, \"2018-11-11\")\n\t\t\t\tSo(len(*updatedVersion.UsageNotes), ShouldEqual, 2)\n\n\t\t\t\tSo((*updatedVersion.UsageNotes)[0].Title, ShouldEqual, \"Coefficients of variation\")\n\n\t\t\t\talert := mongo.Alert{\n\t\t\t\t\tDescription: \"All data entries (observations) for Plymouth have been updated\",\n\t\t\t\t\tDate: \"2017-04-05\",\n\t\t\t\t\tType: \"Correction\",\n\t\t\t\t}\n\n\t\t\t\talertList := &[]mongo.Alert{alert}\n\n\t\t\t\tSo(updatedVersion.Alerts, ShouldResemble, alertList)\n\n\t\t\t\tlatestChange := mongo.LatestChange{\n\t\t\t\t\tDescription: \"change to the period frequency from quarterly to monthly\",\n\t\t\t\t\tName: \"Changes to the period frequency\",\n\t\t\t\t\tType: \"Summary of Changes\",\n\t\t\t\t}\n\n\t\t\t\tlatestChangesList := []mongo.LatestChange{latestChange}\n\n\t\t\t\tSo(updatedVersion.LatestChanges, ShouldResemble, latestChangesList)\n\n\t\t\t\tSo(updatedVersion.Links.Spatial.HRef, ShouldEqual, \"http://ons.gov.uk/new-geography-list\")\n\n\t\t\t\t// Check self link does not update - the only link that can be updated is `spatial`\n\t\t\t\tSo(updatedVersion.Links.Self.HRef, ShouldNotEqual, \"http://bogus/bad-link\")\n\n\t\t\t\ttemporal := mongo.TemporalFrequency{\n\t\t\t\t\tStartDate: \"2014-11-11\",\n\t\t\t\t\tEndDate: \"2017-11-11\",\n\t\t\t\t\tFrequency: \"monthly\",\n\t\t\t\t}\n\n\t\t\t\ttemporalList := []mongo.TemporalFrequency{temporal}\n\n\t\t\t\tSo(updatedVersion.Temporal, ShouldResemble, temporalList)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of associated\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToAssociatedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"associated\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"45454545\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"associated\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a collection id and state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedWithCollectionIDJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated, and CollectionID removed\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceEditionConfirmed)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tlog.Debug(\"edition id\", log.Data{\"edition_id\": ids.EditionUnpublished})\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, and CollectionID removed\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.CollectionID, ShouldBeEmpty)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\n\t\t\t\tinstanceProps, err := neo4JStore.GetInstanceProperties(ids.InstanceEditionConfirmed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"failed to get properties from neo4j instance node\", err, nil)\n\t\t\t\t\tt.FailNow()\n\t\t\t\t}\n\n\t\t\t\tSo(instanceProps[\"is_published\"], ShouldBeTrue)\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceEditionConfirmed); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceEditionConfirmed, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given an unpublished dataset, edition and a version that has been associated\", t, func() {\n\t\tedition := \"2018\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetAssociated, ids.EditionUnpublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 2)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\t// TODO Remove skipped tests when code has been refactored (and hence fixed)\n\t\t// 1 test skipped\n\t\tSkipConvey(\"When a PUT request to update version resource to remove collection id\", func() {\n\t\t\tConvey(\"Then the dataset and version resources are updated accordingly and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionFromAssociatedToEditionConfirmedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"edition-confirmed\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Next.CollectionID, ShouldEqual, \"\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"edition-confirmed\")\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetAssociated, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionUnpublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionUnpublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetAssociated+\"/editions/2018/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetAssociated)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetAssociated, 0))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n\n\tConvey(\"Given a published dataset and edition, and a version that has been associated\", t, func() {\n\t\tedition := \"2017\"\n\t\tversion := \"2\"\n\n\t\tdocs, err := setupResources(ids.DatasetPublished, ids.EditionPublished, edition, ids.InstanceAssociated, ids.UniqueTimestamp, 3)\n\t\tif err != nil {\n\t\t\tlog.ErrorC(\"Was unable to setup test data\", err, nil)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcount, err := neo4JStore.CreateInstanceNode(ids.InstanceAssociated)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"failed to create neo4j instance node: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.Fail()\n\t\t}\n\t\tSo(count, ShouldEqual, 1)\n\n\t\tConvey(\"When a PUT request to update version resource with a state of published\", func() {\n\t\t\tConvey(\"Then the dataset, edition and version resources are updated and returns a status ok (200)\", func() {\n\n\t\t\t\tdatasetAPI.PUT(\"/datasets/{id}/editions/{edition}/versions/{version}\", ids.DatasetPublished, edition, version).\n\t\t\t\t\tWithHeader(florenceTokenName, florenceToken).\n\t\t\t\t\tWithBytes([]byte(validPUTUpdateVersionToPublishedJSON)).\n\t\t\t\t\tExpect().Status(http.StatusOK)\n\n\t\t\t\tupdatedVersion, err := mongo.GetVersion(cfg.MongoDB, \"instances\", \"_id\", ids.InstanceAssociated)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check version has been updated\n\t\t\t\tSo(updatedVersion.ID, ShouldEqual, ids.InstanceAssociated)\n\t\t\t\tSo(updatedVersion.State, ShouldEqual, \"published\")\n\n\t\t\t\tupdatedEdition, err := mongo.GetEdition(cfg.MongoDB, \"editions\", \"_id\", ids.EditionPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check edition has been updated\n\t\t\t\tSo(updatedEdition.ID, ShouldEqual, ids.EditionPublished)\n\t\t\t\tSo(updatedEdition.Next.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current, ShouldNotBeNil)\n\t\t\t\tSo(updatedEdition.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.ID, ShouldEqual, \"2\")\n\t\t\t\tSo(updatedEdition.Current.Links.LatestVersion.HRef, ShouldEqual, cfg.DatasetAPIURL+\"/datasets/\"+ids.DatasetPublished+\"/editions/2017/versions/2\")\n\n\t\t\t\tupdatedDataset, err := mongo.GetDataset(cfg.MongoDB, collection, \"_id\", ids.DatasetPublished)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.ErrorC(\"Unable to retrieve updated version document\", err, nil)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\t// Check dataset has been updated, next sub document should be copied across to current sub doc\n\t\t\t\tSo(updatedDataset.ID, ShouldEqual, ids.DatasetPublished)\n\t\t\t\tSo(updatedDataset.Current.State, ShouldEqual, \"published\")\n\t\t\t\tSo(updatedDataset.Next.State, ShouldEqual, \"published\") // Check next subdoc still exists\n\t\t\t\tSo(updatedDataset, ShouldResemble, expectedDatasetResource(ids.DatasetPublished, 1))\n\t\t\t})\n\t\t})\n\n\t\tif err := mongo.Teardown(docs...); err != nil {\n\t\t\tif err != mgo.ErrNotFound {\n\t\t\t\tlog.ErrorC(\"Was unable to remove test data\", err, nil)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\n\t\tif err := neo4JStore.CleanUpInstance(ids.InstanceAssociated); err != nil {\n\t\t\tt.Errorf(\"failed to cleanup neo4j instances: [%v]\\n error: [%v]\\n\", ids.InstanceAssociated, err)\n\t\t\tt.FailNow()\n\t\t}\n\t})\n}", "func (h *Headers) SetVersion(version string) { h.version = version }", "func (_BaseContentFactoryExt *BaseContentFactoryExtCaller) Version(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _BaseContentFactoryExt.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (m *MockManager) SerializeReleaseName(arg0 string) error {\n\tret := m.ctrl.Call(m, \"SerializeReleaseName\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *ApplicationServiceInterface) Update(_a0 *models.Application) error {\n\tret := _m.Called(_a0)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(*models.Application) error); ok {\n\t\tr0 = rf(_a0)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (c *cachestub) RecordVersion(token, version string) (*cache.Record, error) {\n\treturn &cache.Record{}, nil\n}", "func (_Contract *ContractCaller) Version(opts *bind.CallOpts) ([4]byte, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"version\")\n\n\tif err != nil {\n\t\treturn *new([4]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([4]byte)).(*[4]byte)\n\n\treturn out0, err\n\n}", "func MockPrepareRelease(release *Release) {\n\trelease.SetDefaultRegionAccount(to.Strp(\"region\"), to.Strp(\"account\"))\n\trelease.SetDefaults()\n\trelease.SetUUID()\n}", "func (_PlasmaFramework *PlasmaFrameworkTransactor) SetVersion(opts *bind.TransactOpts, _version string) (*types.Transaction, error) {\n\treturn _PlasmaFramework.contract.Transact(opts, \"setVersion\", _version)\n}", "func (m *MockVersionInfoDao) GetLatestScsVersion(sid string) (*model.VersionInfo, error) {\n\tret := m.ctrl.Call(m, \"GetLatestScsVersion\", sid)\n\tret0, _ := ret[0].(*model.VersionInfo)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDeployedVersionFinder) OpenSourceVersion(ctx context.Context, installNamespace string) (string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"OpenSourceVersion\", ctx, installNamespace)\n\tret0, _ := ret[0].(string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_HelloWorld *HelloWorldCaller) Version(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _HelloWorld.contract.Call(opts, out, \"version\")\n\treturn *ret0, err\n}", "func (m *MockProductCatalog) UpdateVersionForEditor(arg0 context.Context, arg1 db.UpdateVersionForEditorParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateVersionForEditor\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestMakeUpVersion(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tmajor uint8\n\t\tminor uint8\n\t\tfix uint8\n\t\twant uint32\n\t}{\n\t\t{\n\t\t\tname: \"MakeUpversionTest\",\n\t\t\tmajor: FixVersion,\n\t\t\tminor: MinorVersion,\n\t\t\tfix: FixVersion,\n\t\t\twant: 16843008,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := makeUpVersion(tt.major, tt.minor, tt.fix); got != tt.want {\n\t\t\t\tt.Errorf(\"makeUpVersion() = %v, majorVersion %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func setVersion() {\n\tgitTag = GitCommit\n\n\t// A development build is one that's not at a tag or has uncommitted changes\n\tdevBuild = gitTag == \"\" || gitShortStat != \"\"\n\n\t// Only set the appVersion if -ldflags was used\n\tif gitNearestTag != \"\" || gitTag != \"\" {\n\t\tif devBuild && gitNearestTag != \"\" {\n\t\t\tappVersion = fmt.Sprintf(\"%s (+%s %s)\", strings.TrimPrefix(gitNearestTag, \"v\"), GitCommit, buildDate)\n\t\t} else if gitTag != \"\" {\n\t\t\tappVersion = strings.TrimPrefix(gitTag, \"v\")\n\t\t}\n\t}\n}", "func (i *MockOtherDataItem) GetVersion() int {\n\treturn i.Version\n}" ]
[ "0.7078154", "0.70451313", "0.66910595", "0.6581204", "0.6534845", "0.65255547", "0.629458", "0.62848294", "0.62847006", "0.62608105", "0.6256023", "0.62408495", "0.620789", "0.62014997", "0.61569256", "0.6112755", "0.608206", "0.60665065", "0.60335004", "0.60245526", "0.59844303", "0.59792167", "0.59715885", "0.5931363", "0.59010947", "0.58297276", "0.58071965", "0.5804199", "0.5742849", "0.57293963", "0.57252276", "0.569393", "0.56883377", "0.5652411", "0.5626027", "0.5617349", "0.5606514", "0.56041986", "0.5603828", "0.55998975", "0.55974317", "0.5581046", "0.5580514", "0.5563384", "0.55526805", "0.5544228", "0.55226845", "0.55140513", "0.55077285", "0.54865", "0.54847807", "0.5466515", "0.54535055", "0.54472035", "0.5436026", "0.54320717", "0.5425119", "0.5422965", "0.5416658", "0.5407967", "0.54058003", "0.5405307", "0.53988475", "0.53922147", "0.53898066", "0.5383413", "0.5383145", "0.5380453", "0.5378241", "0.5375637", "0.53755504", "0.53694504", "0.5366318", "0.5361411", "0.5359404", "0.53490096", "0.5342469", "0.5328151", "0.53266734", "0.5306409", "0.5300932", "0.5287754", "0.5279504", "0.52674943", "0.52569145", "0.52517074", "0.5240555", "0.5235621", "0.5215389", "0.52118075", "0.52010375", "0.5199776", "0.51878417", "0.518568", "0.5173672", "0.51680005", "0.5166556", "0.5162274", "0.51515", "0.51465106" ]
0.7880125
0
New returns a new instance of Exp struct
func New(s string) *Exp { exp := &Exp{context: s} exp.init() return exp }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewExpCache(ctx context.Context, ttl time.Duration) *ExpCache {\n\tc := &ExpCache{\n\t\tttl: ttl,\n\t}\n\tgo c.runClean(ctx)\n\treturn c\n}", "func New(value int64, exp int32) Decimal {\n\treturn Decimal{\n\t\tvalue: big.NewInt(value),\n\t\texp: exp,\n\t}\n}", "func New(value int64, exp int32) Decimal {\n\treturn Decimal{val: decimal.New(value, exp)}\n}", "func New(value int64, exp int32) Decimal {\n\treturn decimal.New(value, exp)\n}", "func New(host string) (*Expvar, error) {\n\ttr := http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 20 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 2,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\n\texp := Expvar{\n\t\thost: host,\n\t\ttr: &tr,\n\t\tclient: http.Client{\n\t\t\tTransport: &tr,\n\t\t\tTimeout: 1 * time.Second,\n\t\t},\n\t}\n\n\treturn &exp, nil\n}", "func NewMaterialExp(a, b float64) Material {\n\treturn MaterialExp{a: a, b: b}\n}", "func New() *Evaluator {\n\teval := &Evaluator{\n\t\tCtxt: lexer.Context{Line: 1, Col: 1, Ctxt: \"\"},\n\t\tloopcount: 0,\n\t}\n\treturn eval\n}", "func New(mdef MatrixDefiner, amdef AnonymousMatrixDefiner, sdef ScalarDefiner) *E {\n\te := &E{mdef: mdef, amdef: amdef, sdef: sdef}\n\n\tfor r := 'A'; r <= 'Z'; r++ {\n\t\te.mvars = append(e.mvars, matrix.New(3, 3))\n\t}\n\n\tfor r := 'a'; r <= 'z'; r++ {\n\t\te.svars = append(e.svars, matrix.NewScalarFrac(0))\n\t}\n\n\treturn e\n}", "func NewEx() *Ex {\n\treturn &Ex{input: NewInput()}\n}", "func NewExpr(terms interface{}) *Expr {\n\treturn &Expr{\n\t\tNegated: false,\n\t\tTerms: terms,\n\t\tIndex: 0,\n\t}\n}", "func (self *Store) Exp(k string, ttl int64) []byte {\n\tself.mu.Lock()\n\tself.mu.Unlock()\t\n\treturn nil\n}", "func (g *Graph) Exp(x Node) Node {\n\treturn g.NewOperator(fn.NewExp(x), x)\n}", "func New(expr string) (*Regexp, error) {\n\treturn NewWithLimit(expr, DefaultLimit)\n}", "func NewDec(value int64, exp int32) Decimal {\n\treturn Decimal{\n\t\tvalue: big.NewInt(value),\n\t\texp: exp,\n\t}\n}", "func NewExpr(name, source string, expr expression.Expr) *Expr {\n\treturn &Expr{\n\t\tsource: source,\n\t\tExpr: expr,\n\t\tName: name,\n\t}\n}", "func MakeExpRateEstimator(alpha float64, t float64) *ExponentialRateEstimator {\n\tres := new(ExponentialRateEstimator)\n\tres.alpha = alpha\n\tres.last = t\n\tres.s = 0\n\tres.w = 0\n\treturn res\n}", "func New(lhs, rhs string, binds pattern.Binds) (*T, error) {\n\tlp, err := pattern.Parse(lhs, binds)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing %q: %v\", lhs, err)\n\t}\n\trp, err := lp.Derive(rhs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &T{lhs: lp, rhs: rp}, nil\n}", "func New(classArgs ...interface{}) *Ex {\n\treturn &Ex{class: fmt.Sprint(classArgs...), stack: callers()}\n}", "func (tr *transform) newExpression(iVar interface{}) *expression {\n\tvar id string\n\n\tif iVar != nil {\n\t\tswitch tVar := iVar.(type) {\n\t\tcase *ast.Ident:\n\t\t\tid = tVar.Name\n\t\tcase string:\n\t\t\tid = tVar\n\t\t}\n\t}\n\n\treturn &expression{\n\t\ttr,\n\t\tnew(bytes.Buffer),\n\t\tid,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tmake([]string, 0),\n\t\tmake([]string, 0),\n\t}\n}", "func (ta *TA) Exp() *TA {\n\treturn ta.Mapf(math.Exp, false)\n}", "func New(sub uuid.UUID,\n\tiss string, aud []string, exp time.Duration) (t *Token) {\n\n\tt = &Token{\n\t\tId: uuid.New(),\n\t\tSubject: sub,\n\t\tIssuer: iss,\n\t\tAudience: aud,\n\t\tIssued: Timestamp(time.Now().Unix()),\n\t}\n\n\tif 0 != exp {\n\t\tt.Expires = Timestamp(time.Now().Add(exp).Unix())\n\t}\n\n\treturn\n}", "func (s VectOp) Exp() VectOp {\n\treturn fs.Exp(s)\n}", "func New(v interface{}) Record {\n\tt := reflect.TypeOf(v)\n\treturn Record{\n\t\tv: reflect.ValueOf(v),\n\t\tt: t,\n\t\t//\tlen: numExported(t),\n\t}\n}", "func New(duration time.Duration) Cache {\n\tc := &cache{\n\t\tduration: duration,\n\t\trecord: make(map[string]entry),\n\t\trecordLock: &sync.Mutex{},\n\t}\n\tgo c.startGC(duration * 10)\n\treturn c\n}", "func NewExponential(num int, a, step float64) model.Collection {\n\n\texponential := NewExponentialGenerator(a, step)\n\tcollection := exponential.Num(num)\n\n\treturn collection\n}", "func Exp(a Int, e Int) Int {\n\treturn Int{big.NewInt(0).Exp(a.Int, e.Int, nil)}\n}", "func New(fset *token.FileSet, files []*ast.File, in *inspector.Inspector) *Evaluator {\n\treturn &Evaluator{n: NewNodeNavigator(fset, files, in)}\n}", "func funcExp(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn simpleFunc(vals, enh, math.Exp)\n}", "func NewHour(date sql.Expression) sql.Expression {\n\treturn &Hour{expression.UnaryExpression{Child: date}}\n}", "func New(t token.Token, src []expr.Expr, dst []token.Token) expr.Expr {\n\treturn assign{\n\t\tt: t,\n\t\tsrc: src,\n\t\tdst: dst,\n\t}\n}", "func NewExpression(expressionStr string) (*Expression, error) {\n\tfunctions := map[string]govaluate.ExpressionFunction{\n\t\t\"in\": func(args ...interface{}) (interface{}, error) {\n\t\t\tif len(args) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"can't evaluate in() function when zero arguments supplied\")\n\t\t\t}\n\t\t\tv := args[0]\n\t\t\tfor i := 1; i < len(args); i++ {\n\t\t\t\tif v == args[i] {\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, nil\n\t\t},\n\t}\n\n\texpressionCompiled, err := govaluate.NewEvaluableExpressionWithFunctions(expressionStr, functions)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to compile expression '%s': %s\", expressionStr, err)\n\t}\n\treturn &Expression{\n\t\texpressionStr: expressionStr,\n\t\texpressionCompiled: expressionCompiled,\n\t}, nil\n}", "func New(period time.Duration) *ExponentialMovingAverage {\n\treturn &ExponentialMovingAverage{\n\t\tmu: sync.Mutex{},\n\t\tt: time.Now(),\n\t\tperiod: period.Seconds(),\n\t}\n}", "func NewExpBackoff(base int) *ExpBackoff {\n\treturn &ExpBackoff{\n\t\tbase: base,\n\t}\n}", "func NewExpBackoff() *ExpBackoff {\n\treturn NewExpBackoffWithConfig(DefaultConfig)\n}", "func NewEval(opts CompilerOptions, globals Object, args ...Object) *Eval {\n\tif globals == nil {\n\t\tglobals = Map{}\n\t}\n\n\tif opts.SymbolTable == nil {\n\t\topts.SymbolTable = NewSymbolTable()\n\t}\n\n\tif opts.ModuleIndexes == nil {\n\t\topts.ModuleIndexes = NewModuleIndexes()\n\t}\n\n\treturn &Eval{\n\t\tLocals: args,\n\t\tGlobals: globals,\n\t\tOpts: opts,\n\t\tVM: NewVM(nil).SetRecover(true),\n\t}\n}", "func New(keyFn KeyFunc, lessFn lessFunc) *Heap {\n\treturn NewWithRecorder(keyFn, lessFn, nil)\n}", "func New() *Employee {\n\treturn new(Employee)\n}", "func New(cap int) Stack {\n\treturn Stack{capacity: cap}\n}", "func New(a AddFunc, r RemovalFunc, capacity int, ttl time.Duration) *LRU {\n\tif capacity < 1 {\n\t\tpanic(\"capacity < 1\")\n\t}\n\n\treturn &LRU{\n\t\taddFunc: a,\n\t\tremovalFunc: r,\n\t\tlist: list.New(),\n\t\ttable: make(map[Key]*list.Element),\n\t\tcapacity: capacity,\n\t\tttl: ttl,\n\t\ttouchTimeOnUpdate: true,\n\t}\n}", "func New(ctx context.Context, ttl, leeway, interval time.Duration, maxEntries int) *Cache {\n\tc := &Cache{\n\t\tctx: ctx,\n\t\tentries: map[string]*cacheEntry{},\n\t\tttl: ttl,\n\t\tleeway: leeway,\n\t\tinterval: interval,\n\t\tmaxEntries: maxEntries,\n\t\tactionc: make(chan func(), 1),\n\t}\n\tgo c.backend()\n\treturn c\n}", "func New() *VerbalExpression {\n\tr := new(VerbalExpression)\n\tr.flags = MULTILINE | GLOBAL\n\tr.parts = make([]string, 0)\n\treturn r\n}", "func New(name errors.Op) *Metric {\n\treturn &Metric{\n\t\tName: name,\n\t}\n}", "func New(de, ci time.Duration) *Cache {\n\tif de == 0 {\n\t\tde = -1\n\t}\n\tc := &cache{\n\t\tDefaultExpiration: de,\n\t\tItems: map[string]*Item{},\n\t\tmu: &sync.Mutex{},\n\t}\n\tif ci > 0 {\n\t\tj := &janitor{\n\t\t\tInterval: ci,\n\t\t}\n\t\tc.janitor = j\n\t\tgo j.Run(c)\n\t}\n\t// This trick ensures that the janitor goroutine (which--granted it was enabled--is\n\t// running DeleteExpired on c forever) does not keep the returned C object from being\n\t// garbage collected. When it is garbage collected, the finalizer stops the janitor\n\t// goroutine, after which c is collected.\n\tC := &Cache{c}\n\tif ci > 0 {\n\t\truntime.SetFinalizer(C, stopJanitor)\n\t}\n\treturn C\n}", "func Exp(base, exponent, modulus *big.Int) *big.Int {\n\treturn I().Exp(base, exponent, modulus)\n}", "func New(path string) (gval.Evaluable, error) {\n\treturn lang.NewEvaluable(path)\n}", "func NewExchange(apiToken string) *Exchange {\n\treturn &Exchange{\n\t\tcache: make(map[date]map[Currency]ExchangeRate),\n\t\tapiToken: apiToken,\n\t}\n}", "func (v Value) New(args ...interface{}) Value {\n\tpanic(message)\n}", "func New(values ...interface{}) Stack {\n\tlist := linkedlist.New(values)\n\tstack := Stack{list}\n\treturn stack\n}", "func New(classArgs ...interface{}) Exception {\n\treturn &Ex{\n\t\tclass: fmt.Sprint(classArgs...),\n\t\tstack: callers(),\n\t}\n}", "func New() Cache {\n\treturn &cache{\n\t\tcache: c.New(-1, -1),\n\t}\n}", "func Exp(in Res) Res {\n\texpd := in.Output().Copy()\n\tanyvec.Exp(expd)\n\treturn &expRes{OutVec: expd, In: in}\n}", "func NewExpGenerator(seed int64) *ExpGenerator {\n\turng := NewUniformGenerator(seed)\n\treturn &ExpGenerator{urng}\n}", "func (self *State)Exp(a any)any{\n self.IncOperations(self.coeff[\"exp\"]+self.off[\"exp\"])\n return wrap1(a,math.Exp)\n}", "func NewTermsExpiration()(*TermsExpiration) {\n m := &TermsExpiration{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func New(name string, rate float64, tags ...string) Metric {\n\treturn Metric{name, rate, tags}\n}", "func (c *Clac) Exp() error {\n\treturn c.applyFloat(1, func(vals []value.Value) (value.Value, error) {\n\t\treturn unary(\"**\", vals[0])\n\t})\n}", "func MakeHfExpRateEstimator(hf float64, t float64) *HfExponentialRateEstimator {\n\tres := new(HfExponentialRateEstimator)\n\tres.p = math.Exp2(-1.0 / hf)\n\tres.last = t\n\tres.s = 0\n\tres.w = 0\n\treturn res\n}", "func New(v interface{}) Value {\n\treturn Value{v}\n}", "func New() Assert {\n\treturn &assertEncapsulation{nil}\n}", "func New(e *config.EnvVar, c *cache.Cache) *Medium {\r\n\treturn &Medium{EnvVar: e, Cache: c}\r\n}", "func New(t uint8, p []byte) *IE {\n\ti := &IE{Type: t, Payload: p}\n\ti.SetLength()\n\treturn i\n}", "func New() *Cache { return &Cache{} }", "func Exp(a NumberArray) (resultingMatrix NumberArray) {\n\tnumArray, _ := unaryOperation(\"Exp\", a)\n\treturn numArray\n}", "func New(identity string, maxAge time.Duration, resolver Resolver, log *logrus.Entry) *Cache {\n\treturn &Cache{\n\t\tidentity: identity,\n\t\tcache: make(map[query]*entry),\n\t\tmaxAge: maxAge,\n\t\tresolver: resolver,\n\t\tlog: log,\n\t}\n}", "func New() Enigma {\r\n\tleftRotor := availableRotors[\"III\"]\r\n\tmiddleRotor := availableRotors[\"II\"]\r\n\trightRotor := availableRotors[\"I\"]\r\n\treflector := availableReflectors[\"B\"]\r\n\r\n\treturn Enigma{\r\n\t\trotors: rotors{\r\n\t\t\t&rightRotor,\r\n\t\t\t&middleRotor,\r\n\t\t\t&leftRotor,\r\n\t\t},\r\n\t\treflector: reflector,\r\n\t}\r\n}", "func New(es []Entry) *Solver { return &Solver{entries: es} }", "func New() *PegInstructions {\n\tvar m PegInstructions\n\treturn &m\n}", "func (z *Int) Exp(base, exponent *Int) *Int {\n\treturn z.Copy(ExpF(base, exponent))\n}", "func (a *Add) New(key, value string) transformer.Transformer {\n\treturn &Add{\n\t\tPath: key,\n\t\tValue: value,\n\n\t\tvariables: a.variables,\n\t}\n}", "func New(capacity int) *Cache {\n\treturn &Cache{\n\t\tl: list.New(),\n\t\tcache: make(map[string]*list.Element),\n\t\tcapacity: capacity,\n\t}\n}", "func NewExplosion(center gmath.Vector2i, strength int, shooter *Tank) *Explosion {\n\treturn &Explosion{\n\t\tCenter: center,\n\t\tStrength: float64(strength),\n\t\tspeed: 1,\n\t\tnoise: osx.NewNormalized(time.Now().UTC().UnixNano()),\n\t\tcollided: map[tl.Physical]bool{},\n\t\tshooter: shooter,\n\t}\n}", "func (z *E12) Exp(x *E12, e big.Int) *E12 {\n\tvar res E12\n\tres.SetOne()\n\tb := e.Bytes()\n\tfor i := range b {\n\t\tw := b[i]\n\t\tmask := byte(0x80)\n\t\tfor j := 7; j >= 0; j-- {\n\t\t\tres.Square(&res)\n\t\t\tif (w&mask)>>j != 0 {\n\t\t\t\tres.Mul(&res, x)\n\t\t\t}\n\t\t\tmask = mask >> 1\n\t\t}\n\t}\n\tz.Set(&res)\n\treturn z\n}", "func New(hours, minutes int) Time {\n\th := (hours + minutes/60) % 24\n\tm := minutes % 60\n\n\tfor m < 0 {\n\t\tm += 60\n\t\th--\n\t}\n\n\tfor h < 0 {\n\t\th += 24\n\t}\n\n\treturn Time{\n\t\tminutes: h*60 + m,\n\t}\n}", "func New() *Abstraction {\n\treturn &Abstraction{}\n}", "func Newf(classFormat string, args ...interface{}) *Ex {\n\treturn &Ex{class: fmt.Sprintf(classFormat, args...), stack: callers()}\n}", "func (z *Element22) Exp(x Element22, e uint64) *Element22 {\n\tif e == 0 {\n\t\treturn z.SetOne()\n\t}\n\n\tz.Set(&x)\n\n\tl := bits.Len64(e) - 2\n\tfor i := l; i >= 0; i-- {\n\t\tz.Square(z)\n\t\tif e&(1<<uint(i)) != 0 {\n\t\t\tz.MulAssign(&x)\n\t\t}\n\t}\n\treturn z\n}", "func New() *Stack {\n\treturn &Stack{\n\t\tLength: 0,\n\t\tLast: nil,\n\t}\n}", "func New() Go { return Go{} }", "func New(expire, maid int) (*Cache){\n if expire==0 {\n expire = defaultExpiringDuration\n }\n if maid==0 {\n maid = defaultMaidDuration\n }\n\n expireDuration, _ := time.ParseDuration(fmt.Sprintf(\"%dm\", expire))\n maidDuration, _ := time.ParseDuration(fmt.Sprintf(\"%dm\", maid))\n\n //Make sure that no one is calling New at the same time.\n //Lock and Unlock the same mutex and set the old cache as invalid.\n cache.cacheMutex.Lock()\n cache.isValid = false\n cache.cacheMutex.Unlock()\n\n //Create the new cache\n cache = &Cache{\n cache: map[string]value{},\n expire: expireDuration,\n maid: maidDuration,\n isValid: false}\n\n go callMaid(cache)\n\n //Set cache as valid before returning\n cache.isValid = true\n return cache\n}", "func New(options ...Option) (metric.Exporter, error) {\n\tcfg := newConfig(options...)\n\texp := &exporter{\n\t\ttemporalitySelector: cfg.temporalitySelector,\n\t\taggregationSelector: cfg.aggregationSelector,\n\t}\n\texp.encVal.Store(*cfg.encoder)\n\treturn exp, nil\n}", "func New(args ...float64) Tuple {\n\treturn args\n}", "func New(capacity int) Cache {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tcache := Cache{\n\t\tcapacity: capacity,\n\t\tlinkedList: list.New(),\n\t\tcacheMap: make(map[string]*list.Element),\n\t}\n\treturn cache\n}", "func NewPowExpr(scanner parser.Scanner, a, b Expr) Expr {\n\treturn newArithExpr(scanner, a, b, \"^\", func(a, b float64) float64 {\n\t\treturn math.Pow(a, b)\n\t})\n}", "func New(typ NodeType, ns, name string, attrs []Attribute, children ...*Node) *Node {\n\tvar norm []Attribute\n\tvar key string\n\tfor _, v := range attrs {\n\t\tif v.Key == \"key\" {\n\t\t\tkey = expr.Eval(v.Val)\n\t\t} else {\n\t\t\tnorm = append(norm, v)\n\t\t}\n\t}\n\tif len(children) > 0 {\n\t\tnorm = append(norm, Attribute{\n\t\t\tKey: \"children\",\n\t\t\tVal: children,\n\t\t})\n\t}\n\tn := &Node{\n\t\tType: typ,\n\t\tNamespace: ns,\n\t\tKey: key,\n\t\tData: name,\n\t\tAttr: norm,\n\t}\n\treturn n\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func New(capacity int, cmp Less) *Cache {\n\tif capacity < 0 {\n\t\tcapacity = 0\n\t}\n\n\treturn &Cache{\n\t\tcapacity: capacity,\n\t\tcmp: cmp,\n\t\theap: newHeap(capacity, cmp),\n\t\titems: make(itemsMap, capacity),\n\t}\n}", "func New(env *Environment) *Environment {\n\treturn NewSized(env, 0)\n}", "func NewEquation(t, tt Type) Equation {\n\treturn Equation{t, tt}\n}", "func New(size int, onEvict func(key string, value interface{})) *Cache {\n\tif size <= 0 {\n\t\tpanic(\"invalid size\")\n\t}\n\treturn &Cache{\n\t\tentries: make(map[string]*entry, int(float64(size)*1.5)),\n\t\tsize: size,\n\t\tonEvict: onEvict,\n\t}\n}", "func New(analysis reach.Analysis) *Explainer {\n\treturn &Explainer{\n\t\tanalysis: analysis,\n\t}\n}", "func CreateNewExpr() Expr {\n\tc11 := Constant{value: 1.1}\n\tc22 := Constant{value: 2.2}\n\tc33 := Constant{value: 3.3}\n\tbp := BinaryPlus{left: &BinaryPlus{left: &c11, right: &c22}, right: &c33}\n\treturn &bp\n}", "func Exp(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Exp\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func New(instructions *tk.Instructions) (*Interpreter, error) {\r\n\terr := ps.Parse(instructions)\r\n\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tmin := -1\r\n\tmax := 0\r\n\r\n\tfor index := range *instructions {\r\n\t\tif min == -1 || int(index) < min {\r\n\t\t\tmin = int(index)\r\n\t\t}\r\n\t\tif int(index) > max {\r\n\t\t\tmax = int(index)\r\n\t\t}\r\n\t}\r\n\r\n\treturn &Interpreter{\r\n\t\tinstructions: instructions,\r\n\t\tindex: uint32(min),\r\n\t\tlenght: uint32(max) + 1,\r\n\t\tstack: stack.New(),\r\n\t}, nil\r\n}", "func New(r, c int) M {\n\tvals := make([]Frac, r*c)\n\tfor i := range vals {\n\t\tvals[i] = NewScalarFrac(0)\n\t}\n\n\treturn M{r: r, c: c, values: vals}\n}", "func NewElement(name string, val float64) Element {\n\tel := &Element{name, val}\n\treturn *el\n}", "func New(name string, MaxEntries int) *Cache {\n\treturn &Cache{\n\t\tlru: lru.New(MaxEntries),\n\t\tName: name,\n\t}\n}", "func New(value ...interface{}) Stack {\n\ts := Stack{}\n\tfor _, e := range value {\n\t\ts.Push(e)\n\t}\n\treturn s\n}", "func NewExpiration(absoluteTime time.Time, slidingPeriod time.Duration) *Expiration {\n\treturn &Expiration{\n\t\tAbsoluteTime: absoluteTime,\n\t\tSlidingPeriod: slidingPeriod,\n\t}\n}", "func New(year int, month time.Month, day int) Date {\n\treturn Date{year, month, day}\n}", "func New(m int64, c string) *Money {\n\treturn &Money{m, c}\n}" ]
[ "0.6859243", "0.6837793", "0.6766397", "0.66804975", "0.6581954", "0.65122634", "0.627142", "0.6140074", "0.60797876", "0.60538423", "0.5930504", "0.5929171", "0.58859235", "0.58518046", "0.5833372", "0.5824712", "0.5821287", "0.5820043", "0.58156526", "0.57652354", "0.5762473", "0.5757851", "0.5720789", "0.5702451", "0.56926435", "0.5620788", "0.5602356", "0.5597261", "0.55561334", "0.55525506", "0.5551873", "0.55428606", "0.5524277", "0.55136913", "0.5493149", "0.54750615", "0.5474264", "0.54550624", "0.5442341", "0.54282635", "0.5415105", "0.54112667", "0.5410755", "0.5410479", "0.53978074", "0.53959745", "0.53952557", "0.538634", "0.53853995", "0.5384127", "0.53796816", "0.53775984", "0.537115", "0.53644735", "0.53644663", "0.5360683", "0.53538066", "0.53461397", "0.5344763", "0.5342742", "0.53224254", "0.53216296", "0.531507", "0.5314546", "0.5310806", "0.53036183", "0.5302941", "0.52958775", "0.5283778", "0.5282981", "0.5279948", "0.52785516", "0.52758944", "0.52703875", "0.5266839", "0.52658874", "0.52656597", "0.52645886", "0.5263083", "0.5254851", "0.52531445", "0.5248891", "0.5243214", "0.52403075", "0.5236628", "0.5236278", "0.5223608", "0.52187544", "0.5217061", "0.52151406", "0.52148813", "0.521318", "0.5212611", "0.521137", "0.5209099", "0.5205775", "0.52049416", "0.52045596", "0.5204005", "0.51971865" ]
0.76039636
0
Eval returns calculated result of the expression
func (e *Exp) Eval() float64 { e.init() result, _ := e.eval(e.opTree) return result }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ExampleEval() {\n\tfmt.Println(Eval(\"5\"))\n\tfmt.Println(Eval(\"1 + 2\"))\n\tfmt.Println(Eval(\"1 - 2 + 3\"))\n\tfmt.Println(Eval(\"3 * ( 3 + 1 * 3 ) / 2\"))\n\tfmt.Println(Eval(\"3 * ( ( 3 + 1 ) * 3 ) / 2\"))\n\t//OutPut:\n\t//5\n\t//3\n\t//2\n\t//9\n\t//18\n}", "func Eval(ctx context.Context, e Expr, vs Values) (interface{}, error) {\r\n\tfn, err := FuncOf(ctx, e, vs)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn fn.Call(ctx, vs)\r\n}", "func (p *Qlang) Eval(expr string) (err error) {\n\n\treturn p.Exec([]byte(expr), \"\")\n}", "func (bp *BinaryPlus) Eval() float64 {\n\treturn bp.left.(Eval).Eval() + bp.right.(Eval).Eval()\n}", "func Eval(input string, context map[string]interface{}) float64 {\n\tnode, err := Parse(input)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\texpr := &expression{node, context}\n\treturn expr.eval(expr.ast)\n}", "func (r *Resolver) Evaluate(args struct{ Expr string }) (Result, error) {\n\tvar result Result\n\tamount, err := calc.CalculateAmount(args.Expr)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tunitName := amount.Units\n\tunit, err := NewUnit(unitName)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\tresult = Result{amount.Value, unit, args.Expr}\n\tlog.Info(fmt.Sprintf(\"evaluate(%s) = %.2f %s\", args.Expr, result.value, result.units.pluralName))\n\treturn result, nil\n}", "func Eval(txApp *sysl.Application, assign Scope, e *sysl.Expr) *sysl.Value {\n\tswitch x := e.Expr.(type) {\n\tcase *sysl.Expr_Transform_:\n\t\treturn evalTransform(txApp, assign, x, e)\n\tcase *sysl.Expr_Binexpr:\n\t\treturn evalBinExpr(txApp, assign, x.Binexpr)\n\tcase *sysl.Expr_Call_:\n\t\treturn evalCall(txApp, assign, x)\n\tcase *sysl.Expr_Name:\n\t\treturn evalName(assign, x)\n\tcase *sysl.Expr_GetAttr_:\n\t\treturn evalGetAttr(txApp, assign, x)\n\tcase *sysl.Expr_Ifelse:\n\t\treturn evalIfelse(txApp, assign, x)\n\tcase *sysl.Expr_Literal:\n\t\treturn x.Literal\n\tcase *sysl.Expr_Set:\n\t\treturn evalSet(txApp, assign, x)\n\tcase *sysl.Expr_List_:\n\t\treturn evalList(txApp, assign, x)\n\tcase *sysl.Expr_Unexpr:\n\t\treturn evalUnaryFunc(x.Unexpr.Op, Eval(txApp, assign, x.Unexpr.Arg))\n\tdefault:\n\t\tlogrus.Warnf(\"Skipping Expr of type %T\\n\", x)\n\t\treturn nil\n\t}\n}", "func (e *Evaluator) Eval(expr *tipb.Expr) (types.Datum, error) {\n\tswitch expr.GetTp() {\n\tcase tipb.ExprType_Null:\n\t\treturn types.Datum{}, nil\n\tcase tipb.ExprType_Int64:\n\t\treturn e.evalInt(expr.Val)\n\tcase tipb.ExprType_Uint64:\n\t\treturn e.evalUint(expr.Val)\n\tcase tipb.ExprType_String:\n\t\treturn e.evalString(expr.Val)\n\tcase tipb.ExprType_Bytes:\n\t\treturn types.NewBytesDatum(expr.Val), nil\n\tcase tipb.ExprType_Float32:\n\t\treturn e.evalFloat(expr.Val, true)\n\tcase tipb.ExprType_Float64:\n\t\treturn e.evalFloat(expr.Val, false)\n\tcase tipb.ExprType_MysqlDecimal:\n\t\treturn e.evalDecimal(expr.Val)\n\tcase tipb.ExprType_MysqlDuration:\n\t\treturn e.evalDuration(expr.Val)\n\tcase tipb.ExprType_ColumnRef:\n\t\treturn e.evalColumnRef(expr.Val)\n\tcase tipb.ExprType_LT:\n\t\treturn e.evalLT(expr)\n\tcase tipb.ExprType_LE:\n\t\treturn e.evalLE(expr)\n\tcase tipb.ExprType_EQ:\n\t\treturn e.evalEQ(expr)\n\tcase tipb.ExprType_NE:\n\t\treturn e.evalNE(expr)\n\tcase tipb.ExprType_GE:\n\t\treturn e.evalGE(expr)\n\tcase tipb.ExprType_GT:\n\t\treturn e.evalGT(expr)\n\tcase tipb.ExprType_NullEQ:\n\t\treturn e.evalNullEQ(expr)\n\tcase tipb.ExprType_And:\n\t\treturn e.evalAnd(expr)\n\tcase tipb.ExprType_Or:\n\t\treturn e.evalOr(expr)\n\tcase tipb.ExprType_Like:\n\t\treturn e.evalLike(expr)\n\tcase tipb.ExprType_Not:\n\t\treturn e.evalNot(expr)\n\tcase tipb.ExprType_In:\n\t\treturn e.evalIn(expr)\n\tcase tipb.ExprType_Plus, tipb.ExprType_Div:\n\t\treturn e.evalArithmetic(expr)\n\t}\n\treturn types.Datum{}, nil\n}", "func (ev *evaluator) eval(expr Expr) model.Value {\n\t// This is the top-level evaluation method.\n\t// Thus, we check for timeout/cancellation here.\n\tif err := contextDone(ev.ctx, \"expression evaluation\"); err != nil {\n\t\tev.error(err)\n\t}\n\n\tswitch e := expr.(type) {\n\tcase *AggregateExpr:\n\t\tvector := ev.evalVector(e.Expr)\n\t\treturn ev.aggregation(e.Op, e.Grouping, e.Without, e.KeepCommonLabels, e.Param, vector)\n\n\tcase *BinaryExpr:\n\t\tlhs := ev.evalOneOf(e.LHS, model.ValScalar, model.ValVector)\n\t\trhs := ev.evalOneOf(e.RHS, model.ValScalar, model.ValVector)\n\n\t\tswitch lt, rt := lhs.Type(), rhs.Type(); {\n\t\tcase lt == model.ValScalar && rt == model.ValScalar:\n\t\t\treturn &model.Scalar{\n\t\t\t\tValue: scalarBinop(e.Op, lhs.(*model.Scalar).Value, rhs.(*model.Scalar).Value),\n\t\t\t\tTimestamp: ev.Timestamp,\n\t\t\t}\n\n\t\tcase lt == model.ValVector && rt == model.ValVector:\n\t\t\tswitch e.Op {\n\t\t\tcase itemLAND:\n\t\t\t\treturn ev.vectorAnd(lhs.(vector), rhs.(vector), e.VectorMatching)\n\t\t\tcase itemLOR:\n\t\t\t\treturn ev.vectorOr(lhs.(vector), rhs.(vector), e.VectorMatching)\n\t\t\tcase itemLUnless:\n\t\t\t\treturn ev.vectorUnless(lhs.(vector), rhs.(vector), e.VectorMatching)\n\t\t\tdefault:\n\t\t\t\treturn ev.vectorBinop(e.Op, lhs.(vector), rhs.(vector), e.VectorMatching, e.ReturnBool)\n\t\t\t}\n\t\tcase lt == model.ValVector && rt == model.ValScalar:\n\t\t\treturn ev.vectorScalarBinop(e.Op, lhs.(vector), rhs.(*model.Scalar), false, e.ReturnBool)\n\n\t\tcase lt == model.ValScalar && rt == model.ValVector:\n\t\t\treturn ev.vectorScalarBinop(e.Op, rhs.(vector), lhs.(*model.Scalar), true, e.ReturnBool)\n\t\t}\n\n\tcase *Call:\n\t\treturn e.Func.Call(ev, e.Args)\n\n\tcase *MatrixSelector:\n\t\treturn ev.matrixSelector(e)\n\n\tcase *NumberLiteral:\n\t\treturn &model.Scalar{Value: e.Val, Timestamp: ev.Timestamp}\n\n\tcase *ParenExpr:\n\t\treturn ev.eval(e.Expr)\n\n\tcase *StringLiteral:\n\t\treturn &model.String{Value: e.Val, Timestamp: ev.Timestamp}\n\n\tcase *UnaryExpr:\n\t\tse := ev.evalOneOf(e.Expr, model.ValScalar, model.ValVector)\n\t\t// Only + and - are possible operators.\n\t\tif e.Op == itemSUB {\n\t\t\tswitch v := se.(type) {\n\t\t\tcase *model.Scalar:\n\t\t\t\tv.Value = -v.Value\n\t\t\tcase vector:\n\t\t\t\tfor i, sv := range v {\n\t\t\t\t\tv[i].Value = -sv.Value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn se\n\n\tcase *VectorSelector:\n\t\treturn ev.vectorSelector(e)\n\t}\n\tpanic(fmt.Errorf(\"unhandled expression of type: %T\", expr))\n}", "func (op *OpAtan) Eval(x, y float32) float32 {\n\treturn float32(math.Atan(float64(op.Child.Eval(x, y))))\n}", "func (s server) Eval(ctx context.Context, req *entity.Request) (*entity.Result, error) {\n\tlog.Printf(\"Received a request: %+v\\n\", req)\n\tresult := &entity.Result{}\n\tres, err := s.usecase.Eval(req.Value)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tresult.Value = strconv.FormatFloat(res, 'G', -1, 64)\n\treturn result, nil\n}", "func (e *Evaluator) Eval(expr string) (interface{}, error) {\n\tn := e.n.Copy()\n\t_expr, err := xpath.Compile(expr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"expr cannot compile: %w\", err)\n\t}\n\n\tv := _expr.Evaluate(n)\n\tswitch v := v.(type) {\n\tcase *xpath.NodeIterator:\n\t\tns := nodes(v)\n\t\tvs := make([]interface{}, 0, len(ns))\n\t\tfor i := range ns {\n\t\t\tswitch n := ns[i].(type) {\n\t\t\tcase attr:\n\t\t\t\tvs = append(vs, n.val)\n\t\t\t}\n\t\t}\n\t\tif len(vs) == len(ns) {\n\t\t\treturn vs, nil\n\t\t}\n\t\treturn ns, nil\n\t}\n\n\treturn v, nil\n}", "func (e PackageExpr) Eval(_ rel.Scope) (rel.Value, error) {\n\treturn e.a.Eval(stdScope())\n}", "func (e *binaryExprEvaluator) eval(lhs, rhs interface{}) interface{} {\n\tswitch e.op {\n\tcase ADD:\n\t\treturn lhs.(float64) + rhs.(float64)\n\tcase SUB:\n\t\treturn lhs.(float64) - rhs.(float64)\n\tcase MUL:\n\t\treturn lhs.(float64) * rhs.(float64)\n\tcase DIV:\n\t\trhs := rhs.(float64)\n\t\tif rhs == 0 {\n\t\t\treturn float64(0)\n\t\t}\n\t\treturn lhs.(float64) / rhs\n\tdefault:\n\t\t// TODO: Validate operation & data types.\n\t\tpanic(\"invalid operation: \" + e.op.String())\n\t}\n}", "func (op *OpConstant) Eval(x, y float32) float32 {\n\treturn op.value\n}", "func (op *OpDiv) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) / op.RightChild.Eval(x, y)\n}", "func Evaluate(expression string) (float64, error) {\n\ttree, err := parse(expression)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn tree.evaluate()\n}", "func eval(binaryOp stmt.BinaryOP, left, right float64) float64 {\n\tswitch binaryOp {\n\tcase stmt.ADD:\n\t\treturn left + right\n\tcase stmt.SUB:\n\t\treturn left - right\n\tcase stmt.MUL:\n\t\treturn left * right\n\tcase stmt.DIV:\n\t\tif right == 0 {\n\t\t\treturn 0\n\t\t}\n\t\treturn left / right\n\tdefault:\n\t\treturn 0\n\t}\n}", "func (s *Subtraction) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn subtractNumericWithError(left, right)\n}", "func (lscript *Scripting) Eval(luacmd string, arguments ...interface{}) (*ScriptingReturnValues, error) {\n\targs := asScriptingArgs(arguments...)\n\tlargs := forLua(args)\n\tfor _, larg := range largs {\n\t\tlscript.Push(larg)\n\t}\n\tvar r *ScriptingReturnValues\n\terr := lscript.DoString(luacmd)\n\tif err != nil {\n\t\tT().P(\"script\", \"lua\").Errorf(\"scripting error: %s\", err.Error())\n\t} else {\n\t\tif err == nil {\n\t\t\tT().P(\"lua\", \"eval\").Debugf(\"%d return values on the stack\", lscript.GetTop())\n\t\t\tr = lscript.returnFromScripting(lscript.GetTop()) // return all values on the stack\n\t\t}\n\t}\n\treturn r, err\n}", "func (op *OpPlus) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) + op.RightChild.Eval(x, y)\n}", "func (op *OpPlus) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) + op.RightChild.Eval(x, y)\n}", "func (fr *Frame) EvalExpr(a T) (result T) {\n\treturn fr.ParseExpression(a.String())\n}", "func execEval(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret, ret1 := types.Eval(args[0].(*token.FileSet), args[1].(*types.Package), token.Pos(args[2].(int)), args[3].(string))\n\tp.Ret(4, ret, ret1)\n}", "func (state *State) EvalExpr(expr string) (interface{}, error) {\n\texp, err := govaluate.NewEvaluableExpression(expr)\n\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tres, err := exp.Evaluate(state.expr)\n\n\t\treturn res, err\n\t}\n}", "func (fn NoArgFunc) Eval(ctx *Context, r Row) (interface{}, error) {\n\treturn fn.Logic(ctx, r)\n}", "func (c *Context) Eval(script string) (*Value, error) {\n\t// When PHP compiles code with a non-NULL return value expected, it simply\n\t// prepends a `return` call to the code, thus breaking simple scripts that\n\t// would otherwise work. Thus, we need to wrap the code in a closure, and\n\t// call it immediately.\n\ts := C.CString(\"call_user_func(function(){\" + script + \"});\")\n\tdefer C.free(unsafe.Pointer(s))\n\n\tvptr, err := C.context_eval(c.context, s)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error executing script '%s' in context\", script)\n\t}\n\n\tval, err := NewValueFromPtr(vptr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn val, nil\n}", "func (op *OpX) Eval(x, y float32) float32 {\n\treturn x\n}", "func (op *OpX) Eval(x, y float32) float32 {\n\treturn x\n}", "func eval(expression TokenStream) (value int) {\n\ts := stack.New()\n\n\tfor _, token := range expression {\n\t\tif token.kind == OPERAND {\n\t\t\ts.Push(token)\n\t\t} else {\n\t\t\top1 := s.Pop().(Token)\n\t\t\top2 := s.Pop().(Token)\n\t\t\tvar result int\n\t\t\tswitch token.sValue {\n\t\t\tcase \"+\":\n\t\t\t\tresult = op1.iValue + op2.iValue\n\t\t\tcase \"*\":\n\t\t\t\tresult = op1.iValue * op2.iValue\n\t\t\t}\n\t\t\ts.Push(Token{kind: OPERAND, iValue: result})\n\t\t}\n\t}\n\n\tt := s.Pop().(Token)\n\tvalue = t.iValue\n\n\treturn\n}", "func (inst *hiddenInstance) Eval(expr ast.Expr) Value {\n\tv := inst.Value()\n\treturn v.Context().BuildExpr(expr, Scope(v), InferBuiltins(true))\n}", "func (p *Qlang) SafeEval(expr string) (err error) {\n\n\treturn p.SafeExec([]byte(expr), \"\")\n}", "func (d Decomposition) Eval() *big.Int {\n\tresult := big.NewInt(0)\n\tfor _, m := range d.monomes {\n\t\tresult.Add(result, m.eval())\n\t}\n\treturn result\n}", "func (p Primitive) Eval(a *Apl) (Value, error) {\n\treturn p, nil\n}", "func (fr *Frame) EvalExpr(a T) (result T) {\n\t// Optimization: It's already a number.\n\tif a.IsQuickNumber() {\n\t\treturn a\n\t}\n\n\ts := a.String()\n\t// Optimization: \"0\" and \"1\"\n\tif len(s) == 1 {\n\t\tif s == \"0\" {\n\t\t\treturn False\n\t\t}\n\t\tif s == \"1\" {\n\t\t\treturn True\n\t\t}\n\t}\n\n\treturn fr.ParseExpression(s)\n}", "func (form *Form) Eval(scope Scope, args ...interface{}) interface{} {\n\treturn form.Fn(scope, args...)\n}", "func (m *Message) Eval(vm *VM, locals Interface) (result Interface) {\n\treturn m.Send(vm, locals, locals)\n}", "func (op *OpCos) Eval(x, y float32) float32 {\n\treturn float32(math.Cos(float64(op.Child.Eval(x, y))))\n}", "func (op *OpSine) Eval(x, y float32) float32 {\n\treturn float32(math.Sin(float64(op.Child.Eval(x, y))))\n}", "func (v Variable) Evaluate() Expression {\n\treturn v\n}", "func Evaluate(input string) (decimal.Decimal, error) {\n\tvar stack []decimal.Decimal\n\tinputs := strings.Split(input, \" \")\n\n\tfor _, command := range inputs {\n\t\tswitch command {\n\t\tcase \"+\", \"-\", \"*\", \"/\", \"%\", \"^\":\n\t\t\tif len(stack) < 2 {\n\t\t\t\treturn decimal.Zero, errors.New(\"stack overflow\")\n\t\t\t}\n\t\t\tlhs := stack[len(stack)-2]\n\t\t\trhs := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-1]\n\t\t\tswitch command {\n\t\t\tcase \"+\":\n\t\t\t\trhs = lhs.Add(rhs)\n\t\t\tcase \"-\":\n\t\t\t\trhs = lhs.Sub(rhs)\n\t\t\tcase \"*\":\n\t\t\t\trhs = lhs.Mul(rhs)\n\t\t\tcase \"/\":\n\t\t\t\trhs = lhs.Div(rhs)\n\t\t\tcase \"%\":\n\t\t\t\trhs = lhs.Mod(rhs)\n\t\t\tcase \"^\":\n\t\t\t\trhs = lhs.Pow(rhs)\n\t\t\t}\n\t\t\tstack[len(stack)-1] = rhs\n\t\tcase \"abs\", \"atan\", \"ceil\", \"cos\", \"floor\", \"neg\", \"sin\", \"tan\":\n\t\t\tif len(stack) < 1 {\n\t\t\t\treturn decimal.Zero, errors.New(\"stack overflow\")\n\t\t\t}\n\t\t\tval := stack[len(stack)-1]\n\t\t\tswitch command {\n\t\t\tcase \"abs\":\n\t\t\t\tval = val.Abs()\n\t\t\tcase \"atan\":\n\t\t\t\tval = val.Atan()\n\t\t\tcase \"ceil\":\n\t\t\t\tval = val.Ceil()\n\t\t\tcase \"cos\":\n\t\t\t\tval = val.Cos()\n\t\t\tcase \"floor\":\n\t\t\t\tval = val.Floor()\n\t\t\tcase \"neg\":\n\t\t\t\tval = val.Neg()\n\t\t\tcase \"sin\":\n\t\t\t\tval = val.Sin()\n\t\t\tcase \"tan\":\n\t\t\t\tval = val.Tan()\n\t\t\t}\n\t\t\tstack[len(stack)-1] = val\n\t\tdefault:\n\t\t\tval, err := decimal.NewFromString(command)\n\t\t\tif err != nil {\n\t\t\t\treturn val, err\n\t\t\t}\n\t\t\tstack = append(stack, val)\n\t\t}\n\t}\n\n\tif len(stack) != 1 {\n\t\treturn decimal.Zero, errors.New(\"unclean stack\")\n\t}\n\treturn stack[0], nil\n}", "func (d *Division) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn divideNumericWithError(left, right)\n}", "func (op *OpMult) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) * op.RightChild.Eval(x, y)\n}", "func Evaluate(tpl string, data interface{}) (string, error) {\n\tt, err := Parse(tpl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn Execute(t, data)\n}", "func (p Polynomial) Eval(arg int) ed25519.Scalar {\n\tx := ed25519.New_scalar(*big.NewInt(int64(arg)))\n\tresult := p.coeffs[0].Add(p.coeffs[1].Mul(x))\n\tx_pow := x.Copy()\n\tfor i := 2; i < len(p.coeffs); i++ {\n\t\tx_pow = x_pow.Mul(x)\n\t\tresult = result.Add(p.coeffs[i].Mul(x_pow))\n\t}\n\treturn result\n}", "func (e *ExpressionAtom) Evaluate(dataContext IDataContext, memory *WorkingMemory) (reflect.Value, error) {\n\tif e.Evaluated == true {\n\t\treturn e.Value, nil\n\t}\n\tif e.Variable != nil {\n\t\tval, err := e.Variable.Evaluate(dataContext, memory)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\te.Value = val\n\t\te.Evaluated = true\n\t\treturn val, err\n\t}\n\tif e.FunctionCall != nil {\n\t\tvalueNode := dataContext.Get(\"DEFUNC\")\n\t\targs, err := e.FunctionCall.EvaluateArgumentList(dataContext, memory)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\tret, err := valueNode.CallFunction(e.FunctionCall.FunctionName, args...)\n\t\tif err != nil {\n\t\t\treturn reflect.Value{}, err\n\t\t}\n\t\te.Value = ret\n\t\te.Evaluated = true\n\t\treturn ret, err\n\t}\n\tpanic(\"should not be reached\")\n}", "func (f *funcExpr) Eval(record Record) (*Value, error) {\n\tswitch f.name {\n\tcase Avg, Sum:\n\t\treturn f.sum(record)\n\tcase Count:\n\t\treturn f.count(record)\n\tcase Max:\n\t\treturn f.max(record)\n\tcase Min:\n\t\treturn f.min(record)\n\tcase Coalesce:\n\t\treturn f.coalesce(record)\n\tcase NullIf:\n\t\treturn f.nullIf(record)\n\tcase ToTimestamp:\n\t\treturn f.toTimeStamp(record)\n\tcase UTCNow:\n\t\treturn f.utcNow(record)\n\tcase Substring:\n\t\treturn f.substring(record)\n\tcase CharLength, CharacterLength:\n\t\treturn f.charLength(record)\n\tcase Trim:\n\t\treturn f.trim(record)\n\tcase Lower:\n\t\treturn f.lower(record)\n\tcase Upper:\n\t\treturn f.upper(record)\n\t}\n\n\tpanic(fmt.Sprintf(\"unsupported aggregate function %v\", f.name))\n}", "func (f *CallExpression) Evaluate(ctx *Context) Value {\n\tcallable := f.Callable.Evaluate(ctx)\n\n\tif callable.Type == vtVariable {\n\t\tcallable = callable.Evaluate(ctx)\n\t}\n\n\tif callable.isCallable() {\n\t\tnewCtx := NewContext(\"\", nil)\n\t\targs := f.Args.EvaluateAll(ctx)\n\t\treturn callable.callable().Execute(newCtx, &args)\n\t}\n\n\tpanic(NewNotCallableError(callable))\n}", "func (a *Addition) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn addNumericWithError(left, right)\n}", "func Eval(input string, env interface{}) (interface{}, error) {\n\tif _, ok := env.(Option); ok {\n\t\treturn nil, fmt.Errorf(\"misused expr.Eval: second argument (env) should be passed without expr.Env\")\n\t}\n\n\ttree, err := parser.Parse(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := compiler.Compile(tree, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput, err := vm.Run(program, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn output, nil\n}", "func Eval(node ast.Node, env *object.Environment, stop <-chan struct{}) object.Object {\n\tselect {\n\tcase <-stop:\n\t\treturn ConstNil\n\tdefault:\n\t}\n\n\tswitch node := node.(type) {\n\t// statements\n\tcase *ast.Program:\n\t\treturn evalProgram(node, env, stop)\n\tcase *ast.LetStatement:\n\t\tval := Eval(node.Value, env, stop)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\tcase *ast.ReturnStatement:\n\t\tval := Eval(node.Value, env, stop)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\treturn &object.ReturnValue{Value: val}\n\tcase *ast.BlockStatement:\n\t\treturn evalBlockStatement(node, env, stop)\n\tcase *ast.ExpressionStatement:\n\t\treturn Eval(node.Expression, env, stop)\n\n\t\t// expressions\n\tcase *ast.PrefixExpression:\n\t\tright := Eval(node.Right, env, stop)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalPrefixExpr(node.Token, right)\n\tcase *ast.InfixExpression:\n\t\tif node.Operator == token.Assign {\n\t\t\treturn evalAssign(node, env, stop)\n\t\t}\n\n\t\tleft := Eval(node.Left, env, stop)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tright := Eval(node.Right, env, stop)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalInfixExpr(node.Token, left, right)\n\tcase *ast.IndexExpression:\n\t\tleft := Eval(node.Left, env, stop)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\n\t\tindex := Eval(node.Index, env, stop)\n\t\tif isError(index) {\n\t\t\treturn index\n\t\t}\n\t\treturn evalIndexExpr(node.Token, left, index)\n\tcase *ast.IfExpression:\n\t\treturn evalIfExpr(node, env, stop)\n\tcase *ast.WhileExpression:\n\t\treturn evalWhileExpr(node, env, stop)\n\tcase *ast.CallExpression:\n\t\tfunction := Eval(node.Func, env, stop)\n\t\tif isError(function) {\n\t\t\treturn function\n\t\t}\n\n\t\targs, err := evalExpressions(node.Args, env, stop)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn doFunction(node.Token, function, args, stop)\n\n\t\t// literals\n\tcase *ast.IntegerLiteral:\n\t\treturn &object.Integer{Value: node.Value}\n\tcase *ast.FloatLiteral:\n\t\treturn &object.Float{Value: node.Value}\n\tcase *ast.BooleanLiteral:\n\t\treturn boolToBoolean(node.Value)\n\tcase *ast.NilLiteral:\n\t\treturn ConstNil\n\tcase *ast.FunctionLiteral:\n\t\treturn &object.Function{Params: node.Params, Body: node.Body, Env: env}\n\tcase *ast.StringLiteral:\n\t\treturn &object.String{Value: node.Value}\n\tcase *ast.ArrayLiteral:\n\t\telems, err := evalExpressions(node.Elements, env, stop)\n\t\tif len(elems) == 1 && err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn &object.Array{Elements: elems}\n\tcase *ast.Identifier:\n\t\treturn evalIdentifier(node, env)\n\tcase *ast.AccessIdentifier:\n\t\treturn evalAccessIdentifier(node, env)\n\t}\n\treturn nil\n}", "func (e *BinExpr) Eval(ctx context.Context, local Scope) (_ Value, err error) {\n\ta, err := e.a.Eval(ctx, local)\n\tif err != nil {\n\t\treturn nil, WrapContextErr(err, e, local)\n\t}\n\n\tb, err := e.b.Eval(ctx, local)\n\tif err != nil {\n\t\treturn nil, WrapContextErr(err, e, local)\n\t}\n\tval, err := e.eval(ctx, a, b, local)\n\tif err != nil {\n\t\treturn nil, WrapContextErr(err, e, local)\n\t}\n\treturn val, nil\n}", "func Evaluate(e ast.Node, genCtx *GenCtx) parser_driver.ValueExpr {\n\tswitch t := e.(type) {\n\tcase *ast.ParenthesesExpr:\n\t\treturn Evaluate(t.Expr, genCtx)\n\tcase *ast.BinaryOperationExpr:\n\t\tres, err := operator.BinaryOps.Eval(t.Op.String(), Evaluate(t.L, genCtx), Evaluate(t.R, genCtx))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"error occurred on eval: %+v\", err))\n\t\t}\n\t\treturn res\n\tcase *ast.UnaryOperationExpr:\n\t\tres, err := operator.UnaryOps.Eval(t.Op.String(), Evaluate(t.V, genCtx))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"error occurred on eval: %+v\", err))\n\t\t}\n\t\treturn res\n\tcase *ast.IsNullExpr:\n\t\tsubResult := Evaluate(t.Expr, genCtx)\n\t\tc := ConvertToBoolOrNull(subResult)\n\t\tr := parser_driver.ValueExpr{}\n\t\tr.SetInt64(0)\n\t\tif c == -1 {\n\t\t\tr.SetInt64(1)\n\t\t}\n\t\treturn r\n\tcase *ast.ColumnNameExpr:\n\t\tfor key, value := range genCtx.unwrapPivotRows {\n\t\t\toriginTableName := t.Name.Table.L\n\t\t\tfor k, v := range genCtx.TableAlias {\n\t\t\t\tif v == originTableName {\n\t\t\t\t\toriginTableName = k\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\toriginColumnName := t.Name.Name.L\n\t\t\tif key == fmt.Sprintf(\"%s.%s\", originTableName, originColumnName) {\n\t\t\t\tv := parser_driver.ValueExpr{}\n\t\t\t\tv.SetValue(value)\n\t\t\t\tif tmpTable, ok := genCtx.TableAlias[t.Name.Table.L]; ok {\n\t\t\t\t\tt.Name.Table = model.NewCIStr(tmpTable)\n\t\t\t\t}\n\t\t\t\treturn v\n\t\t\t}\n\t\t}\n\t\tpanic(fmt.Sprintf(\"no such col %s in table %s\", t.Name, t.Name.Table))\n\tcase ast.ValueExpr:\n\t\tv := parser_driver.ValueExpr{}\n\t\tv.SetValue(t.GetValue())\n\t\tv.SetType(t.GetType())\n\t\treturn v\n\t}\n\n\t// is useless?\n\t// if e == nil {\n\t// \treturn trueValueExpr()\n\t// }\n\n\tpanic(\"not reachable\")\n\tv := parser_driver.ValueExpr{}\n\tv.SetNull()\n\treturn v\n}", "func (a *AddActivity) Eval(context activity.Context) (done bool, err error) {\n\n\t//mv := context.GetInput(ivMessage)\n\tnum1, _ := context.GetInput(ivNum1).(int)\n\tnum2, _ := context.GetInput(ivNum2).(int)\n\n\tactivityLog.Info(fmt.Sprintf(\"Num1: %d, Num2: %d\", num1, num2))\n\tactivityLog.Info(fmt.Sprintf(\"Addition is : %d\", num1+num2))\n\tcontext.SetOutput(ovAddition, num1+num2)\n\n\treturn true, nil\n}", "func evaluateExpression(c *Context, exp interface{}) interface{} {\r\n var val interface{}\r\n\r\n // fmt.Printf(\"Evaluating type %T, \\n\", exp)\r\n switch t := exp.(type) {\r\n case int:\r\n // fmt.Printf(\"Returning int %d\\n\", t)\r\n val = t\r\n case *Integer:\r\n val = t.Number\r\n case *StringPrimitive:\r\n val = t.str\r\n case string:\r\n val = t\r\n case []interface{}:\r\n val = t\r\n case *InfixExpression:\r\n // fmt.Printf(\"Evaluating infix expresison %T l: %T, r:%T\\n\", t,t.leftNode.Exp, t.rightNode.Exp)\r\n //Get the value of the left node and right\r\n lVal := evaluateExpression(c, t.leftNode.Exp)\r\n rVal := evaluateExpression(c, t.rightNode.Exp)\r\n\r\n\r\n //then apply the correct infix operator to the values\r\n val = evaluateInfixExpression(c, t.opType, lVal, rVal)\r\n\r\n case *Identifier:\r\n // fmt.Printf(\"Was identifier returning %v\\n\", t.id)\r\n if(t.id == \"nil\") {\r\n val = NewNil(0)\r\n } else {\r\n // fmt.Printf(\"Posssible indeitEifer %T\\n\", c.values[t.id])\r\n val = evaluateExpression(c, c.values[t.id])\r\n }\r\n case *CallExpression:\r\n // fmt.Printf(\"Evaluation call to %s\\n\",t.callee)\r\n\r\n //get declaration of call\r\n callDec := c.lookup(t.callee).(*FuncDeclaration)\r\n if(callDec.returnType == \"\") { //no rreturn type = unit\r\n val = &UnitType{}\r\n } else { //Evaluate the expression of the body for a value\r\n //This should produce a value and will execute all\r\n //of the code of the body as well\r\n for i, _ := range callDec.paramNodes {\r\n paramDec := callDec.paramNodes[i].Exp.(*Param)\r\n paramValue := t.paramNodes[i].Exp\r\n c.values[paramDec.id] = evaluateExpression(c, paramValue)\r\n val = c.values[paramDec.id]\r\n }\r\n\r\n }\r\n\r\n if(t.callee == \"printi\") {\r\n invokePrintI(c, t)\r\n } else if(t.callee == \"print\") {\r\n invokePrint(c, t)\r\n } else if(t.callee == \"not\") {\r\n invokeNot(c, t)\r\n } else { //Regular other user defined function do your thing!\r\n //invoke the body\r\n //Get the declaration of the calling function so we can execute it\r\n callDec := c.lookup(t.callee).(*FuncDeclaration)\r\n // fmt.Printf(\"Invoking random func \\n\")\r\n evaluateExpression(c, callDec.body.Exp)\r\n }\r\n case *IfThenElseExpression:\r\n condition := evaluateExpression(c, t.condNode.Exp).(bool)\r\n // fmt.Printf(\"Cond was %v \\n\", condition)\r\n //If else is nil then its an IfThen Exp\r\n if(t.elseNode == nil) {\r\n val = &UnitType{}\r\n if(condition) { //if the condition is true evaluatie the code inside\r\n evaluateExpression(c, t.thenNode.Exp)\r\n }\r\n } else { //otherwise its and ifThenElse\r\n if(condition) {\r\n val = evaluateExpression(c, t.thenNode.Exp)\r\n } else {\r\n val = evaluateExpression(c, t.elseNode.Exp)\r\n }\r\n }\r\n case *SeqExpression:\r\n // Value is equivalent to the last node of the seqence expression\r\n if(len(t.nodes) == 0) {\r\n val = &UnitType{}\r\n } else {\r\n // fmt.Printf(\"Seq type was %T\\n\", t.nodes[len(t.nodes)-1].Exp)\r\n val = evaluateExpression(c, t.nodes[len(t.nodes)-1].Exp)\r\n }\r\n case *Nil:\r\n val = NewNil(0)\r\n case *ArrayExp:\r\n arrType := getType(c, c.lookup(t.typeId)).(*Identifier)\r\n val = c.lookup(arrType.id)\r\n case *ForExpression:\r\n val = &UnitType{}\r\n case *LetExpression:\r\n if(len(t.exps) == 0) {\r\n val = &UnitType{}\r\n } else {\r\n // fmt.Printf(\"%T is last exp type\\n\", t.exps[len(t.exps)-1].Exp)\r\n // val = getType(c, t.exps[len(t.exps)-1].Exp)\r\n }\r\n case *Assignment:\r\n val = &UnitType{}\r\n case *RecordExp:\r\n var slc []interface{}\r\n for _, fcNode := range t.fieldCreateNodes {\r\n if b, isABinding := fcNode.Exp.(*Binding); isABinding {\r\n slc = append(slc, evaluateExpression(c, b.exp.Exp))\r\n }\r\n }\r\n val = slc\r\n default:\r\n fmt.Fprintf(os.Stderr, \"Could not evaluate exp %T\\n\", t)\r\n os.Exit(4)\r\n }\r\n\r\n return val\r\n}", "func (op *OpY) Eval(x, y float32) float32 {\n\treturn y\n}", "func (op *OpY) Eval(x, y float32) float32 {\n\treturn y\n}", "func (op *OpSin) Eval(x, y float32) float32 {\n\treturn float32(math.Sin(float64(op.Child.Eval(x, y))))\n}", "func (t *Check) Eval(r, s string) (bool, error) {\n\treturn false, errors.New(\"Not implemented\")\n}", "func (op *OpMinus) Eval(x, y float32) float32 {\n\treturn op.LeftChild.Eval(x, y) - op.RightChild.Eval(x, y)\n}", "func NumericEval(expression string, variables map[string]float64) (float64, error) {\n\ttokens, err := tokenize(expression)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tast, err := createNumericAST(tokens, 0)\n\tif err != nil {\n\t\tif _, ok := err.(eoi); !ok {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif ast == nil {\n\t\treturn 0, errors.New(\"unexpected nil ast\")\n\t}\n\n\treturn ast.Eval(variables)\n}", "func TestEval(t *testing.T) {\n\tany := `.+`\n\ttestCases := []struct {\n\t\tname string\n\t\tquery string\n\t\twantErr string\n\t\twant []values.Value\n\t}{\n\t\t{\n\t\t\tname: \"string interpolation\",\n\t\t\tquery: `\n\t\t\t\tstr = \"str\"\n\t\t\t\ting = \"ing\"\n\t\t\t\t\"str + ing = ${str+ing}\"`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewString(\"str + ing = string\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"string interpolation missing field\",\n\t\t\tquery: `\n\t\t\t\tr = makeRecord(o: {a: \"foo\", b: 42})\n\t\t\t\t\"r._value = ${r._value}\"`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"string interpolation non-string type\",\n\t\t\tquery: `\n\t\t\t\tr = makeRecord(o: {a: \"foo\", b: 42})\n\t\t\t\t\"r._value = ${r.b}\"`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewString(\"r._value = 42\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"string interpolation wrong type\",\n\t\t\tquery: `\n\t\t\t\tr = makeRecord(o: {a: \"foo\", b: 42})\n\t\t\t\t\"r = ${r}\"`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"call builtin function\",\n\t\t\tquery: \"six()\",\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewFloat(6.0),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"call function with fail\",\n\t\t\tquery: \"fail()\",\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"call function with duplicate args\",\n\t\t\tquery: \"plusOne(x:1.0, x:2.0)\",\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"binary expressions\",\n\t\t\tquery: `\n\t\t\tsix_value = six()\n\t\t\tnine_value = nine()\n\n\t\t\tfortyTwo() == six_value * nine_value\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"logical expressions short circuit\",\n\t\t\tquery: `\n six_value = six()\n nine_value = nine()\n\n not (fortyTwo() == six_value * nine_value) or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"function\",\n\t\t\tquery: `\n plusSix = (r) => r + six()\n plusSix(r:1.0) == 7.0 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"function block\",\n\t\t\tquery: `\n f = (r) => {\n r1 = 1.0 + r\n return (r + r1) / r\n }\n f(r:1.0) == 3.0 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"function block polymorphic\",\n\t\t\tquery: `\n f = (r) => {\n r2 = r * r\n return r2 / r\n }\n f(r:2.0) == 2.0 or fail()\n f(r:2) == 2 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"function with default param\",\n\t\t\tquery: `\n addN = (r,n=4) => r + n\n addN(r:2) == 6 or fail()\n addN(r:3,n:1) == 4 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"scope closing\",\n\t\t\tquery: `\n\t\t\tx = 5\n plusX = (r) => r + x\n plusX(r:2) == 7 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"nested scope mutations not visible outside\",\n\t\t\tquery: `\n\t\t\tx = 5\n xinc = () => {\n x = x + 1\n return x\n }\n xinc() == 6 or fail()\n x == 5 or fail()\n\t\t\t`,\n\t\t},\n\t\t// TODO(jsternberg): This test seems to not\n\t\t// infer the type constraints correctly for m.a,\n\t\t// but it doesn't fail.\n\t\t{\n\t\t\tname: \"return map from func\",\n\t\t\tquery: `\n toMap = (a,b) => ({\n a: a,\n b: b,\n })\n m = toMap(a:1, b:false)\n m.a == 1 or fail()\n not m.b or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"pipe expression\",\n\t\t\tquery: `\n\t\t\tadd = (a=<-,b) => a + b\n\t\t\tone = 1\n\t\t\tone |> add(b:2) == 3 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"ignore pipe default\",\n\t\t\tquery: `\n\t\t\tadd = (a=<-,b) => a + b\n\t\t\tadd(a:1, b:2) == 3 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"pipe expression function\",\n\t\t\tquery: `\n\t\t\tadd = (a=<-,b) => a + b\n\t\t\tsix() |> add(b:2.0) == 8.0 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"pipe builtin function\",\n\t\t\tquery: `\n\t\t\tsix() |> plusOne() == 7.0 or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"regex match\",\n\t\t\tquery: `\n\t\t\t\"abba\" =~ /^a.*a$/ or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"regex not match\",\n\t\t\tquery: `\n\t\t\t\"abc\" =~ /^a.*a$/ and fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not regex match\",\n\t\t\tquery: `\n\t\t\t\"abc\" !~ /^a.*a$/ or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not regex not match\",\n\t\t\tquery: `\n\t\t\t\"abba\" !~ /^a.*a$/ and fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"options metadata\",\n\t\t\tquery: `\n\t\t\toption task = {\n\t\t\t\tname: \"foo\",\n\t\t\t\trepeat: 100,\n\t\t\t}\n\t\t\ttask.name == \"foo\" or fail()\n\t\t\ttask.repeat == 100 or fail()\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"query with side effects\",\n\t\t\tquery: `sideEffect() == 0 or fail()`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewInt(0),\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"array index expression\",\n\t\t\tquery: `\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\tx = a[1]\n\t\t\t\tx == 2 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"dict expression\",\n\t\t\tquery: `\n\t\t\t\tm = [\"a\" + \"b\": 0, \"c\" + \"d\": 1]\n\t\t\t\tx = get(dict: m, key: \"ab\", default: 2)\n\t\t\t\ty = get(dict: m, key: \"cd\", default: 2)\n\t\t\t\tz = get(dict: m, key: \"ef\", default: 2)\n\t\t\t\tx == 0 and y == 1 and z == 2 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"empy dictionary\",\n\t\t\tquery: `\n\t\t\t\tm0 = [:]\n\t\t\t\tm1 = insert(dict: m0, key: \"a\", value: 0)\n\t\t\t\tm2 = insert(dict: m0, key: 0, value: \"a\")\n\t\t\t\tv1 = get(dict: m1, key: \"a\", default: -1)\n\t\t\t\tv2 = get(dict: m2, key: 0, default: \"b\")\n\t\t\t\tv1 == 0 and v2 == \"a\" or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"array index expression out of bounds low\",\n\t\t\tquery: `\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\ti = -1\n\t\t\t\tx = a[i]\n\t\t\t`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"array index expression out of bounds high\",\n\t\t\tquery: `\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\ti = 3\n\t\t\t\tx = a[i]\n\t\t\t`,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"array with complex index expression\",\n\t\t\tquery: `\n\t\t\t\tf = () => ({l: 0, m: 1, n: 2})\n\t\t\t\ta = [1, 2, 3]\n\t\t\t\tx = a[f().l]\n\t\t\t\ty = a[f().m]\n\t\t\t\tz = a[f().n]\n\t\t\t\tx == 1 or fail()\n\t\t\t\ty == 2 or fail()\n\t\t\t\tz == 3 or fail()\n\t\t\t`,\n\t\t},\n\t\t{\n\t\t\tname: \"short circuit logical and\",\n\t\t\tquery: `\n false and fail()\n `,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"short circuit logical or\",\n\t\t\tquery: `\n true or fail()\n `,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"no short circuit logical and\",\n\t\t\tquery: `\n true and fail()\n `,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"no short circuit logical or\",\n\t\t\tquery: `\n false or fail()\n `,\n\t\t\twantErr: any,\n\t\t},\n\t\t{\n\t\t\tname: \"conditional true\",\n\t\t\tquery: `\n\t\t\t\tif 1 != 0 then 10 else 100\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewInt(10),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"conditional false\",\n\t\t\tquery: `\n\t\t\t\tif 1 == 0 then 10 else 100\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewInt(100),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"conditional in function\",\n\t\t\tquery: `\n\t\t\t\tf = (t, c, a) => if t then c else a\n\t\t\t\t{\n\t\t\t\t\tv1: f(t: false, c: 30, a: 300),\n\t\t\t\t\tv2: f(t: true, c: \"cats\", a: \"dogs\"),\n\t\t\t\t}\n\t\t\t`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewObjectWithValues(map[string]values.Value{\n\t\t\t\t\t\"v1\": values.NewInt(300),\n\t\t\t\t\t\"v2\": values.NewString(\"cats\"),\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"exists\",\n\t\t\tquery: `hasValue(o: makeRecord(o: {value: 1}))`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"exists null\",\n\t\t\tquery: `hasValue(o: makeRecord(o: {val: 2}))`,\n\t\t\twant: []values.Value{\n\t\t\t\tvalues.NewBool(false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"invalid function parameter\",\n\t\t\tquery: `from(bucket: \"telegraf\") |> window(every: 0s)`,\n\t\t\twantErr: `error calling function \"window\" @\\d+:\\d+-\\d+:\\d+: window function requires at least one of \"every\" or \"period\" to be set and non-zero`,\n\t\t},\n\t\t{\n\t\t\t// tests that we don't nest error messages when\n\t\t\t// a function call fails and gets piped into another\n\t\t\t// function.\n\t\t\tname: \"nested function error\",\n\t\t\tquery: `from(bucket: \"telegraf\") |> window(every: 0s) |> mean()`,\n\t\t\twantErr: `error calling function \"window\" @\\d+:\\d+-\\d+:\\d+: window function requires at least one of \"every\" or \"period\" to be set and non-zero`,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\ttc := tc\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tsrc := prelude + tc.query\n\n\t\t\tctx, deps := dependency.Inject(context.Background(), dependenciestest.Default())\n\t\t\tdefer deps.Finish()\n\n\t\t\tsideEffects, _, err := runtime.Eval(ctx, src)\n\t\t\tif err != nil {\n\t\t\t\tif tc.wantErr == \"\" {\n\t\t\t\t\tt.Fatalf(\"unexpected error: %s\", err)\n\t\t\t\t}\n\n\t\t\t\t// We expect an error, so it should be a non-internal Flux error.\n\t\t\t\tif code := flux.ErrorCode(err); code == codes.Internal || code == codes.Unknown {\n\t\t\t\t\tt.Errorf(\"expected non-internal error code, got %s\", code)\n\t\t\t\t}\n\n\t\t\t\tre := regexp.MustCompile(tc.wantErr)\n\t\t\t\tif got := err.Error(); !re.MatchString(got) {\n\t\t\t\t\tt.Errorf(\"expected error to match pattern %q, but error was %q\", tc.wantErr, got)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if tc.wantErr != \"\" {\n\t\t\t\tt.Fatal(\"expected error\")\n\t\t\t}\n\n\t\t\tvs := getSideEffectsValues(sideEffects)\n\t\t\tif tc.want != nil && !cmp.Equal(tc.want, vs, semantictest.CmpOptions...) {\n\t\t\t\tt.Fatalf(\"unexpected side effect values -want/+got: \\n%s\", cmp.Diff(tc.want, vs, semantictest.CmpOptions...))\n\t\t\t}\n\t\t})\n\t}\n}", "func (i *IntNode) Eval(m memory.M) dragonscript.Value {\n\treturn dragonscript.Integer(i.value)\n}", "func (m *MockExpressionNode) Eval() func(backend.Row) (core.Value, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Eval\")\n\tret0, _ := ret[0].(func(backend.Row) (core.Value, error))\n\treturn ret0\n}", "func (f *function) Eval(a *Apl) (Value, error) {\n\tvar err error\n\tvar l, r Value\n\n\t// The right argument must be evaluated first.\n\t// Otherwise this A←1⋄A+(A←2) evaluates to 3,\n\t// but it should evaluate to 4.\n\tr, err = f.right.Eval(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif f.left != nil {\n\n\t\t// Special case for modified assignments.\n\t\t// Defer evaluation of the left argument.\n\t\tif d, ok := f.Function.(*derived); ok && d.op == \"←\" {\n\t\t\tl = assignment{f.left}\n\t\t} else {\n\t\t\tl, err = f.left.Eval(a)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t// Special case: the last function in a selective assignment uses Select instead of Call.\n\tif _, ok := f.right.(numVar); ok && f.selection {\n\t\tif d, ok := f.Function.(*derived); ok == true {\n\t\t\treturn d.Select(a, l, r)\n\t\t} else if p, ok := f.Function.(Primitive); ok == false {\n\t\t\treturn nil, fmt.Errorf(\"cannot use %T in selective assignment\", f.Function)\n\t\t} else {\n\t\t\treturn p.Select(a, l, r)\n\t\t}\n\t}\n\treturn f.Function.Call(a, l, r)\n}", "func (v LiteralValue) Eval(*Environment) (document.Value, error) {\n\treturn document.Value(v), nil\n}", "func (a Abstraction) Evaluate() Expression {\n\treturn Abstraction{a.Argument, a.Body.Evaluate()}\n}", "func (e *Evaluator) Evaluate(expression string) (*string, error) {\n\tinfixExpression, err := e.tknzr.Tokenize(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// a bit of syntax sugar: if expression contains only atoms\n\t// consider it as just a string literal\n\tif e.onlyAtoms(infixExpression) {\n\t\treturn &expression, nil\n\t}\n\n\tpostfixExpression, err := e.cnvtr.Convert(infixExpression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn e.evaluateExpression(postfixExpression)\n}", "func (m *Multiplication) Evaluate(left, right EvalResult) (EvalResult, error) {\n\treturn multiplyNumericWithError(left, right)\n}", "func (ev *Evaler) Eval(name, text string, n *parse.Chunk, ports []*Port) error {\n\top, err := ev.Compile(name, text, n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec := NewTopEvalCtx(ev, name, text, ports)\n\treturn ec.PEval(op)\n}", "func (session Runtime) Evaluate(code string, async bool, returnByValue bool) (interface{}, error) {\n\tresult, err := session.evaluate(code, session.currentContext(), async, returnByValue)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn result.Value, nil\n}", "func Calculate(substitutedExpression string) (float64, error) {\n\tvar node Node\n\tvar result Number\n\tvar p *Parser\n\tvar parseOk, evalOk bool\n\n\tsubstitutedExpression = NegativeNumberParser(substitutedExpression)\n\tp = new(Parser).Init(substitutedExpression)\n\tp.AddOperator('+', 1)\n\tp.AddOperator('-', 1)\n\tp.AddOperator('*', 2)\n\tp.AddOperator('/', 2)\n\tnode, parseOk = p.Parse()\n\tif parseOk {\n\t\tresult, evalOk = node.Eval()\n\t\tif evalOk {\n\t\t\treturn float64(result), nil // %v = default format\n\t\t} else {\n\t\t\treturn float64(result), fmt.Errorf(\"%s = Invalid Evaluation error\\n\", substitutedExpression)\n\t\t}\n\t} else {\n\t\treturn 0.0, fmt.Errorf(\"%s = Invalid Syntax error\\n\", substitutedExpression)\n\t}\n}", "func TestEvaluatorArithmetic(t *testing.T) {\n\tvar values = make(map[string]int)\n\ttestCases := []TestCase{\n\t\t{\n\t\t\tname: \"short expression\",\n\t\t\texpression: \"1+2*3\",\n\t\t\texpectedValue: 7,\n\t\t},\n\t\t{\n\t\t\tname: \"long expression\",\n\t\t\texpression: \"4/2-1+5%2\",\n\t\t\texpectedValue: 2,\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tresult, err := evaluator.Evaluate(tc.expression, values)\n\t\t\tassert.NoError(t, err, \"unexpected error\")\n\t\t\tassert.Equal(t, tc.expectedValue, result)\n\t\t})\n\t}\n}", "func (p *prog) Eval(input any) (v ref.Val, det *EvalDetails, err error) {\n\t// Configure error recovery for unexpected panics during evaluation. Note, the use of named\n\t// return values makes it possible to modify the error response during the recovery\n\t// function.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch t := r.(type) {\n\t\t\tcase interpreter.EvalCancelledError:\n\t\t\t\terr = t\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"internal error: %v\", r)\n\t\t\t}\n\t\t}\n\t}()\n\t// Build a hierarchical activation if there are default vars set.\n\tvar vars interpreter.Activation\n\tswitch v := input.(type) {\n\tcase interpreter.Activation:\n\t\tvars = v\n\tcase map[string]any:\n\t\tvars = activationPool.Setup(v)\n\t\tdefer activationPool.Put(vars)\n\tdefault:\n\t\treturn nil, nil, fmt.Errorf(\"invalid input, wanted Activation or map[string]any, got: (%T)%v\", input, input)\n\t}\n\tif p.defaultVars != nil {\n\t\tvars = interpreter.NewHierarchicalActivation(p.defaultVars, vars)\n\t}\n\tv = p.interpretable.Eval(vars)\n\t// The output of an internal Eval may have a value (`v`) that is a types.Err. This step\n\t// translates the CEL value to a Go error response. This interface does not quite match the\n\t// RPC signature which allows for multiple errors to be returned, but should be sufficient.\n\tif types.IsError(v) {\n\t\terr = v.(*types.Err)\n\t}\n\treturn\n}", "func (r *Rule) Eval(devices *devices.List, rules map[string]bool) (bool, error) {\n\treturn eval(r.Expression(), devices, rules, r.ast)\n}", "func (ev *Evaler) Eval(name, text string, n *parse.Chunk, ports []*Port) error {\n\top, err := ev.Compile(n)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec := NewTopEvalCtx(ev, name, text, ports)\n\treturn ec.PEval(op)\n}", "func (e *Eval) Value() values.T {\n\treturn e.root.Value\n}", "func (n *aliasPlanExpression) Evaluate(currentRow []interface{}) (interface{}, error) {\n\treturn n.expr.Evaluate(currentRow)\n}", "func eval(sc *scope, e sexpr) sexpr {\n\te = transform(sc, e)\n\tswitch e := e.(type) {\n\tcase cons: // a function to evaluate\n\t\tcons := e\n\t\tcar := eval(sc, cons.car)\n\t\tif !isFunction(car) && !isPrimitive(car) {\n\t\t\tpanic(\"Attempted application on non-function\")\n\t\t}\n\t\tcdr := cons.cdr\n\t\targs := flatten(cdr)\n\t\tif isPrimitive(car) {\n\t\t\treturn (car.(primitive))(sc, args)\n\t\t}\n\t\tf := car.(function)\n\t\t// This is a function - evaluate all arguments\n\t\tfor i, a := range args {\n\t\t\targs[i] = eval(sc, a)\n\t\t}\n\t\treturn f(sc, args)\n\tcase sym:\n\t\treturn sc.lookup(e)\n\t}\n\treturn e\n}", "func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {\n\tvar (\n\t\tres interface{}\n\t\tisNull bool\n\t)\n\tswitch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {\n\tcase types.ETInt:\n\t\tvar intRes int64\n\t\tintRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)\n\t\tif mysql.HasUnsignedFlag(tp.Flag) {\n\t\t\tres = uint64(intRes)\n\t\t} else {\n\t\t\tres = intRes\n\t\t}\n\tcase types.ETString:\n\t\tres, isNull, err = sf.EvalString(sf.GetCtx(), row)\n\t}\n\n\tif isNull || err != nil {\n\t\td.SetNull()\n\t\treturn d, err\n\t}\n\td.SetValue(res, sf.RetType)\n\treturn\n}", "func (e *ExpressionAtom) Evaluate() (reflect.Value, error) {\n\tvar val reflect.Value\n\tvar err error\n\tif e.Variable != nil {\n\t\tval, err = e.Variable.Evaluate()\n\t} else if e.FunctionCall != nil {\n\t\tval, err = e.FunctionCall.Evaluate()\n\t} else if e.MethodCall != nil {\n\t\tval, err = e.MethodCall.Evaluate()\n\t} else if e.Constant != nil {\n\t\tval, err = e.Constant.Evaluate()\n\t}\n\tif err == nil {\n\t\te.Value = val\n\t}\n\treturn val, err\n}", "func (ast *Return) Eval(env *Env, ctx *Codegen, gen *ssa.Generator) (\n\tssa.Value, bool, error) {\n\treturn ssa.Undefined, false, nil\n}", "func (f *functionQuery) Evaluate(t iterator) interface{} {\n\treturn f.Func(f.Input, t)\n}", "func (le ListExpr) Eval(scope Scope) (interface{}, error) {\n\tif len(le.List) == 0 {\n\t\treturn le.List, nil\n\t}\n\n\tval, err := le.List[0].Eval(scope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif macroFn, ok := val.(MacroFunc); ok {\n\t\tvar name string\n\t\tif sym, ok := le.List[0].(SymbolExpr); ok {\n\t\t\tname = sym.Symbol\n\t\t}\n\t\treturn macroFn(scope, name, le.List[1:])\n\t}\n\n\targs := []interface{}{}\n\tfor i := 1; i < len(le.List); i++ {\n\t\targ, err := le.List[i].Eval(scope)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\targs = append(args, arg)\n\t}\n\n\tif scopedFn, ok := val.(ScopedFunc); ok {\n\t\treturn scopedFn(scope, args...)\n\t}\n\n\treturn reflection.Call(val, args...)\n}", "func Eval(t testing.TestingT, options *EvalOptions, jsonFilePaths []string, resultQuery string) {\n\trequire.NoError(t, EvalE(t, options, jsonFilePaths, resultQuery))\n}", "func Evaluate(expression *[]string, dispatchTable DispatchTable, stack *Stack) interface{} {\n\n\tfor idx, token := range *expression {\n\t\tvar dispatchFunction DispatchFunc\n\n\t\tif _, err := strconv.ParseFloat(token, 64); err == nil {\n\t\t\tdispatchFunction = dispatchTable[\"FLOAT\"]\n\t\t} else {\n\t\t\tvar evalsOk bool\n\t\t\tif dispatchFunction, evalsOk = dispatchTable[token]; !evalsOk {\n\t\t\t\tdispatchFunction = dispatchTable[\"__DEFAULT__\"]\n\t\t\t\t// delete token from expression\n\t\t\t\tcopy((*expression)[idx:], (*expression)[idx+1:])\n\t\t\t\t(*expression)[len(*expression)-1] = \"\"\n\t\t\t\t(*expression) = (*expression)[:len(*expression)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tdispatchFunction(token, stack)\n\t}\n\treturn stack.Pop()\n}", "func (s *candidate) Evaluate() (float64, error) {\n\tr, err := s.Schedule()\n\treturn r.Evaluate(), err\n}", "func Evaluate(query string, values map[string]interface{}) interface{} {\n\ttokens := Parser(query)\n\trpn := ToPostfix(tokens)\n\touts := SolvePostfix(rpn, values)\n\treturn outs\n}", "func (this *Mod) Evaluate(item value.Value, context Context) (value.Value, error) {\n\treturn this.BinaryEval(this, item, context)\n}", "func (s *String) Eval(_, _ *Scope) (Value, error) {\n\treturn s, nil\n}", "func (p *Matcher) Eval(src string) (err error) {\n\treturn p.MatchExactly([]byte(src), \"\")\n}", "func (e *echo) Eval(str string) string {\n\treturn os.Expand(str, e.Val)\n}", "func (c *ComparisonExpr) eval(env *ExpressionEnv, result *EvalResult) {\n\tvar left, right EvalResult\n\tleft.init(env, c.Left)\n\tright.init(env, c.Right)\n\tcmp, err := c.Op.compare(&left, &right)\n\tif err != nil {\n\t\tthrowEvalError(err)\n\t}\n\tresult.setBoolean(cmp)\n}", "func (e *Engine) Eval(ctx map[string]interface{}) ([]*model.DecisionValue, error) {\n\tinput := e.actPool.Get().(*activation)\n\tdefer e.actPool.Put(input)\n\tinput.vars = ctx\n\tvar decisions []*model.DecisionValue\n\tfor tmplName, insts := range e.instances {\n\t\trt, found := e.runtimes[tmplName]\n\t\tif !found {\n\t\t\t// Report an error\n\t\t\tcontinue\n\t\t}\n\t\tfor _, inst := range insts {\n\t\t\tif !e.selectInstance(inst, input) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdecs, err := rt.Eval(inst, input)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdecisions = append(decisions, decs...)\n\t\t}\n\t}\n\treturn decisions, nil\n}", "func evaluate(arg1 *vector.Vector, oper *vector.Vector, arg2 *vector.Vector) *vector.Vector {\n\t//Store the operator in a temp string, to save typing it out\n\tvar operS string\n\toperS = oper.At(0).(string)\n\tvar val1, val2 int \n\tvar err1, err2 os.Error\n\tval1, err1 = strconv.Atoi(arg1.At(0).(string))\n\tval2, err2 = strconv.Atoi(arg2.At(0).(string))\n\t//screens for consecutive operators\n\tif(err1 != nil || err2 != nil){\n\t\tfmt.Println(\"expr: syntax error\")\n\t\tos.Exit(-2)\n\t}\n\tvar result int = -1\n\t//Evaluate based on the operator\n\tif operS == \"+\" {\n\t\tresult = val1 + val2\n\t} else if operS == \"-\" {\n\t\tresult = val1 - val2\n\t} else if operS == \"/\" {\n\t\tresult = val1 / val2\n\t} else if operS == \"*\" {\n\t\tresult = val1 * val2\n\t} else if operS == \"%\" {\n\t\tresult = val1 % val2\n\t}\n\t//Clear the arg1 vector and add the result to it, then return\n\t//(saves memory by not creating a new vector)\n\targ1.Cut(0, arg1.Len())\n\targ1.Push(strconv.Itoa(result))\n\treturn arg1\n}", "func (pp *ProcedureParam) Eval(ctx *sql.Context, r sql.Row) (interface{}, error) {\n\treturn pp.pRef.Get(pp.name)\n}", "func (ce *CollatedExpression) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {\n\ttyp := ce.expr.Type()\n\tif !types.IsText(typ) {\n\t\treturn nil, sql.ErrCollatedExprWrongType.New()\n\t}\n\tif ce.collation.CharacterSet() != typ.(sql.TypeWithCollation).Collation().CharacterSet() {\n\t\treturn nil, sql.ErrCollationInvalidForCharSet.New(\n\t\t\tce.collation.Name(), typ.(sql.TypeWithCollation).Collation().CharacterSet().Name())\n\t}\n\treturn ce.expr.Eval(ctx, row)\n}", "func (t *TagExpr) Eval(exprSelector string) interface{} {\n\texpr, ok := t.s.exprs[exprSelector]\n\tif !ok {\n\t\t// Compatible with single mode or the expression with the name @\n\t\tif strings.HasSuffix(exprSelector, ExprNameSeparator) {\n\t\t\texprSelector = exprSelector[:len(exprSelector)-1]\n\t\t\tif strings.HasSuffix(exprSelector, ExprNameSeparator) {\n\t\t\t\texprSelector = exprSelector[:len(exprSelector)-1]\n\t\t\t}\n\t\t\texpr, ok = t.s.exprs[exprSelector]\n\t\t}\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t}\n\tdir, base := splitFieldSelector(exprSelector)\n\ttargetTagExpr, err := t.checkout(dir)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn expr.run(base, targetTagExpr)\n}", "func eval(list []*Item) int {\n\n\tvar stack *Item\n\n\tfor _, node := range list {\n\n\t\tif node.Typ == Number {\n\t\t\tstack = stack.Push(node)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar left, right *Item\n\n\t\tstack, right = stack.Pop()\n\t\tstack, left = stack.Pop()\n\n\t\tvar val int\n\t\tswitch node.Operation {\n\t\tcase \"+\":\n\t\t\tval = left.Value + right.Value\n\t\tcase \"-\":\n\t\t\tval = left.Value - right.Value\n\t\tcase \"/\":\n\t\t\t// Watch for div-by-zero\n\t\t\tval = left.Value / right.Value\n\t\tcase \"*\":\n\t\t\tval = left.Value * right.Value\n\t\t}\n\t\tstack = stack.Push(&Item{Typ: Number, Value: val})\n\t}\n\n\treturn stack.Value\n}", "func Eval(node ast.Node, env *object.Environment) object.Object {\n\tswitch node := node.(type) {\n\n\t// Statements\n\tcase *ast.RootNode:\n\t\treturn evalRootNode(node, env)\n\n\tcase *ast.BlockStatement:\n\t\treturn evalBlockStmt(node, env)\n\n\tcase *ast.ExpressionStatement:\n\t\treturn Eval(node.Expression, env)\n\n\tcase *ast.ReturnStatement:\n\t\tval := Eval(node.ReturnValue, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\treturn &object.ReturnValue{Value: val}\n\n\tcase *ast.LetStatement:\n\t\tval := Eval(node.Value, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\n\tcase *ast.ConstStatement:\n\t\tval := Eval(node.Value, env)\n\t\tif isError(val) {\n\t\t\treturn val\n\t\t}\n\t\tenv.Set(node.Name.Value, val)\n\n\t// Expressions\n\tcase *ast.IntegerLiteral:\n\t\treturn &object.Integer{Value: node.Value}\n\n\tcase *ast.StringLiteral:\n\t\treturn &object.String{Value: node.Value}\n\n\tcase *ast.Boolean:\n\t\treturn nativeBoolToBooleanObj(node.Value)\n\n\tcase *ast.PrefixExpression:\n\t\tright := Eval(node.Right, env)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalPrefixExpr(node.Operator, right, node.Token.Line)\n\n\tcase *ast.InfixExpression:\n\t\tleft := Eval(node.Left, env)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tright := Eval(node.Right, env)\n\t\tif isError(right) {\n\t\t\treturn right\n\t\t}\n\t\treturn evalInfixExpr(node.Operator, left, right, node.Token.Line)\n\n\tcase *ast.PostfixExpression:\n\t\treturn evalPostfixExpr(env, node.Operator, node)\n\n\tcase *ast.IfExpression:\n\t\treturn evalIfExpr(node, env)\n\n\tcase *ast.Identifier:\n\t\treturn evalIdentifier(node, env)\n\n\tcase *ast.FunctionLiteral:\n\t\tparams := node.Parameters\n\t\tbody := node.Body\n\t\treturn &object.Function{\n\t\t\tParameters: params,\n\t\t\tBody: body,\n\t\t\tEnv: env,\n\t\t}\n\n\tcase *ast.CallExpression:\n\t\tfn := Eval(node.Function, env)\n\t\tif isError(fn) {\n\t\t\treturn fn\n\t\t}\n\t\targs := evalExprs(node.Arguments, env)\n\t\tif len(args) == 1 && isError(args[0]) {\n\t\t\treturn args[0]\n\t\t}\n\t\treturn applyFunction(fn, args, node.Token.Line)\n\n\tcase *ast.ArrayLiteral:\n\t\telements := evalExprs(node.Elements, env)\n\t\tif len(elements) == 1 && isError(elements[0]) {\n\t\t\treturn elements[0]\n\t\t}\n\t\treturn &object.Array{Elements: elements}\n\n\tcase *ast.IndexExpression:\n\t\tleft := Eval(node.Left, env)\n\t\tif isError(left) {\n\t\t\treturn left\n\t\t}\n\t\tindex := Eval(node.Index, env)\n\t\tif isError(index) {\n\t\t\treturn index\n\t\t}\n\t\treturn evalIndexExpr(left, index, node.Token.Line)\n\n\tcase *ast.HashLiteral:\n\t\treturn evalHashLiteral(node, env)\n\t}\n\n\treturn nil\n}" ]
[ "0.78225446", "0.7148306", "0.70671", "0.7050722", "0.6980047", "0.6950422", "0.69288963", "0.685653", "0.6832329", "0.66447026", "0.6639212", "0.6600153", "0.6545889", "0.65193206", "0.65044826", "0.6502576", "0.6476158", "0.64584225", "0.6431236", "0.6425402", "0.6418105", "0.6418105", "0.63964444", "0.63858604", "0.6364513", "0.6337169", "0.6330889", "0.6328099", "0.6328099", "0.6317278", "0.63159174", "0.6302402", "0.6284013", "0.6253582", "0.6246791", "0.624241", "0.62412035", "0.62311715", "0.6190466", "0.61798936", "0.6175938", "0.6173542", "0.61661774", "0.61646587", "0.6157976", "0.6157906", "0.61473227", "0.6139316", "0.6133098", "0.61317986", "0.61277527", "0.612455", "0.6113807", "0.6108641", "0.61068016", "0.60925865", "0.60925865", "0.60891753", "0.60866964", "0.60829395", "0.6082924", "0.60816693", "0.60489845", "0.60448545", "0.6023833", "0.6018569", "0.6016442", "0.60151786", "0.60101193", "0.6009476", "0.6007023", "0.59971327", "0.59947026", "0.5984881", "0.59815484", "0.59778446", "0.59731674", "0.59683675", "0.5967812", "0.5964234", "0.5962582", "0.5946943", "0.593662", "0.59344095", "0.59274465", "0.59250575", "0.5911193", "0.59059423", "0.59005594", "0.5892203", "0.5892028", "0.58908784", "0.58881795", "0.5885908", "0.58822536", "0.58804667", "0.587008", "0.5856987", "0.58561856", "0.5839251" ]
0.7565433
1
tokenize converts expression context to tokens
func (e *Exp) tokenize() []string { siz := len(e.context) tokens := make([]string, 0, 1) for i := 0; i < siz; i++ { ch := e.context[i] switch { case e.isSpace(ch): continue case ch == '(': tokens = append(tokens, "(") case ch == ')': tokens = append(tokens, ")") default: isOperator, op := e.checkOperatorAt(i) if !isOperator { op = e.getOperandAt(i) } tokens = append(tokens, op) i = i + len(op) - 1 } } return tokens }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func tokenize(text string) ([]Token, error) {\n\t// So we can split on whitespace, TODO - be better, maybe use strings.FieldsFunc() ?\n\ttext = strings.ReplaceAll(text, \"(\", \" ( \")\n\ttext = strings.ReplaceAll(text, \")\", \" ) \")\n\n\twords := strings.Fields(text)\n\ttokens := make([]Token, 0, len(words))\n\n\t// Determine the virtual type for each token\n\tfor i, word := range words {\n\t\ttoken := Token{\n\t\t\tname: word,\n\t\t}\n\n\t\tswitch {\n\t\tcase word == \"(\":\n\t\t\ttoken.Kind = Begin\n\n\t\tcase word == \")\":\n\t\t\ttoken.Kind = End\n\n\t\tcase word[0] >= '0' && word[0] <= '9' && strings.Contains(word, \".\"):\n\t\t\ttoken.Kind = Floating\n\n\t\t// TODO - case out negatives\n\t\tcase word[0] >= '0' && word[0] <= '9':\n\t\t\ttoken.Kind = Integral\n\n\t\tdefault:\n\t\t\tif i == 0 {\n\t\t\t\treturn nil, e(`first rune must be \"(\", got \"` + word + `\"`)\n\t\t\t}\n\n\t\t\tif tokens[i-1].Kind == Begin {\n\t\t\t\ttoken.Kind = Procedure\n\t\t\t} else {\n\t\t\t\ttoken.Kind = Value\n\t\t\t}\n\t\t}\n\n\t\ttokens = append(tokens, token)\n\t}\n\n\treturn tokens, nil\n}", "func Tokenize(s string) (e shared.Equation, err error) {\n e.Arguments = extractArguements(s)\n e.Operators = extractOperators(s)\n return\n}", "func tokenize(code string) ([]token, error) {\n\n}", "func (t *infixTokenizer) Tokenize(expression string) ([]token, error) {\n\tsplitter, err := newExpressionSplitter(func(value string) tokenType {\n\t\treturn t.tokenTypeByValue(value)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawTokens, err := splitter.SplitIntoTokens(expression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trefinedTokens := t.splitTokensByOperators(rawTokens)\n\tt.convertExpressionsIntoAtoms(refinedTokens)\n\n\treturn refinedTokens, nil\n}", "func tokenize(expr []byte, op1, op2 byte) (indices1 [][]byte, indices2 [][]byte) {\n\tdepth := 0\n\tindices1 = make([][]byte, 0, len(expr)/2)\n\tindices2 = make([][]byte, 0, len(expr)/2)\n\tstart := 0\n\twhich := 1\n\t// this is for the special case when there's a minus first\n\tif expr[0] == op2 && op2 == '-' {\n\t\twhich = 2\n\t\texpr = expr[1:]\n\t}\n\n\tfor i, v := range expr {\n\t\tif v == '(' {\n\t\t\tdepth++\n\t\t} else if v == ')' {\n\t\t\tdepth--\n\t\t} else if depth == 0 && (v == op1 || v == op2) {\n\t\t\tif which == 1 {\n\t\t\t\tindices1 = append(indices1, expr[start:i])\n\t\t\t} else {\n\t\t\t\tindices2 = append(indices2, expr[start:i])\n\t\t\t}\n\n\t\t\tif v == op1 {\n\t\t\t\twhich = 1\n\t\t\t} else {\n\t\t\t\twhich = 2\n\t\t\t}\n\t\t\tstart = i+1\n\n\t\t}\n\t}\n\t// last one\n\tif which == 1 {\n\t\tindices1 = append(indices1, expr[start:])\n\t} else {\n\t\tindices2 = append(indices2, expr[start:])\n\t}\n\n\treturn indices1, indices2\n}", "func Tokenize(input string) []string {\n\tinput = strings.TrimSpace(input)\n\trunes := []rune(input)\n\ttoken := \"\"\n\ttokens := []string{token, \"\\n\"}\n\n\tfor i := 0; i < len(runes); i++ {\n\t\tr := runes[i]\n\n\t\tif r == '\\n' {\n\t\t\tif len(token) > 0 {\n\t\t\t\ttokens = append(tokens, token)\n\t\t\t\ttoken = \"\"\n\t\t\t}\n\n\t\t\ttokens = append(tokens, \"\\n\")\n\t\t\tcontinue\n\t\t}\n\n\t\tend, literal := LiteralDelimiters[string(r)]\n\t\tif literal {\n\t\t\tif len(token) > 0 {\n\t\t\t\ttokens = append(tokens, token)\n\t\t\t\ttoken = \"\"\n\t\t\t}\n\n\t\t\tlen, str := parseLiteral(string(r), runes[i + 1:])\n\t\t\ti += len\n\t\t\ttokens = append(tokens, string(r) + str)\n\t\t\tif end == \"\\n\" { tokens = append(tokens, end) }\n\t\t\tcontinue\n\t\t}\n\n\t\topindex := matchOperator(runes, i)\n\t\tif opindex != -1 {\n\t\t\top := Operators[opindex]\n\t\t\ti += len(op) - 1\n\n\t\t\t// weird hack to get dot operator to play nicely with floating-point numbers\n\t\t\tisNumber := false\n\t\t\tif op == \".\" {\n\t\t\t\t_, err := strconv.ParseFloat(token, 64)\n\t\t\t\tisNumber = err == nil\n\t\t\t}\n\n\t\t\tif op != \".\" || (!isNumber) {\n\t\t\t\tif len(token) > 0 {\n\t\t\t\t\ttokens = append(tokens, token)\n\t\t\t\t\ttoken = \"\"\n\t\t\t\t}\n\n\t\t\t\ttokens = append(tokens, op)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t_, delimiter := TokenDelimiters[string(r)]\n\t\tif !delimiter && !unicode.IsSpace(r) {\n\t\t\ttoken += string(r)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(token) > 0 {\n\t\t\ttokens = append(tokens, token)\n\t\t}\n\n\t\ttoken = \"\"\n\t\tif delimiter {\n\t\t\ttokens = append(tokens, string(r))\n\t\t}\n\t}\n\n\tif len(token) > 0 { tokens = append(tokens, token) }\n\ttokens = append(tokens, \"\\n\", \"\")\n\n\treturn tokens\n}", "func tokenize(src string) []string {\n\tsrc = strings.Replace(src, \"(\", \" ( \", -1)\n\tsrc = strings.Replace(src, \")\", \" ) \", -1)\n\treturn strings.Fields(src)\n}", "func (t *Tokenizer) Tokenize() []Token {\n\tinput, err := ioutil.ReadFile(t.filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt.input = string(input)\n\tvar toks []Token\n\tfor {\n\t\t// new line will be omitted in preprocessor, but still needed to parse #include ... and #define ...\n\t\tif tok := t.readNewLine(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tt.trimSpace()\n\n\t\ts := t.cur()\n\t\tif s == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif t.isComment() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readStrLiteral(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readCharLiteral(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readDigitLiteral(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readReserved(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readMultiCharOp(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readRuneFrom(\"+-*/(){}[]<>;=,&.!|^:?~#\"); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tok := t.readID(); tok != nil {\n\t\t\ttoks = append(toks, tok)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Fatalf(\"Unexpected input %s\\n\", s)\n\t}\n\tif t.addEOF {\n\t\ttoks = append(toks, newEOFTok())\n\t}\n\tp := newPreprocessor(toks, t.addEOF, t.filePath)\n\treturn p.Preprocess()\n}", "func Tokenize(str string) *list.List {\r\n\r\n\ttokens := list.New()\r\n\r\n\tvar tokenType = 0\r\n\tvar curToken = \"\"\r\n\tvar curTokenPos = 0\r\n\tfor i := 0; i < len(str); i++ {\r\n\t\tvar c = str[i]\r\n\r\n\t\tif (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' {\r\n\t\t\tif tokenType == 0 {\r\n\t\t\t\ttokenType = TokenIdentifier\r\n\t\t\t\tcurToken += string(c)\r\n\t\t\t\tcurTokenPos = i\r\n\t\t\t} else if tokenType == TokenIdentifier {\r\n\t\t\t\tcurToken += string(c)\r\n\t\t\t} else if tokenType == TokenNumber {\r\n\t\t\t\tif c == 'e' || c == 'E' {\r\n\t\t\t\t\tcurToken += string(c)\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// this must be unit information\r\n\t\t\t\t\tif tokenType != 0 {\r\n\t\t\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttokenType = TokenIdentifier\r\n\t\t\t\t\tcurToken += string(c)\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tpanic(\"Don't know what happens here\")\r\n\t\t\t}\r\n\t\t} else if (c >= '0' && c <= '9') || c == '.' {\r\n\t\t\tif tokenType == 0 {\r\n\t\t\t\ttokenType = TokenNumber\r\n\t\t\t\tcurTokenPos = i\r\n\t\t\t}\r\n\t\t\tcurToken += string(c)\r\n\t\t} else if c == '-' {\r\n\t\t\t// could be negative number or subtraction\r\n\t\t\tif len(curToken) > 1 && curToken[len(curToken) - 1] == 'e' {\r\n\t\t\t\tcurToken += string(c)\r\n\t\t\t} else {\r\n\t\t\t\tif tokenType != 0 {\r\n\t\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t\t}\r\n\t\t\t\ttokens.PushBack(Token{TokenOperatorSubtract, i, string(c)})\r\n\t\t\t\tcurToken = \"\"\r\n\t\t\t\ttokenType = 0\r\n\t\t\t}\r\n\t\t} else if c == '=' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenOperatorEquals, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '+' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenOperatorAdd, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '*' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenOperatorMultiply, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '/' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenOperatorDivide, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '^' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenOperatorExponent, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '{' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenBraceOpen, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '}' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenBraceClose, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '(' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenParenthesisOpen, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == ')' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenParenthesisClose, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == '[' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenBracketOpen, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == ']' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenBracketClose, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == ',' {\r\n\t\t\t/*if tokenType == TokenNumber {\r\n\t\t\t\tcurToken += string(c)\r\n\t\t\t} else*/{\r\n\t\t\t\tif tokenType != 0 {\r\n\t\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t\t}\r\n\t\t\t\ttokens.PushBack(Token{TokenComma, i, string(c)})\r\n\t\t\t\tcurToken = \"\"\r\n\t\t\t\ttokenType = 0\r\n\t\t\t}\r\n\t\t} else if c == ';' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenStatementTerminator, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else if c == ':' {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\ttokens.PushBack(Token{TokenUnitSeparator, i, string(c)})\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t} else {\r\n\t\t\tif tokenType != 0 {\r\n\t\t\t\ttokens.PushBack(Token{tokenType, curTokenPos, curToken})\r\n\t\t\t}\r\n\t\t\tcurToken = \"\"\r\n\t\t\ttokenType = 0\r\n\t\t}\r\n\t}\r\n\r\n\treturn tokens\r\n\r\n}", "func Tokenize(str string) *TokenList {\n\tvar tkn Token\n\n\tlog.Debug(\"Parsing...\" + str)\n\n\ttl := NewTokenList()\n\tr := []rune(str)\n\n\tfor {\n\t\t//make sure that there is a rune to process\n\t\tif r == nil || len(r) <= 0 {\n\t\t\tbreak\n\t\t}\n\t\t//test for whitespace and condense into one token\n\t\tif isWhiteSpace(r[0]) {\n\t\t\tr = getWhiteSpace(r)\n\t\t\tcontinue\n\t\t}\n\t\tif isLetter(r[0]) || isUnderScore(r[0]) {\n\t\t\tr, tkn = getIdentifier(r)\n\t\t\ttl.Add(tkn)\n\t\t\tcontinue\n\t\t}\n\n\t\tif isQuote(r[0]) {\n\t\t\t// add QUOTE token\n\t\t\tr, tkn = getQuote(r)\n\t\t\ttl.Add(tkn)\n\t\t\tcontinue\n\n\t\t}\n\n\t\tif isDigit(r[0]) {\n\t\t\tr, tkn = getNumber(r)\n\t\t\ttl.Add(tkn)\n\t\t\tcontinue\n\t\t}\n\n\t\t//check to see if it is a symbol\n\t\t// Check double char symbols first\n\t\tif len(r) > 1 {\n\t\t\tif Symbl, isSymbl := WordMap[string(r[0])+string(r[1])]; isSymbl {\n\t\t\t\ttl.Add(Symbl)\n\t\t\t\tr = r[2:]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// now single char symbols\n\t\tif Symbl, isSymbl := WordMap[string(r[0])]; isSymbl {\n\t\t\ttl.Add(Symbl)\n\t\t\tr = r[1:]\n\t\t\tcontinue\n\t\t}\n\n\t\ttl.Add(NewValueToken(Unk, string(r[0])))\n\t\tr = r[1:]\n\n\t}\n\n\treturn tl\n\n}", "func (ds *DefaultSyntax) tokenize() error {\n\t// Note this split on a single white space, if we want to split on white spaces\n\t// we can use a regexp for it regexp.MustCompile(`\\S+`) and then re.FindAllString(input, -1)\n\ttokens := strings.Split(ds.input, ds.separator)\n\t// We check if it has been passed the strings format for Day of week and month\n\t// and we convert it to the integers\n\ttokens[3] = utils.StringToNumber(tokens[3], ds.monthsMapper)\n\ttokens[4] = utils.StringToNumber(tokens[4], ds.daysMapper)\n\n\t// we do not validate the command token that is in the last position\n\tfor i := 0; i < len(tokens)-2; i++ {\n\t\terr := ds.validateTokens(tokens[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t//TO DO use \"enum\" instead of integer here\n\tce := &CronElements{Minute: tokens[0],\n\t\tHour: tokens[1],\n\t\tDayMonth: tokens[2],\n\t\tMonth: tokens[3],\n\t\tDayWeek: tokens[4],\n\t\tCommand: tokens[5],\n\t}\n\tds.cronElements = ce\n\treturn nil\n}", "func tidyTokens(tokens []token) ([]token, error) {\n\tfor i := range tokens {\n\t\tt := &(tokens[i])\n\t\tif t.Kind == govaluate.VARIABLE {\n\t\t\t// Change function name to lower case\n\t\t\tt.Value = strings.ToLower(t.Value.(string))\n\t\t\t_, ok := indicatorMap[t.Value.(string)]\n\t\t\tif !ok {\n\t\t\t\treturn nil, newError(fmt.Sprintf(\"Unsupported function used: %s\", t.Value.(string)))\n\t\t\t}\n\t\t} else if t.Kind == govaluate.CLAUSE {\n\t\t\tt.Value = \"(\"\n\t\t} else if t.Kind == govaluate.CLAUSE_CLOSE {\n\t\t\tt.Value = \")\"\n\t\t}\n\t}\n\treturn tokens, nil\n}", "func Tokenize(tokenizer *LongLexto, text string) []Token {\n\ttokenizer.SetText(text)\n\tresult := []Token{}\n\n\tfor tokenizer.HasNext() {\n\t\tresult = append(result, tokenizer.Next())\n\t}\n\n\treturn result\n}", "func Tokenize(src string) token.Tokens {\n\tvar s scanner.Scanner\n\ts.Init(src)\n\tvar tokens token.Tokens\n\tfor {\n\t\tsubTokens, err := s.Scan()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\ttokens.Add(subTokens...)\n\t}\n\treturn tokens\n}", "func Tokenize(s Sentence) []string {\n\treturn strings.Split(s.Input, \" \")\n}", "func (t *Tokenizer) Tokenize() ([]*Token, error) {\n\tvar err error\n\tres := make([]*Token, 0, 10)\n\n\tl := len(t.in)\n\ti := 0\n\tmode := modeNorm\n\tcurToken := t.newToken(typeStaticPart)\n\tbracketCounter := 0\n\n\tfor {\n\t\tskip1 := false\n\n\t\tif i >= l {\n\t\t\tif len(curToken.part) > 0 {\n\t\t\t\tres = append(res, curToken)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\tswitch mode {\n\t\tcase modeNorm:\n\t\t\tbracketCounter = 0\n\t\t\tif t.in[i] == '$' {\n\t\t\t\t// peek one ahead\n\t\t\t\tif i < l-1 {\n\t\t\t\t\tif t.in[i+1] == '{' {\n\t\t\t\t\t\tmode = modeBeginParam\n\t\t\t\t\t\tskip1 = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase modeBeginParam:\n\t\t\tif t.in[i] == '{' {\n\t\t\t\tif len(curToken.part) > 0 {\n\t\t\t\t\tres = append(res, curToken)\n\t\t\t\t}\n\t\t\t\tcurToken = t.newToken(typeParamPart)\n\n\t\t\t\tmode = modeInParam\n\t\t\t\tskip1 = true\n\t\t\t}\n\n\t\tcase modeInParam:\n\t\t\tif t.in[i] == '{' {\n\t\t\t\tbracketCounter++\n\n\t\t\t\tcurToken.withNestedParam = true\n\t\t\t}\n\t\t\tif t.in[i] == '}' {\n\t\t\t\tbracketCounter--\n\t\t\t\tif bracketCounter < 0 {\n\t\t\t\t\tif len(curToken.part) > 0 {\n\t\t\t\t\t\tres = append(res, curToken)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn res, &TokenizeError{what: \"empty params not allowed\", pos: i, token: curToken}\n\t\t\t\t\t}\n\t\t\t\t\tcurToken = t.newToken(typeStaticPart)\n\n\t\t\t\t\tmode = modeNorm\n\t\t\t\t\tskip1 = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif skip1 == false {\n\t\t\tcurToken.part = append(curToken.part, t.in[i])\n\t\t}\n\n\t\t//fmt.Printf(\"%d (%c) mode=%d bc=%d curTokenPart=%s\\n\", i, t.in[i], mode, bracketCounter, curToken.part)\n\n\t\ti++\n\t}\n\n\tif mode == modeInParam {\n\t\treturn res, &TokenizeError{what: \"invalid bracket balance\", pos: i, token: curToken}\n\t}\n\n\treturn res, err\n}", "func (t *infixTokenizer) splitTokensBySingleOperator(tokens []token, operator string) []token {\n\tresult := make([]token, 0, len(tokens))\n\n\tfor _, tkn := range tokens {\n\t\tif tkn.Type == expressionType {\n\t\t\tresult = append(result, t.splitSingleTokenBySingleOperator(tkn.Value, operator)...)\n\t\t} else {\n\t\t\tresult = append(result, tkn)\n\t\t}\n\t}\n\n\treturn result\n}", "func (e *htmlTag) parseTokens() []string {\n\tvar inQuote bool\n\tvar inDelim bool\n\tvar tokens []string\n\tvar token string\n\n\tstr := strings.Join(e.ln.tokens[1:], space)\n\tfor _, chr := range str {\n\t\tswitch c := string(chr); c {\n\t\tcase space:\n\t\t\tif inQuote || inDelim {\n\t\t\t\ttoken += c\n\t\t\t} else {\n\t\t\t\ttokens = append(tokens, token)\n\t\t\t\ttoken = \"\"\n\t\t\t}\n\t\tcase doubleQuote:\n\t\t\tif !inDelim {\n\t\t\t\tif inQuote {\n\t\t\t\t\tinQuote = false\n\t\t\t\t} else {\n\t\t\t\t\tinQuote = true\n\t\t\t\t}\n\t\t\t}\n\t\t\ttoken += c\n\t\tdefault:\n\t\t\ttoken += c\n\t\t\tif inDelim {\n\t\t\t\tif strings.HasSuffix(token, e.opts.DelimRight) {\n\t\t\t\t\tinDelim = false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif strings.HasSuffix(token, e.opts.DelimLeft) {\n\t\t\t\t\tinDelim = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(token) > 0 {\n\t\ttokens = append(tokens, token)\n\t}\n\treturn tokens\n}", "func (ps *Parser) getTokens() Tokens {\n\t// state-dependent character evaluation (order is important)\n\tfor !ps.EOF() {\n\t\tif ps.InBracket {\n\t\t\tif ps.Token.TType == TokenTypeCurrencyLanguage {\n\t\t\t\tif ps.currentChar() != Dash && ps.currentChar() != BracketClose {\n\t\t\t\t\tif len(ps.Token.Parts) == 0 {\n\t\t\t\t\t\tps.Token.Parts = append(ps.Token.Parts, Part{Token: Token{TType: TokenSubTypeLanguageInfo}})\n\t\t\t\t\t}\n\t\t\t\t\tps.Token.Parts[len(ps.Token.Parts)-1].Token.TValue += ps.currentChar()\n\t\t\t\t}\n\t\t\t\tif ps.currentChar() == Dash {\n\t\t\t\t\tif len(ps.Token.Parts) == 1 {\n\t\t\t\t\t\tps.Token.Parts[0].Token.TType = TokenSubTypeCurrencyString\n\t\t\t\t\t}\n\t\t\t\t\tif len(ps.Token.Parts) == 1 {\n\t\t\t\t\t\tps.Token.Parts = append(ps.Token.Parts, Part{Token: Token{TType: TokenSubTypeLanguageInfo}})\n\t\t\t\t\t} else if len(ps.Token.Parts) > 1 {\n\t\t\t\t\t\tps.Token.Parts[1].Token.TValue += ps.currentChar()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ps.currentChar() == Comma {\n\t\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(ps.Token.TValue) > 1 && inStrSlice(ConditionOperators, ps.Token.TValue[1:], true) != -1 {\n\t\t\t\tif ps.currentChar() == Dash || strings.ContainsAny(NumCodeChars, ps.currentChar()) {\n\t\t\t\t\tps.Token.TType = TokenTypeCondition\n\t\t\t\t\tps.Token.Parts = []Part{\n\t\t\t\t\t\t{Token: Token{TType: TokenTypeOperator, TValue: ps.Token.TValue[1:]}},\n\t\t\t\t\t\t{Token: Token{TType: TokenTypeOperand}},\n\t\t\t\t\t}\n\t\t\t\t\tps.Token.TValue = \"\"\n\t\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ps.currentChar() == BracketClose {\n\t\t\t\tps.InBracket = false\n\t\t\t\tif ps.Token.TType == TokenTypeCondition && len(ps.Token.Parts) == 2 {\n\t\t\t\t\tps.Token.Parts[1].Token.TValue = ps.Token.TValue\n\t\t\t\t\tps.Tokens.add(ps.Token.Parts[0].Token.TValue+ps.Token.Parts[1].Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tif l := len(ps.Token.TValue); l > 2 {\n\t\t\t\t\tlit := ps.Token.TValue[1 : l-1]\n\n\t\t\t\t\tif idx := inStrSlice(ColorNames, lit, false); idx != -1 {\n\t\t\t\t\t\tps.Tokens.add(lit, TokenTypeColor, nil)\n\t\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\t\tps.Offset++\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tif idx := inStrSlice(GeneralFormattingSwitchArguments, lit, false); idx != -1 {\n\t\t\t\t\t\tps.Tokens.add(ps.Token.TValue, TokenTypeSwitchArgument, nil)\n\t\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\t\tps.Offset++\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tif ps.Token.TType == TokenTypeCurrencyLanguage {\n\t\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\t\tps.Offset++\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tps.Token.TType, ps.Token.TValue = TokenTypeUnknown, lit\n\t\t\t\t\tisDateTime := true\n\t\t\t\t\tfor _, ch := range lit {\n\t\t\t\t\t\tif !strings.ContainsAny(DatesTimesCodeChars, strings.ToUpper(string(ch))) {\n\t\t\t\t\t\t\tisDateTime = false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif isDateTime {\n\t\t\t\t\t\tps.Token.TType = TokenTypeElapsedDateTimes\n\t\t\t\t\t}\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !ps.InBracket {\n\t\t\tif strings.ContainsAny(NumCodeChars, ps.currentChar()) {\n\t\t\t\tif ps.Token.TType == TokenTypeZeroPlaceHolder || ps.Token.TType == TokenTypeDenominator {\n\t\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif ps.Token.TType == TokenTypeFraction {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{TType: TokenTypeDenominator, TValue: ps.currentChar()}\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif ps.Token.TType != \"\" {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t}\n\t\t\t\tif ps.Token.TValue != \"\" && !strings.ContainsAny(NumCodeChars, ps.Token.TValue) {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, TokenTypeLiteral, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t}\n\t\t\t\tps.Token.TType = TokenTypeZeroPlaceHolder\n\t\t\t\tif ps.currentChar() != Zero {\n\t\t\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\t\t}\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ps.currentChar() == Hash {\n\t\t\t\tif ps.Token.TType != TokenTypeHashPlaceHolder && ps.Token.TType != \"\" {\n\t\t\t\t\tif ps.Token.TValue == Dot {\n\t\t\t\t\t\tps.Token.TType = TokenTypeDecimalPoint\n\t\t\t\t\t}\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t}\n\t\t\t\tps.Token.TType = TokenTypeHashPlaceHolder\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ps.currentChar() == Dot {\n\t\t\t\tif ps.Token.TType == TokenTypeZeroPlaceHolder || ps.Token.TType == TokenTypeHashPlaceHolder {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Tokens.add(ps.currentChar(), TokenTypeDecimalPoint, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\tps.Offset++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !ps.InString {\n\t\t\t\t\tif ps.Token.TType != \"\" && strings.ContainsAny(NumCodeChars, ps.nextChar()) {\n\t\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\t\tps.Token = Token{}\n\t\t\t\t\t}\n\t\t\t\t\tps.Token.TType = TokenTypeDecimalPoint\n\t\t\t\t}\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif strings.ContainsAny(Dollar+Dash+Plus+ParenOpen+ParenClose+Colon+Whitespace, ps.currentChar()) {\n\t\t\tif ps.InBracket {\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Token.TType = TokenTypeCurrencyLanguage\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ps.Token.TType != TokenTypeLiteral && ps.Token.TType != TokenTypeDateTimes && ps.Token.TType != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{TType: TokenTypeLiteral, TValue: ps.currentChar()}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif ps.Token.TValue != BackSlash && ps.Token.TType == \"\" && inStrSlice(AmPm, ps.Token.TValue, false) == -1 {\n\t\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\t}\n\n\t\t\tif ps.Token.TType == TokenTypeLiteral {\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif ps.currentChar() == Underscore {\n\t\t\tps.Offset += 2\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Asterisk {\n\t\t\tps.Tokens.add(ps.nextChar(), TokenTypeRepeatsChar, ps.Token.Parts)\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset += 2\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == BackSlash {\n\t\t\tif ps.Token.TValue != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t}\n\t\t\tps.Tokens.add(ps.nextChar(), TokenTypeLiteral, ps.Token.Parts)\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset += 2\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Dash {\n\t\t\tif ps.Token.TType != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t}\n\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\tif ps.currentChar() != ps.nextChar() {\n\t\t\t\tps.Tokens.add(ps.currentChar(), ps.Token.TType, ps.Token.Parts)\n\t\t\t}\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Comma {\n\t\t\tif ps.Token.TType == TokenTypeZeroPlaceHolder || ps.Token.TType == TokenTypeHashPlaceHolder {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Tokens.add(ps.currentChar(), TokenTypeThousandsSeparator, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !ps.InString {\n\t\t\t\tif ps.Token.TType == TokenTypeLiteral {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{TType: TokenTypeThousandsSeparator}\n\t\t\t\t}\n\t\t\t\tif ps.Token.TType == TokenTypeDateTimes {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{TType: TokenTypeLiteral}\n\t\t\t\t}\n\t\t\t\tif ps.currentChar() != ps.nextChar() {\n\t\t\t\t\tif ps.Token.TType == \"\" {\n\t\t\t\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\t\t\t}\n\t\t\t\t\tps.Tokens.add(ps.currentChar(), ps.Token.TType, ps.Token.Parts)\n\t\t\t\t}\n\t\t\t\tps.Token = Token{}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Whitespace {\n\t\t\tif inStrSlice(AmPm, ps.Token.TValue, false) != -1 {\n\t\t\t\tps.Token.TType = TokenTypeDateTimes\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ps.Token.TType != \"\" && ps.Token.TType != TokenTypeLiteral {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t}\n\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\tps.Tokens.add(ps.currentChar(), ps.Token.TType, ps.Token.Parts)\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Slash {\n\t\t\tif ps.Token.TType == TokenTypeDateTimes {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Tokens.add(ps.currentChar(), TokenTypeLiteral, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ps.Token.TType == TokenTypeDigitalPlaceHolder {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{TType: TokenTypeFraction, TValue: ps.currentChar()}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif ps.currentChar() == Colon && ps.Token.TType == TokenTypeDateTimes {\n\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\tps.Tokens.add(ps.currentChar(), TokenTypeLiteral, ps.Token.Parts)\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == QuoteDouble {\n\t\t\tps.Offset++\n\t\t\tif ps.InString && len(ps.Token.TValue) > 0 {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, TokenTypeLiteral, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t\tps.InString = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ps.Token.TValue != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t}\n\t\t\tps.InString = true\n\t\t\tps.Token = Token{TType: TokenTypeLiteral}\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == At {\n\t\t\tif len(ps.Tokens.Sections) <= ps.Tokens.SectionIndex {\n\t\t\t\tps.Tokens.Sections = append(ps.Tokens.Sections, Section{Type: TokenSectionText})\n\t\t\t}\n\t\t\tps.Tokens.Sections[ps.Tokens.SectionIndex].Type = TokenSectionText\n\t\t\tif ps.Token.TType != \"\" && !ps.InBracket {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t}\n\t\t\tps.Token = Token{TType: TokenTypeTextPlaceHolder, TValue: ps.currentChar()}\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == BracketOpen {\n\t\t\tif ps.Token.TType == \"\" && ps.Token.TValue != \"\" {\n\t\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\t}\n\t\t\tif ps.Token.TType != \"\" && !ps.InBracket {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t}\n\t\t\tps.InBracket = true\n\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Question {\n\t\t\tif ps.Token.TType != \"\" && ps.Token.TType != TokenTypeDigitalPlaceHolder {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t}\n\t\t\tps.Token.TType = TokenTypeDigitalPlaceHolder\n\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == Percent {\n\t\t\tif ps.Token.TType != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t}\n\t\t\tps.Token.TType = TokenTypePercent\n\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif ps.currentChar() == BlockDelimiter {\n\t\t\tsectionTypes := []string{TokenSectionPositive, TokenSectionNegative, TokenSectionZero, TokenSectionText}\n\t\t\tif ps.Token.TType != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t}\n\t\t\tif len(ps.Tokens.Sections) <= ps.Tokens.SectionIndex {\n\t\t\t\tps.Tokens.Sections = append(ps.Tokens.Sections, Section{Type: sectionTypes[ps.Tokens.SectionIndex]})\n\t\t\t}\n\t\t\tps.Tokens.SectionIndex++\n\t\t\tif ps.Tokens.SectionIndex > 3 {\n\t\t\t\ttokens := fTokens()\n\t\t\t\ttokens.reset()\n\t\t\t\treturn Tokens{}\n\t\t\t}\n\t\t\tps.Token = Token{}\n\t\t\tps.Tokens.Sections = append(ps.Tokens.Sections, Section{Type: sectionTypes[ps.Tokens.SectionIndex]})\n\t\t\tps.Offset++\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.EqualFold(\"E+\", ps.doubleChar()) {\n\t\t\tif ps.Token.TType != \"\" {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t}\n\t\t\tps.Token.TType = TokenTypeExponential\n\t\t\tps.Token.TValue += ps.doubleChar()\n\t\t\tps.Offset += 2\n\t\t\tcontinue\n\t\t}\n\n\t\tif ap, matched := ps.apPattern(); ap != -1 {\n\t\t\tps.Tokens.add(matched, TokenTypeDateTimes, ps.Token.Parts)\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset += len(matched)\n\t\t\tcontinue\n\t\t}\n\n\t\tif general, matched := ps.generalPattern(); general != -1 {\n\t\t\tps.Tokens.add(matched, TokenTypeGeneral, ps.Token.Parts)\n\t\t\tps.Token = Token{}\n\t\t\tps.Offset += len(matched)\n\t\t\tcontinue\n\t\t}\n\n\t\t// token accumulation\n\t\tif !ps.InBracket && !ps.InString {\n\t\t\tif strings.ContainsAny(DatesTimesCodeChars, strings.ToUpper(ps.currentChar())) {\n\t\t\t\tif inStrSlice(AmPm, ps.Token.TValue, false) != -1 {\n\t\t\t\t\tps.Token.TType = TokenTypeDateTimes\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t}\n\t\t\t\tif ps.Token.TType == TokenTypeLiteral || ps.Token.TType == TokenTypeDateTimes && !strings.ContainsAny(ps.Token.TValue, ps.currentChar()) {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t}\n\t\t\t\tif ps.Token.TType != \"\" && ps.Token.TType != TokenTypeDateTimes {\n\t\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\t\tps.Token = Token{}\n\t\t\t\t}\n\t\t\t\tps.Token.TType = TokenTypeDateTimes\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.ContainsAny(DatesTimesCodeChars, strings.ToUpper(ps.Token.TValue)) {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, TokenTypeDateTimes, ps.Token.Parts)\n\t\t\t\tps.Token = Token{TType: TokenTypeLiteral, TValue: ps.currentChar()}\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.ContainsAny(DatesTimesCodeChars, strings.ToUpper(ps.nextChar())) {\n\t\t\t\tps.Token.TValue += ps.currentChar()\n\t\t\t\tps.Token.TType = TokenTypeLiteral\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ps.currentChar() == QuoteSingle {\n\t\t\t\tps.Offset++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !strings.ContainsAny(NumCodeChars, ps.currentChar()) && ps.Token.TType == TokenTypeZeroPlaceHolder {\n\t\t\t\tps.Tokens.add(ps.Token.TValue, ps.Token.TType, ps.Token.Parts)\n\t\t\t\tps.Token = Token{}\n\t\t\t}\n\t\t}\n\t\tps.Token.TValue += ps.currentChar()\n\t\tps.Offset++\n\t}\n\n\t// dump remaining accumulation\n\tif len(ps.Token.TValue) > 0 {\n\t\ttokenType := TokenTypeLiteral\n\t\tif ps.Token.TType != \"\" {\n\t\t\ttokenType = ps.Token.TType\n\t\t}\n\t\tps.Tokens.add(ps.Token.TValue, tokenType, nil)\n\t}\n\n\ttokens := fTokens()\n\ttokens.reset()\n\treturn ps.Tokens\n}", "func lex(s string) ([]string, []int) {\n\ti := 0\n\tvar tokens []string\n\tvar starts []int\n\tfor i < len(s) {\n\t\tstart := i\n\t\tif isWhitespace(s[i]) {\n\t\t\t// Skip whitespaces\n\t\t\ti++\n\t\t\tfor i < len(s) && isWhitespace(s[i]) {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif isLetter(s[i]) || isNumber(s[i]) {\n\t\t\t// Lump number and variable tokens together, since numbers can\n\t\t\t// contain letters (like 0x10) and variables can contain numbers\n\t\t\t// (like a1). They can be later distinguished with isNumberToken and\n\t\t\t// isVariableToken.\n\t\t\ti++\n\t\t\tfor i < len(s) && (isLetter(s[i]) || isNumber(s[i])) {\n\t\t\t\ti++\n\t\t\t}\n\t\t} else {\n\t\t\tif i+1 < len(s) && isTwoByteOp(s[i:i+2]) {\n\t\t\t\ti += 2\n\t\t\t} else {\n\t\t\t\ti += 1\n\t\t\t}\n\t\t}\n\t\ttokens = append(tokens, s[start:i])\n\t\tstarts = append(starts, start)\n\t}\n\treturn tokens, starts\n}", "func Tokenize(input []byte) []Token {\n\tcurToken := \"\"\n\tvar tokens []Token\n\tcurTokenType := None\n\tvar curLine uint = 1\n\tvar curCol uint = 1\n\tvar curColStart uint = 1\n\tfor _, runeValue := range input {\n\t\tnextTokenType := curTokenType\n\t\tswitch curTokenType {\n\t\tcase None:\n\t\t\tif unicode.IsPunct(rune(runeValue)) {\n\t\t\t\tnextTokenType = Punctuation\n\t\t\t} else if unicode.IsSpace(rune(runeValue)) {\n\t\t\t\tnextTokenType = Whitespace\n\t\t\t} else if unicode.IsDigit(rune(runeValue)) {\n\t\t\t\tnextTokenType = Number\n\t\t\t} else if unicode.IsLetter(rune(runeValue)) {\n\t\t\t\tnextTokenType = Word\n\t\t\t}\n\t\t\tbreak\n\t\tcase Punctuation:\n\t\t\tif unicode.IsSpace(rune(runeValue)) {\n\t\t\t\tnextTokenType = Whitespace\n\t\t\t} else if unicode.IsDigit(rune(runeValue)) {\n\t\t\t\tnextTokenType = Number\n\t\t\t} else if unicode.IsLetter(rune(runeValue)) {\n\t\t\t\tnextTokenType = Word\n\t\t\t}\n\t\t\tbreak\n\t\tcase Whitespace:\n\t\t\tif unicode.IsPunct(rune(runeValue)) {\n\t\t\t\tnextTokenType = Punctuation\n\t\t\t} else if unicode.IsDigit(rune(runeValue)) || stringInSlice(rune(runeValue), []rune{rune('-'), rune('$')}) {\n\t\t\t\tnextTokenType = Number\n\t\t\t} else if unicode.IsLetter(rune(runeValue)) {\n\t\t\t\tnextTokenType = Word\n\t\t\t}\n\t\t\tbreak\n\t\tcase Number:\n\t\t\tif unicode.IsPunct(rune(runeValue)) && !stringInSlice(rune(runeValue), []rune{rune(','), rune('.')}) {\n\t\t\t\tnextTokenType = Punctuation\n\t\t\t} else if unicode.IsSpace(rune(runeValue)) {\n\t\t\t\tnextTokenType = Whitespace\n\t\t\t}\n\t\t\tbreak\n\t\tcase Word:\n\t\t\tif unicode.IsPunct(rune(runeValue)) {\n\t\t\t\tnextTokenType = Punctuation\n\t\t\t} else if unicode.IsSpace(rune(runeValue)) {\n\t\t\t\tnextTokenType = Whitespace\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif nextTokenType == curTokenType {\n\t\t\tcurToken += string(runeValue)\n\t\t} else {\n\t\t\tif curTokenType != None {\n\t\t\t\ttokens = append(tokens, Token{\n\t\t\t\t\ttokType: curTokenType,\n\t\t\t\t\tvalue: curToken,\n\t\t\t\t\tline: curLine,\n\t\t\t\t\tcolStart: curColStart,\n\t\t\t\t\tcolEnd: curCol - 1, //the last token ended on the previous character\n\t\t\t\t})\n\t\t\t\tcurColStart = curCol\n\t\t\t}\n\t\t\tcurToken = string(runeValue)\n\t\t\tcurTokenType = nextTokenType\n\t\t}\n\t\tcurCol++\n\t\tif rune(runeValue) == rune('\\n') {\n\t\t\tcurCol = 1\n\t\t\tcurLine++\n\t\t}\n\t}\n\ttokens = append(tokens, Token{\n\t\ttokType: curTokenType,\n\t\tvalue: curToken,\n\t\tline: curLine,\n\t\tcolStart: curColStart,\n\t\tcolEnd: curCol - 1,\n\t})\n\treturn tokenizeStep2(tokens)\n}", "func (s Sentence) Tokenize() []string {\n\treturn strings.Split(s.Input, \" \")\n}", "func Tokenize(txt string) []string {\n\ttxt = strings.ToLower(txt)\n\ttxt = spacereplace.ReplaceAllString(txt, \" \")\n\treturn strings.Fields(txt)\n}", "func parseExpression(tokens []*lexmachine.Token, vars []Variable, pos int) (output []Node, endPos int, err error) {\n\t// Here we loop through the tokens multiple times and convert each piece to a (possibly nested) Node\n\t// Buffers are used to hold intermediate results between passes\n\t// Passes should be in order of operator precedence (e.g. * before +)\n\tbuffer := make([]interface{}, 0)\n\n\t// First pass for parentheses, functions, and variable substitution\nparen: // label used to escape for loop\n\tfor pos < len(tokens) {\n\t\ttokenType := tokenTypeName(tokens[pos])\n\t\tvalue := tokens[pos].Value.(string)\n\t\tswitch tokenType {\n\t\tcase \",\": // skip commas and move the position forward\n\t\t\tpos++\n\t\tcase \")\": // we hit the end of the current parenthesis\n\t\t\tbreak paren // escape for loop\n\t\tcase \"(\": // start a new parenthesis, nested node here\n\t\t\tnodes, end, cErr := parseExpression(tokens, vars, pos+1)\n\t\t\tif cErr != nil {\n\t\t\t\terr = cErr\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor _, n := range nodes {\n\t\t\t\tbuffer = append(buffer, n)\n\t\t\t}\n\t\t\tpos = end + 1\n\t\tcase \"IDENT\":\n\t\t\tif isFunction(value) { // nested node here\n\t\t\t\tif tokens[pos+1].Value.(string) == \"(\" {\n\t\t\t\t\tnode := Node{value, make([]interface{}, 0)}\n\t\t\t\t\tiNodes, end, cErr := parseExpression(tokens, vars, pos+2)\n\t\t\t\t\tif cErr != nil {\n\t\t\t\t\t\terr = cErr\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tfor _, n := range iNodes {\n\t\t\t\t\t\tnode.Args = append(node.Args, n)\n\t\t\t\t\t}\n\t\t\t\t\tbuffer = append(buffer, node)\n\t\t\t\t\tpos = end + 1\n\t\t\t\t} else {\n\t\t\t\t\terr = fmt.Errorf(\"expected '(' after %s\", value)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else { // it's a Variable\n\t\t\t\tfor _, v := range vars {\n\t\t\t\t\tif value == v.N {\n\t\t\t\t\t\tnode := Node{v.T, make([]interface{}, 0)}\n\t\t\t\t\t\tif v.T == \"NUMBER\" {\n\t\t\t\t\t\t\tf, fErr := reformatFloat(v.V)\n\t\t\t\t\t\t\tif fErr != nil {\n\t\t\t\t\t\t\t\terr = fErr\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnode.Args = append(node.Args, f)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnode.Args = append(node.Args, v.V)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbuffer = append(buffer, node)\n\t\t\t\t\t\tpos++\n\t\t\t\t\t\tgoto paren // continue for loop at next token\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\terr = fmt.Errorf(\"the identifier '%s' was not found\", value)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase \"NUMBER\": // reformat the float (e.g. 2 => 2.000000)\n\t\t\tf, fErr := reformatFloat(value)\n\t\t\tif fErr != nil {\n\t\t\t\terr = fErr\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnode := Node{tokenType, make([]interface{}, 0)}\n\t\t\tnode.Args = append(node.Args, f)\n\t\t\tbuffer = append(buffer, node)\n\t\t\tpos++\n\t\tcase \"STRING\":\n\t\t\t// Replace any params/vars with their value\n\t\t\tfor _, v := range vars {\n\t\t\t\tif strings.HasPrefix(v.N, \"$\") {\n\t\t\t\t\tvalue = strings.ReplaceAll(value, v.N, v.V)\n\t\t\t\t}\n\t\t\t}\n\t\t\tnode := Node{tokenType, make([]interface{}, 0)}\n\t\t\tnode.Args = append(node.Args, value)\n\t\t\tbuffer = append(buffer, node)\n\t\t\tpos++\n\t\tdefault:\n\t\t\t// misc type that doesn't need further processing right now\n\t\t\tnode := Node{tokenType, make([]interface{}, 0)}\n\t\t\tnode.Args = append(node.Args, value)\n\t\t\tbuffer = append(buffer, node)\n\t\t\tpos++\n\t\t}\n\t}\n\t// set the endPos now since we've done a pass thru the original tokens\n\t// further passes will be on the buffers and so the end positions will be irrelevant to the function caller\n\tendPos = pos\n\n\t// \"*\", \"/\", \"%\"\n\tbufferNew := make([]interface{}, 0)\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"*\", \"/\", \"%\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// \"+\", \"-\"\n\tbuffer = nil\n\tbuffer = append(buffer, bufferNew...)\n\tbufferNew = nil\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"+\", \"-\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// \"||\"\n\tbuffer = nil\n\tbuffer = append(buffer, bufferNew...)\n\tbufferNew = nil\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"||\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// \"<\", \"<=\", \">\", \">=\"\n\tbuffer = nil\n\tbuffer = append(buffer, bufferNew...)\n\tbufferNew = nil\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"<\", \"<=\", \">\", \">=\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// \"=\", \"<>\", \"!=\", \"^=\"\n\tbuffer = nil\n\tbuffer = append(buffer, bufferNew...)\n\tbufferNew = nil\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"=\", \"<>\", \"!=\", \"^=\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// \"AND\"\n\tbuffer = nil\n\tbuffer = append(buffer, bufferNew...)\n\tbufferNew = nil\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"AND\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// \"OR\"\n\tbuffer = nil\n\tbuffer = append(buffer, bufferNew...)\n\tbufferNew = nil\n\tpos = 0\n\tfor pos < len(buffer) {\n\t\tswitch buffer[pos].(type) {\n\t\tcase Node:\n\t\t\tswitch buffer[pos].(Node).Exp {\n\t\t\tcase \"OR\":\n\t\t\t\tnode := Node{\n\t\t\t\t\tExp: buffer[pos].(Node).Exp,\n\t\t\t\t\tArgs: []interface{}{\n\t\t\t\t\t\tbufferNew[len(bufferNew)-1],\n\t\t\t\t\t\tbuffer[pos+1],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbufferNew[len(bufferNew)-1] = node\n\t\t\t\tpos += 2\n\t\t\tdefault:\n\t\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\t\tpos++\n\t\t\t}\n\t\tdefault:\n\t\t\tbufferNew = append(bufferNew, buffer[pos])\n\t\t\tpos++\n\t\t}\n\t}\n\n\t// validate each output is a Node\n\t// TODO this check shouldn't be needed but keeping for now while in heavy dev\n\tfor _, b := range bufferNew {\n\t\tif n, ok := b.(Node); ok {\n\t\t\toutput = append(output, n)\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"exptected a Node but got: %s\\n+%v\", reflect.TypeOf(bufferNew[0]), bufferNew[0])\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}", "func (l *Lexer) CreateTokens(inputText []rune) ([]*Token, []error) {\r\n\tvar tokens []*Token\r\n\tvar errGlobal []error\r\n\tsplittedText := strings.SplitAfter(string(inputText), \"\")\r\n\t//main loop for lexer\r\n\tvar (\r\n\t\tcurrLine int = 1\r\n\t\tcurrOffset int = 0\r\n\t)\r\n\r\n\tfor index := 0; index < len(inputText); index++ {\r\n\t\tvar tokenExists bool = false\r\n\t\tsymbol := string(inputText[index])\r\n\r\n\t\tcurrOffset++\r\n\t\t//check if token is number\r\n\t\tif IsNumber([]rune(symbol)[0]) || (index <= len(splittedText) && symbol == \".\" && IsNumber([]rune(splittedText[index+1])[0])) {\r\n\t\t\ti, number, err := CheckNumber(index, splittedText)\r\n\t\t\tlength := i - index\r\n\t\t\tindex = i\r\n\t\t\tif err != nil { //show error\r\n\t\t\t\terrGlobal = append(errGlobal, err)\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: err.Error(),\r\n\t\t\t\t\tValue: number,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\tPrintError(i, splittedText, token)\r\n\t\t\t\terrGlobal = append(errGlobal, err)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\ttoken := &Token{\r\n\t\t\t\tType: \"number\",\r\n\t\t\t\tValue: number,\r\n\t\t\t\tLine: currLine,\r\n\t\t\t\tOffset: currOffset,\r\n\t\t\t\tLength: length,\r\n\t\t\t}\r\n\t\t\ttokens = append(tokens, token)\r\n\t\t\tcontinue\r\n\r\n\t\t}\r\n\r\n\t\t//check if token is string\r\n\t\tif symbol == `\"` || symbol == `'` { //stringCheck\r\n\t\t\ti, name, err := ProcessString(index, splittedText)\r\n\t\t\tif err != nil {\r\n\t\t\t\terrGlobal = append(errGlobal, err)\r\n\t\t\t\tindex = i\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: err.Error(),\r\n\t\t\t\t\tValue: name,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\r\n\t\t\t\tPrintError(i, splittedText, token)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\t//index = i\r\n\t\t\ttoken := &Token{\r\n\t\t\t\tType: \"string\",\r\n\t\t\t\tValue: name,\r\n\t\t\t}\r\n\t\t\tPrintError(i, splittedText, token)\r\n\t\t\treturn nil, []error{fmt.Errorf(\"Знайдений тип, що не можна привести до int\")}\r\n\t\t\ttokens = append(tokens, token)\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\t//check if token is one of special symbols\r\n\t\tfor key, value := range l.SpecialSymbols {\r\n\t\t\tif key == symbol {\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tValue: key,\r\n\t\t\t\t\tType: value,\r\n\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\tLength: 1,\r\n\t\t\t\t}\r\n\t\t\t\tif value == `whitespace` {\r\n\t\t\t\t\tcurrLine++\r\n\t\t\t\t\tcurrOffset = 0\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\ttokenExists = true\r\n\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t}\r\n\t\tif tokenExists {\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\t//Check if token is one of basic operator symbol\r\n\t\tfor _, value := range l.Operators.SimpleSymbol {\r\n\t\t\tif symbol == value {\r\n\t\t\t\ttoken, i := l.Operators.PredictOperator(index, splittedText)\r\n\t\t\t\tindex = i\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\ttokenExists = true\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t}\r\n\t\tif tokenExists {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\t//check if token is commentary\r\n\t\tif symbol == \"#\" {\r\n\t\t\ti, name := ProcessCommentary(index, splittedText)\r\n\t\t\tlength := i - index\r\n\t\t\tindex = i\r\n\t\t\ttoken := &Token{\r\n\t\t\t\tType: \"commentary\",\r\n\t\t\t\tValue: name,\r\n\t\t\t\tLine: currLine,\r\n\t\t\t\tOffset: currOffset,\r\n\t\t\t\tLength: length,\r\n\t\t\t}\r\n\t\t\ttokens = append(tokens, token)\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tif IsAlphabet(([]rune(symbol))[0]) {\r\n\t\t\ti, name := CheckName(index, splittedText)\r\n\t\t\tlength := i - index\r\n\t\t\tindex = i\r\n\r\n\t\t\tfor key, value := range l.Operators.LogicalOperators { //check \"AND OR \"\r\n\t\t\t\tif name == key {\r\n\t\t\t\t\ttoken := &Token{\r\n\t\t\t\t\t\tType: value,\r\n\t\t\t\t\t\tValue: name,\r\n\t\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\t\tLength: length,\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\t\ttokenExists = true\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif tokenExists {\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tfor key, value := range l.Operators.IdentityOperators { //check \"IS\"\r\n\t\t\t\tif name == key {\r\n\t\t\t\t\ttoken := &Token{\r\n\t\t\t\t\t\tType: value,\r\n\t\t\t\t\t\tValue: name,\r\n\t\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\t\tLength: length,\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\t\ttokenExists = true\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif tokenExists {\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tfor key, value := range l.Operators.MembershipOperators { //CHECK IN\r\n\t\t\t\tif name == key {\r\n\t\t\t\t\ttoken := &Token{\r\n\t\t\t\t\t\tType: value,\r\n\t\t\t\t\t\tValue: name,\r\n\t\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\t\tLength: length,\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\t\ttokenExists = true\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif tokenExists {\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\tfor key, value := range l.KeyWords { //DEF FOR\r\n\t\t\t\tif name == key {\r\n\t\t\t\t\ttoken := &Token{\r\n\t\t\t\t\t\tType: value,\r\n\t\t\t\t\t\tValue: name,\r\n\t\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\t\tLength: length,\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\t\ttokenExists = true\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif tokenExists {\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tif name == \"True\" || name == \"False\" { //check boolean\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: \"Boolean\",\r\n\t\t\t\t\tValue: name,\r\n\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\t\tLength: length,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tif name == \"if\" { //check boolean\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: \"IF\",\r\n\t\t\t\t\tValue: name,\r\n\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\tLength: length,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tif name == \"else\" { //check boolean\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: \"ELSE\",\r\n\t\t\t\t\tValue: name,\r\n\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\tLength: length,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tif name == \"break\" { //check boolean\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: \"break\",\r\n\t\t\t\t\tValue: name,\r\n\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\tLength: length,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\tif name == \"continue\" { //check boolean\r\n\t\t\t\ttoken := &Token{\r\n\t\t\t\t\tType: \"continue\",\r\n\t\t\t\t\tValue: name,\r\n\t\t\t\t\tLine: currLine,\r\n\t\t\t\t\tOffset: currOffset,\r\n\t\t\t\t\tLength: length,\r\n\t\t\t\t}\r\n\t\t\t\ttokens = append(tokens, token)\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\t\t\ttoken := &Token{\r\n\t\t\t\tType: \"Name\",\r\n\t\t\t\tValue: name,\r\n\t\t\t\tLine: currLine,\r\n\t\t\t\tOffset: currOffset,\r\n\t\t\t\tLength: length,\r\n\t\t\t}\r\n\t\t\ttokens = append(tokens, token)\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t}\r\n\treturn tokens, errGlobal\r\n}", "func getTokens(sql string) ([]token, error) {\n\ttokens := []token{}\n\terr := lex(sql, func(t token) {\n\t\ttokens = append(tokens, t)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tokens, nil\n}", "func (t *nextTokenizer) tokenize(q data.Queryable, lastEvaluatedKey map[string]*dynamodb.AttributeValue) (*string, gomerr.Gomerr) {\n\tif lastEvaluatedKey == nil {\n\t\treturn nil, nil\n\t}\n\n\tnt := &nextToken{\n\t\tVersion: formatVersion,\n\t\tFilter: nil, // TODO\n\t\tLastEvaluatedKey: encodeLastEvaluatedKey(lastEvaluatedKey),\n\t\tExpiration: expirationTime(),\n\t}\n\n\ttoEncrypt, err := json.Marshal(nt)\n\tif err != nil {\n\t\treturn nil, gomerr.Marshal(NextPageToken, nt).Wrap(err)\n\t}\n\n\t// TODO: provide an encryption context - probably w/ q data\n\tencrypted, ge := t.cipher.Encrypt(toEncrypt, nil)\n\tif ge != nil {\n\t\treturn nil, ge\n\t}\n\n\tencoded := base64.RawURLEncoding.EncodeToString(encrypted)\n\treturn &encoded, nil\n}", "func Lexer(tokens []token) []expression {\n\tvar expressions []expression\n\n\tp := parser{\n\t\ttokens: tokens,\n\t\tpos: 0,\n\t}\n\n\tfor !p.done() {\n\t\texpressions = append(expressions, p.expression())\n\t}\n\n\treturn expressions\n}", "func tokenize(chars string) []string {\r\n s := strings.Replace(chars, \"(\", \" ( \", -1)\r\n s = strings.Replace(s, \")\", \" ) \", -1)\r\n s = strings.TrimSpace(s)\r\n return regexp.MustCompile(\"\\\\s+\").Split(s, -1)\r\n}", "func tokenizeStep2(tokens []Token) []Token {\n\tvar newTokens []Token\n\tfor _, token := range tokens {\n\t\tif token.tokType == Number && strings.HasSuffix(token.value, \".\") {\n\t\t\tsplitTokens := token.split(uint(len(token.value))-1, Number, Punctuation)\n\t\t\tnewTokens = append(newTokens, splitTokens[:]...)\n\t\t\tcontinue\n\t\t}\n\t\tif token.tokType == Number && strings.HasSuffix(token.value, \",\") {\n\t\t\tsplitTokens := token.split(uint(len(token.value))-1, Number, Punctuation)\n\t\t\tnewTokens = append(newTokens, splitTokens[:]...)\n\t\t\tcontinue\n\t\t}\n\t\tif token.tokType == Punctuation && strings.HasSuffix(token.value, \".\") && strings.Contains(token.value, \"\\\"\") {\n\t\t\tsplitTokens := token.split(uint(len(token.value))-1, Number, Punctuation)\n\t\t\tnewTokens = append(newTokens, splitTokens[:]...)\n\t\t\tcontinue\n\t\t}\n\t\tnewTokens = append(newTokens, token)\n\t}\n\treturn newTokens\n}", "func tokenizer(input string, position int) (token *Token, EOF bool, err error) {\n\tif position > len(input)-1 {\n\t\treturn nil, true, nil\n\t}\n\n\tcurrent_character := input[position : position+1]\n\n\t// Check if val is integer\n\tif intVal, err := strconv.Atoi(current_character); err == nil {\n\t\ttoken := Token{\n\t\t\telem: \"INTEGER\",\n\t\t\tvalInt: intVal,\n\t\t\tnext: position + 1,\n\t\t}\n\t\treturn token, false, nil\n\t}\n\n\t// Check if val is a plus char\n\tif current_character == '+' {\n\t\ttoken := Token{\n\t\t\telem: \"PLUS\",\n\t\t\tvalStr: current_character,\n\t\t\tnext: position + 1,\n\t\t}\n\t\treturn token, false, nil\n\t}\n\n\terr := raiseException(\"Error parsing input\")\n\treturn nil, nil, err\n}", "func tokenize(s string) []string {\n\ttokens := []string{}\n\tr_opMatch := regexp.MustCompile(`\\+|\\-|\\*`)\n\tm_inds := r_opMatch.FindAllStringSubmatchIndex(s, -1)\n\t// if no ops, just return the string\n\tif len(m_inds) == 0 {\n\t\treturn []string{s}\n\t}\n\t// for each theres a symbol and hex/num after it\n\tl := 0\n\tfor i, matchI := range m_inds {\n\t\ti0 := matchI[0]\n\t\ti1 := matchI[1]\n\t\tss := s[l:i0]\n\t\tl = i1\n\t\tif len(ss) != 0 {\n\t\t\ttokens = append(tokens, ss)\n\t\t}\n\t\ttokens = append(tokens, s[i0:i1])\n\t\tif i == len(m_inds)-1 {\n\t\t\ttokens = append(tokens, s[i1:])\n\t\t\tbreak\n\t\t}\n\t\t//tokens = append(tokens, s[i1:m_inds[i+1][0]])\n\t}\n\treturn tokens\n}", "func tokenize(infix string) []interface{} {\n\n\tvar tokens []interface{}\n\n\tvar s string\n\tvar escapeStr string\n\tappendToS := false\n\twantsToEscape := false\n\tnegate := false\n\tignoreCase := len(infix) >= 4 && strings.HasPrefix(infix, \"(?i)\")\n\t// all an input of \"(?i)\" + regex which will make it case insensitive.\n\t// put the infix string to lower case to eliminate differences between cases.\n\tif ignoreCase {\n\t\tinfix = infix[4:] // remove the (?i) on the string\n\t}\n\n\tfor i, r := range infix {\n\n\t\tif wantsToEscape { // there was a backslash escape the character\n\t\t\tescapeStr += string(r)\n\t\t\twantsToEscape = false\n\t\t\tswitch r {\n\t\t\tcase 'd': // \\d\n\t\t\t\ttokens = append(tokens, digitToken{val: `\\d`, negate: negate})\n\t\t\tcase 'w': // \\w\n\t\t\t\ttokens = append(tokens, wordToken{val: `\\w`, negate: negate})\n\t\t\tcase 's':\n\t\t\t\ttokens = append(tokens, spaceToken{val: `\\s`, negate: negate})\n\t\t\tdefault: // it's an escaped character\n\t\t\t\ttokens = append(tokens, characterClassToken{val: string(r), negate: negate, caseInsensitive: ignoreCase})\n\t\t\t}\n\t\t\tnegate = false\n\n\t\t\t// handle implicit concatenation\n\t\t\tatEnd := i == len(infix)-1\n\t\t\tif !atEnd && !isExplicitOperator(infix[i+1]) && !isClosingBracket(infix[i+1]) {\n\t\t\t\tif !isOpeningBracket(r) && r != '|' {\n\t\t\t\t\ttokens = append(tokens, characterClassToken{val: \".\", negate: false})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif r == '\\\\' { // want to escape a character\n\t\t\twantsToEscape = true\n\t\t\tescapeStr = \"\"\n\t\t\tcontinue\n\t\t}\n\n\t\t// if we should invert the match\n\t\tif r == '^' {\n\t\t\tnegate = true\n\t\t\tcontinue\n\t\t}\n\n\t\t// if it's an underscore (and isn't being escaped), add a token that will match any character\n\t\tif r == '_' {\n\t\t\ttokens = append(tokens, anyToken{val: \"_\", negate: negate})\n\n\t\t\t// handle implicit concatenation\n\t\t\tatEnd := i == len(infix)-1\n\t\t\tif !atEnd && !isExplicitOperator(infix[i+1]) && !isClosingBracket(infix[i+1]) {\n\t\t\t\tif !isOpeningBracket(r) && r != '|' {\n\t\t\t\t\ttokens = append(tokens, characterClassToken{val: \".\", negate: false})\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tstartingClass, endingClass := r == '[', r == ']'\n\n\t\t// don't want to append the last element in a token\n\t\tif appendToS && !endingClass {\n\t\t\ts += string(r) // add as a single character of a multi character token\n\t\t} else if !startingClass && !endingClass { // add the single character as a token\n\t\t\ttokens = append(tokens, characterClassToken{string(r), negate, ignoreCase})\n\n\t\t\t// handle implicit concatenation\n\t\t\tatEnd := i == len(infix)-1\n\t\t\tif !atEnd && !isExplicitOperator(infix[i+1]) && !isClosingBracket(infix[i+1]) {\n\t\t\t\tif !isOpeningBracket(r) && r != '|' {\n\t\t\t\t\ttokens = append(tokens, characterClassToken{val: \".\", negate: false})\n\t\t\t\t}\n\t\t\t}\n\t\t\tnegate = false\n\t\t}\n\n\t\tif startingClass { // we're going to start a multi character token\n\t\t\tappendToS = true\n\t\t} else if endingClass { // reached end of character class\n\t\t\ttokens = append(tokens, characterClassToken{val: s, negate: negate}) // add the full string as a single token\n\t\t\tnegate = false\n\n\t\t\tatEnd := i == len(infix)-1\n\t\t\tif !atEnd && !isExplicitOperator(infix[i+1]) {\n\t\t\t\t// only don't add implicit concat if the next character is an explicit operator\n\t\t\t\ttokens = append(tokens, characterClassToken{\".\", false, ignoreCase})\n\t\t\t}\n\n\t\t\ts = \"\"\n\t\t\tappendToS = false // stop building up character class\n\n\t\t}\n\t}\n\n\treturn tokens\n}", "func Tokenize(ctx context.Context, r io.Reader) ([]string, error) {\n\n\tb := bufio.NewReader(r)\n\n\ttokens := []string{}\n\tcurrent := \"\"\n\tcount := 0\n\n\tfor {\n\t\tl, err := b.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tif len(current) > 0 {\n\t\t\t\ttokens = append(tokens, current)\n\t\t\t}\n\t\t\tbreak\n\n\t\t} else if err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tl = strings.TrimSpace(l)\n\t\tif len(l) == 0 {\n\t\t\tif len(current) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcount = 0\n\t\t\ttokens = append(tokens, current)\n\t\t\tcurrent = \"\"\n\t\t\tcontinue\n\t\t}\n\n\t\tsp := \" \"\n\t\tif count == 0 {\n\t\t\tsp = \"\"\n\t\t}\n\t\tcurrent = current + sp + string(l)\n\t\tcount++\n\n\t}\n\n\treturn tokens, nil\n\n}", "func T(c code, text string) *token { return &token{code: c, Text: text} }", "func lexText(l *lexer) (fn lexFn) {\n\tomitSpaces(l)\n\t// reaches the EOF\n\tif l.accept(\";\") {\n\t\treturn nil\n\t}\n\n\tl.acceptRun(_Keywords)\n\tif isKeyword(l.input[l.start:l.pos]) {\n\t\tl.emit(KEYWORD)\n\t\treturn lexText\n\t}\n\tl.forget()\n\n\tif l.accept(_Star) {\n\t\tl.emit(IDENT)\n\t\treturn lexText\n\t}\n\n\t// identifier\n\tif l.peek() == '`' {\n\t\treturn lexIdentLeftQuote\n\t}\n\tvar isQuoted, isOperator, isNumber bool\n\tisQuoted = l.accept(_Quote)\n\tif isQuoted {\n\t\tl.backup()\n\t}\n\n\tisOperator = l.accept(_Operator)\n\tif isOperator {\n\t\tl.backup()\n\t}\n\n\tisNumber = l.accept(_NumberRunes)\n\tif isNumber {\n\t\tl.backup()\n\t}\n\n\tif !isQuoted && !isOperator && !isNumber {\n\t\treturn lexIdent\n\t}\n\n\tif isOperator {\n\t\treturn lexOperator\n\t}\n\n\t// after a valid operator, there should be a valid op value\n\tif isQuoted || isNumber {\n\t\treturn lexOpValue\n\t}\n\n\treturn l.errorf(\"Illegal expression `%s`, start:pos => %d:%d\", l.input[l.start:], l.start, l.pos)\n}", "func tokenize(f string, customVerbs []string) tokens {\n\tvar t tokens\n\n\tsr := strings.NewReader(f)\n\tr := &tokenFormat{bufio.NewReader(sr)}\n\n\tfor {\n\t\ttkn, err := r.nextToken(customVerbs)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn t\n\t\t\t}\n\n\t\t\tpanic(fmt.Sprintf(\"tokenize: %v\", err))\n\t\t}\n\n\t\tt = append(t, tkn)\n\t}\n}", "func mul_initTokenT(varidname string) (TokenT, string) {\n\tswitch varidname {\n\tcase \"EOF\":\n\t\treturn TokenT{idname: varidname, idno: -1}, \"\"\n\tcase \"NEWLINE\":\n\t\treturn TokenT{idname: varidname, idno: 0}, \"\"\n\tcase \"NUMBER\":\n\t\treturn TokenT{idname: varidname, idno: 1}, \"\"\n\tcase \"IDENT\":\n\t\treturn TokenT{idname: varidname, idno: 2}, \"\"\n\tcase \"STRING\":\n\t\treturn TokenT{idname: varidname, idno: 3}, \"\"\n\t// Keywords\n\tcase \"LABEL\":\n\t\treturn TokenT{idname: varidname, idno: 101}, \"LABEL\"\n\tcase \"GOTO\":\n\t\treturn TokenT{idname: varidname, idno: 102}, \"GOTO\"\n\tcase \"PRINT\":\n\t\treturn TokenT{idname: varidname, idno: 103}, \"PRINT\"\n\tcase \"INPUT\":\n\t\treturn TokenT{idname: varidname, idno: 104}, \"INPUT\"\n\tcase \"LET\":\n\t\treturn TokenT{idname: varidname, idno: 105}, \"LET\"\n\tcase \"IF\":\n\t\treturn TokenT{idname: varidname, idno: 106}, \"IF\"\n\tcase \"THEN\":\n\t\treturn TokenT{idname: varidname, idno: 107}, \"THEN\"\n\tcase \"ENDIF\":\n\t\treturn TokenT{idname: varidname, idno: 108}, \"ENDIF\"\n\tcase \"WHILE\":\n\t\treturn TokenT{idname: varidname, idno: 109}, \"WHILE\"\n\tcase \"REPEAT\":\n\t\treturn TokenT{idname: varidname, idno: 110}, \"REPEAT\"\n\tcase \"ENDWHILE\":\n\t\treturn TokenT{idname: varidname, idno: 111}, \"ENDWHILE\"\n\t// Operators\n\tcase \"EQ\":\n\t\treturn TokenT{idname: varidname, idno: 201}, \"\"\n\tcase \"PLUS\":\n\t\treturn TokenT{idname: varidname, idno: 202}, \"\"\n\tcase \"MINUS\":\n\t\treturn TokenT{idname: varidname, idno: 203}, \"\"\n\tcase \"ASTERISK\":\n\t\treturn TokenT{idname: varidname, idno: 204}, \"\"\n\tcase \"SLASH\":\n\t\treturn TokenT{idname: varidname, idno: 205}, \"\"\n\tcase \"EQEQ\":\n\t\treturn TokenT{idname: varidname, idno: 206}, \"\"\n\tcase \"NOTEQ\":\n\t\treturn TokenT{idname: varidname, idno: 207}, \"\"\n\tcase \"LT\":\n\t\treturn TokenT{idname: varidname, idno: 208}, \"\"\n\tcase \"LTEQ\":\n\t\treturn TokenT{idname: varidname, idno: 210}, \"\"\n\tcase \"GT\":\n\t\treturn TokenT{idname: varidname, idno: 211}, \"\"\n\tcase \"GTEQ\":\n\t\treturn TokenT{idname: varidname, idno: -1}, \"\"\n\tdefault:\n\t\treturn TokenT{idname: \"\", idno: -10000}, \"\"\n\t}\n}", "func makeST(delim string, tokens []string) ([]STNode, []string) {\n\tnodes := make([]STNode, 0, len(tokens))\n\tzip := false\n\tdot := false\n\tvar prev *STNode\n\tvar current STNode\n\tnewline := false\n\tprevlength := 0\n\ti := 0\n\n\tfor ; i < len(tokens); i++ {\n\t\tif tokens[i] == TokenDelimiters[delim] { return nodes, tokens[i + 1:] }\n\n\t\tif tokens[i] == \"\\n\" {\n\t\t\tdelimtype := TokenDelimiterTypes[delim]\n\t\t\tif newline && (len(nodes) - prevlength) > 1 &&\n\t\t\t\tdelimtype != STNodeTypeMap && delimtype != STNodeTypeList {\n\t\t\t\tnode := STNode{\n\t\t\t\t\tType: STNodeTypeExpression,\n\t\t\t\t\tChildren: make([]STNode, len(nodes[prevlength:])),\n\t\t\t\t}\n\t\t\t\tcopy(node.Children, nodes[prevlength:])\n\t\t\t\tnodes = nodes[:prevlength]\n\t\t\t\tnodes, prev, zip, dot = appendNode(nodes, node, prev, zip, dot)\n\t\t\t}\n\t\t\tnewline = true\n\t\t\tprevlength = len(nodes)\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrent = STNode{\n\t\t\tHead: tokens[i],\n\t\t\tType: STNodeTypeIdentifier,\n\t\t\tChildren: make([]STNode, 0),\n\t\t}\n\n\t\t// check if current token is a delimiter '[]' or '{}'\n\t\t// parse recursively if so\n\t\tdelimtype, isDelimiter := TokenDelimiterTypes[current.Head]\n\t\tif isDelimiter {\n\t\t\tvar newtokens []string\n\t\t\tcurrent.Type = delimtype\n\t\t\tcurrent.Children, newtokens = makeST(current.Head, tokens[i + 1:])\n\t\t\ti = -1\n\t\t\ttokens = newtokens\n\t\t\tnodes, prev, zip, dot = appendNode(nodes, current, prev, zip, dot)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if current token is an extended literal i.e a string or comment\n\t\tliteraltype, isLiteral := LiteralDelimiterTypes[string(current.Head[0])]\n\t\tif isLiteral {\n\t\t\tif literaltype == STNodeTypeComment { continue }\n\t\t\tif literaltype == STNodeTypeStringLiteral {\n\t\t\t\tcurrent.Head = fmt.Sprintf(\"\\\"%s\\\"\", normalizeString(current.Head[1:len(current.Head) - 1]))\n\t\t\t}\n\t\t\tcurrent.Type = literaltype\n\t\t\tnodes, prev, zip, dot = appendNode(nodes, current, prev, zip, dot)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if current token is a number literal\n\t\tnum, err := strconv.ParseFloat(current.Head, 64)\n\t\tif err == nil {\n\t\t\tcurrent.Type = STNodeTypeNumberLiteral\n\t\t\tif float64(int(num)) == num {\n\t\t\t\tcurrent.Head = strconv.Itoa(int(num))\n\t\t\t} else { current.Head = fmt.Sprintf(\"%g\", num) }\n\t\t\tnodes, prev, zip, dot = appendNode(nodes, current, prev, zip, dot)\n\t\t\tcontinue\n\t\t}\n\n\t\t// check if current token is an operator\n\t\toptype, isOperator := OperatorTypes[current.Head]\n\t\tif isOperator && len(nodes) > 0 {\n\t\t\tswitch optype {\n\t\t\tcase OperatorTypeSpread: prev.Spread = true\n\t\t\tcase OperatorTypeZip: zip = true\n\t\t\tcase OperatorTypeDot: dot = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// current token must be an identifier\n\t\tnodes, prev, zip, dot = appendNode(nodes, current, prev, zip, dot)\n\t}\n\n\treturn nodes, tokens[i:]\n}", "func (t *Tokeniser) token(typ Type) Token {\n\tvar literalVal interface{}\n\tswitch typ {\n\tcase INT:\n\t\ti, err := strconv.ParseInt(t.Input[t.start:t.pos], 0, 64)\n\t\tif err != nil {\n\t\t\tlogi.Get().Warn(\"integer parse err\", \"err\", err.Error(), \"line\", t.line, \"col\", t.col)\n\t\t} else {\n\t\t\tliteralVal = i\n\t\t}\n\tcase FLOAT:\n\t\ti, err := strconv.ParseFloat(t.Input[t.start:t.pos], 64)\n\t\tif err != nil {\n\t\t\tlogi.Get().Warn(\"float parse err\", \"err\", err.Error(), \"line\", t.line, \"col\", t.col)\n\t\t} else {\n\t\t\tliteralVal = i\n\t\t}\n\tcase STR:\n\t\tliteralVal = t.Input[t.start:t.pos]\n\tcase FALSE:\n\t\tliteralVal = false\n\tcase TRUE:\n\t\tliteralVal = true\n\t}\n\treturn Token{\n\t\tType: typ,\n\t\tLiteral: literalVal,\n\t\tStringValue: t.Input[t.start:t.pos],\n\t\tLine: t.prevLine,\n\t\tCol: t.prevCol,\n\t\tOffset: t.start,\n\t\tWidth: t.pos - t.start,\n\t}\n}", "func Tokenise(lexer Lexer, options *TokeniseOptions, text string) ([]Token, error) {\n\tvar out []Token\n\tit, err := lexer.Tokenise(options, text)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor t := it(); t != EOF; t = it() {\n\t\tout = append(out, t)\n\t}\n\treturn out, nil\n}", "func Tokenize(filename string, src []byte, err ErrorHandler, mode uint, f func(pos token.Position, tok token.Token, lit []byte) bool) int {\n\tvar s Scanner;\n\ts.Init(filename, src, err, mode);\n\tfor f(s.Scan()) {\n\t\t// action happens in f\n\t}\n\treturn s.ErrorCount;\n}", "func Tokenize(s string) []string {\n\tre := regexp.MustCompile(\"\\\\s+\")\n\treturn re.Split(s, -1)\n}", "func execTokenString(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := scanner.TokenString(args[0].(rune))\n\tp.Ret(1, ret)\n}", "func InitTokens(args []string) schema.TokenList {\n\ttokenList := make(schema.TokenList, len(args))\n\tfor i, arg := range args {\n\t\tcontextFreeTType := parseArgument(arg)\n\t\tvar tokenType schema.TokenType = contextFreeTType\n\t\ttoken := schema.NewToken(i, tokenType, arg, tokenList)\n\t\ttokenList[i] = token\n\t\ttoken.AttemptConvertToSemantic()\n\t}\n\treturn tokenList\n}", "func LexExpression(src string) ([]*Token, int, *ExprError) {\n\tl := NewExprLexer(src)\n\tts := []*Token{}\n\tfor {\n\t\tt := l.Next()\n\t\tif l.lexErr != nil {\n\t\t\treturn nil, l.scan.Pos().Offset, l.lexErr\n\t\t}\n\t\tts = append(ts, t)\n\t\tif t.Kind == TokenKindEnd {\n\t\t\treturn ts, l.scan.Pos().Offset, nil\n\t\t}\n\t}\n}", "func token(t string) Parser {\r\n\treturn func(code string) (string, error) {\r\n\t\tcode = stripWhitespaceLeft(code)\r\n\t\tif !strings.HasPrefix(code, t) {\r\n\t\t\treturn code, &ParseError{Message: \"Couldn't match token '\" + t + \"'\"}\r\n\t\t}\r\n\r\n\t\treturn code[len(t):], nil\r\n\t}\r\n}", "func tokenize(s string) []string {\n\treturn strings.Split(strings.TrimSpace(s), \" \")\n}", "func (dialect *Dialect) Split(line string) (tokens []string) {\n\ttokens = make([]string, 0, 8)\n\n\tvar token []rune\n\tvar state = []rune{' '}\n\n\tfor r, w := utf8.DecodeRuneInString(line); 0 != w; {\n\t\tline = line[w:]\n\t\tr0, w0 := utf8.DecodeRuneInString(line)\n\n\t\ts := state[len(state)-1]\n\t\tvar e rune\n\t\tif 0 != w0 {\n\t\t\te = dialect.Escape(s, r, r0)\n\t\t} else {\n\t\t\te = dialect.Escape(s, r, EmptyRune)\n\t\t}\n\t\tif NoEscape != e {\n\t\t\tif 0 != w0 {\n\t\t\t\tline = line[w0:]\n\t\t\t\tr0, w0 = utf8.DecodeRuneInString(line)\n\t\t\t}\n\t\t\tif EmptyRune == e {\n\t\t\t\tr, w = r0, w0\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tswitch s {\n\t\tcase Space:\n\t\t\tswitch {\n\t\t\tcase NoEscape != e:\n\t\t\t\tstate = append(state, Word)\n\t\t\t\ttoken = append(token, e)\n\t\t\tcase dialect.IsQuote(r):\n\t\t\t\tstate = append(state, Word, r)\n\t\t\t\ttoken = make([]rune, 0)\n\t\t\tcase !dialect.IsSpace(r):\n\t\t\t\tstate = append(state, Word)\n\t\t\t\ttoken = append(token, r)\n\t\t\t}\n\t\tcase Word:\n\t\t\tswitch {\n\t\t\tcase NoEscape != e:\n\t\t\t\ttoken = append(token, e)\n\t\t\tcase dialect.IsQuote(r):\n\t\t\t\tstate = append(state, r)\n\t\t\tcase dialect.IsSpace(r):\n\t\t\t\tstate = state[:len(state)-1]\n\t\t\t\ttokens = append(tokens, string(token))\n\t\t\t\ttoken = nil\n\t\t\tdefault:\n\t\t\t\ttoken = append(token, r)\n\t\t\t}\n\t\tdefault: // quote\n\t\t\tswitch {\n\t\t\tcase NoEscape != e:\n\t\t\t\ttoken = append(token, e)\n\t\t\tcase s == r:\n\t\t\t\tstate = state[:len(state)-1]\n\t\t\tdefault:\n\t\t\t\ttoken = append(token, r)\n\t\t\t}\n\t\t}\n\n\t\tif NoEscape == e && nil != dialect.LongEscape {\n\t\t\tif er, line1, r1, w1 := dialect.LongEscape(s, r, line); nil != er {\n\t\t\t\ttoken = append(token, er...)\n\t\t\t\tline = line1\n\t\t\t\tr0 = r1\n\t\t\t\tw0 = w1\n\t\t\t}\n\t\t}\n\n\t\tr, w = r0, w0\n\t}\n\n\tif nil != token {\n\t\ttokens = append(tokens, string(token))\n\t}\n\n\treturn\n}", "func Tokens(tmpl []byte) [][][]byte {\n\treturn keyRegExp.FindAllSubmatch(tmpl, -1)\n}", "func tokenize(s string) []string {\n\ts = comment.ReplaceAllString(s, \"\")\n\tvar result []string\n\tfor _, t := range tokenizer.Split(s, -1) {\n\t\tif t == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, t)\n\t}\n\treturn result\n}", "func Tokens(sql string) (tokens []TokenString, ok bool) {\n\ts := makeScanner(sql)\n\tfor {\n\t\tvar lval sqlSymType\n\t\ts.scan(&lval)\n\t\tif lval.id == ERROR {\n\t\t\treturn nil, false\n\t\t}\n\t\tif lval.id == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttokens = append(tokens, TokenString{TokenID: lval.id, Str: lval.str})\n\t}\n\treturn tokens, true\n}", "func (engine *Engine) Tokens(request types.SearchReq) (tokens []string) {\n\t// 收集关键词\n\t// tokens := []string{}\n\tif request.Text != \"\" {\n\t\trequest.Text = strings.ToLower(request.Text)\n\t\tif engine.initOptions.NotUseGse {\n\t\t\ttokens = strings.Split(request.Text, \" \")\n\t\t} else {\n\t\t\t// querySegments := engine.segmenter.Segment([]byte(request.Text))\n\t\t\t// tokens = engine.Tokens([]byte(request.Text))\n\t\t\ttokens = engine.Segment(request.Text)\n\t\t}\n\n\t\t// 叠加 tokens\n\t\tfor _, t := range request.Tokens {\n\t\t\ttokens = append(tokens, t)\n\t\t}\n\n\t\treturn\n\t}\n\n\tfor _, t := range request.Tokens {\n\t\ttokens = append(tokens, t)\n\t}\n\treturn\n}", "func (fl *FunctionLiteral) TokenLiteral() token.Token { return fl.Token }", "func tokenize(path string) *list.List {\n\n\t// Creates the list.\n\tl := list.New()\n\tfor _, tok := range strings.Split(path, \"/\") {\n\t\tl.PushBack(tok)\n\t}\n\treturn l\n}", "func (wp Wordpiece) Tokenize(text string) []string {\n\t// TODO: determine if utf8 conversion is necessary, per python impl\n\t// text = convert_to_unicode(text)\n\tvar toks []string\n\tfor _, tok := range tokenizeWhitespace(text) {\n\t\tif len(tok) > wp.maxWordChars {\n\t\t\ttoks = append(toks, wp.unknownToken)\n\t\t\tcontinue\n\t\t}\n\t\tfor len(tok) > 0 && tok != \"##\" {\n\t\t\tsub := wp.vocab.LongestSubstring(tok)\n\t\t\tif sub == \"\" {\n\t\t\t\ttoks = append(toks, wp.unknownToken)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttoks = append(toks, sub)\n\t\t\ttok = fmt.Sprintf(\"##%s\", tok[len(sub):])\n\t\t}\n\t}\n\treturn toks\n}", "func GetTokens(source string) []*token {\n\tignoreErrors := false\n\tcountIfs := 0\n\n\ti := 0\n\tend := len(source)\n\tvar tokenSlice []*token\n\n\tfor i < end {\n\t\t// skip spaces\n\t\tfor i < end && unicode.IsSpace(rune(source[i])) {\n\t\t\ti++\n\t\t}\n\t\tif i >= end {\n\t\t\treturn tokenSlice\n\t\t}\n\n\t\ttokenType := Unknown\n\t\tstart := i\n\t\tc := source[i]\n\n\t\tif unicode.IsLetter(rune(c)) || c == '_' {\n\t\t\ttokenType, i = getNameOrPrefixedConstant(source, i, start)\n\t\t} else if c == '/' && source[i+1] == '/' { // Find // comments\n\t\t\ti = ignoreDoubleSlashComment(source, i, end)\n\t\t\tcontinue\n\t\t} else if c == '/' && source[i+1] == '*' { // Find /* comments */\n\t\t\ti = findInString(source, i+1, \"*/\")\n\t\t\tcontinue\n\t\t} else if isByteInString(c, \":+-<>&|*=\") {\n\t\t\ttokenType, i = getOperator(source, i)\n\t\t} else if isByteInString(c, \"()[]{}~!?^%;/.,\") {\n\t\t\ttokenType, i = getSyntaxCharacterOrConstant(source, i)\n\t\t} else if isByteInString(source[i], numChars) { // integer\n\t\t\ttokenType, i = getInteger(source, i)\n\t\t} else if c == '\"' {\n\t\t\ttokenType = Constant\n\t\t\ti = getString(source, start, i)\n\t\t} else if c == '\\'' {\n\t\t\ttokenType = Constant\n\t\t\ti = getChar(source, start, i)\n\t\t} else if c == '#' {\n\t\t\ttokenType, i, countIfs, ignoreErrors = getPreProcessor(source, i, start, countIfs)\n\t\t} else if c == '\\\\' {\n\t\t\ti++\n\t\t\tcontinue\n\t\t} else if ignoreErrors {\n\t\t\tfmt.Println(\"Dunno\")\n\t\t} else {\n\t\t\tfmt.Println(\"Error\")\n\t\t}\n\n\t\tif i <= 0 {\n\t\t\tfmt.Println(\"Invalid index, exit\")\n\t\t\treturn tokenSlice\n\t\t}\n\n\t\t//fmt.Println(token{tokenType, string(source[start:i]), start, i})\n\t\ttokenSlice = append(tokenSlice, &token{tokenType, string(source[start:i]), start, i})\n\t}\n\treturn tokenSlice\n}", "func (a *Assembler) parseExpression(pri int, emptyOK bool) (expr, token, error) {\n\tfor {\n\t\ttok, err := a.nextToken()\n\t\tif err != nil {\n\t\t\treturn nil, token{}, err\n\t\t}\n\t\tswitch tok.t {\n\t\tcase ';', '\\n', scanner.EOF:\n\t\t\tif !emptyOK {\n\t\t\t\treturn nil, token{}, a.scanErrorf(\"unexpected %s\", tok)\n\t\t\t}\n\t\t\treturn nil, tok, nil\n\t\tcase '-', '^', '!':\n\t\t\top := tok.t\n\t\t\tx, tok, err := a.parseExpression(precUnary, false)\n\t\t\treturn a.continueExpr(pri, exprUnaryOp{op, x}, tok, err)\n\t\tcase '(':\n\t\t\tex, tok, err := a.parseExpression(0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, token{}, err\n\t\t\t}\n\t\t\tif tok.t != ')' {\n\t\t\t\treturn nil, token{}, a.scanErrorf(\"found: %s, expected )\", tok)\n\t\t\t}\n\t\t\tex = exprBracket{ex}\n\t\t\tnt, err := a.nextToken()\n\t\t\treturn a.continueExpr(0, ex, nt, err)\n\t\tcase scanner.Int:\n\t\t\ti, err := strconv.ParseInt(tok.s, 0, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, token{}, a.scanErrorf(\"bad number %q: %v\", tok, err)\n\t\t\t}\n\t\t\tnt, err := a.nextToken()\n\t\t\treturn a.continueExpr(pri, exprInt{i}, nt, err)\n\t\tcase scanner.String, scanner.RawString:\n\t\t\tr, err := strconv.Unquote(tok.s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, token{}, a.scanErrorf(\"bad string %q: %v\", tok.s, err)\n\t\t\t}\n\t\t\tnt, err := a.nextToken()\n\t\t\treturn a.continueExpr(pri, exprString{r}, nt, err)\n\t\tcase scanner.Char:\n\t\t\tr, _, _, err := strconv.UnquoteChar(tok.s[1:], '\\'')\n\t\t\tif err != nil {\n\t\t\t\treturn nil, token{}, a.scanErrorf(\"bad char %q: %v\", tok, err)\n\t\t\t}\n\t\t\tnt, err := a.nextToken()\n\t\t\treturn exprChar{r}, nt, err\n\t\tcase scanner.Ident:\n\t\t\texpr := exprIdent{\n\t\t\t\tid: tok.s,\n\t\t\t\tr: regFromString[tok.s],\n\t\t\t\tcc: ccFromString[tok.s],\n\t\t\t}\n\t\t\tnt, err := a.nextToken()\n\t\t\treturn a.continueExpr(pri, expr, nt, err)\n\t\tdefault:\n\t\t\treturn nil, token{}, a.scanErrorf(\"unexpected token %s\", tok)\n\t\t}\n\t}\n}", "func Tokenize(text string) []Token {\n sanitized := Sanitize(text)\n raw := reSplits.Split(sanitized, -1)\n\n var tagged []tagger.TaggedWord\n if useTagger {\n tagged = crTagger.TagBytes([]byte(sanitized))\n }\n\n var result []Token\n tagCount := 0\n for _, t := range raw {\n if len(t) == 0 {\n continue\n }\n if reSkipwords.MatchString(t) {\n continue\n }\n\n var token Token\n if rePunctuation.MatchString(t) {\n if KeepPunctuation {\n token = Token{Punctuation, t, nil, \"_punc\"}\n } else {\n continue\n }\n } else if reURL.MatchString(t) {\n token = Token{URL, t, nil, \"_link\"}\n } else if strings.HasPrefix(t, \"#\") {\n s := reGenitive.ReplaceAllString(t, \"$1\")\n // TODO more checks on hashtag\n token = Token{Hashtag, s, nil, \"_tag\"}\n } else if strings.HasPrefix(t, \"$\") {\n token = Token{Cashtag, t, nil, \"_cash\"}\n } else if strings.HasPrefix(t, \"@\") {\n // TODO more checks on username\n token = Token{User, t, nil, \"_user\"}\n } else if strings.HasPrefix(t, \"/photo\") {\n token = Token{Photo, t, nil, \"_photo\"}\n } else if strings.HasPrefix(t, \"RT\") {\n token = Token{Retweet, t, nil, \"_rt\"}\n } else if strings.HasPrefix(t, \"via\") {\n token = Token{Via, t, nil, \"_via\"}\n } else if strings.HasPrefix(t, \"cc\") {\n token = Token{CC, t, nil, \"_cc\"}\n } else {\n emote, err := CheckEmoticon(t)\n if err == nil {\n token = Token{Emoticon, t, emote, \"_emoticon\"}\n } else if useTagger {\n stripped := StripPunctuation(t)\n for {\n if tagCount >= len(tagged) {\n tagCount = 0\n break\n }\n\n if tagged[tagCount].GetWord() == stripped {\n token = Token{POS, stripped, nil, tagged[tagCount].GetTag()}\n tagCount = tagCount + 1\n break\n } else {\n tagCount = tagCount + 1\n }\n }\n if tagCount == 0 {\n token = Token{None, t, nil, \"\"}\n }\n } else {\n token = Token{None, t, nil, \"\"}\n }\n }\n\n result = append(result, token)\n }\n\n return result\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.skipWhitespace()\n\tl.skipComment()\n\tl.skipWhitespace()\n\n\tswitch l.ch {\n\tcase '\"':\n\t\tkind, literal := l.readString()\n\t\ttok = l.newToken(kind, literal)\n\tcase '+':\n\t\tif l.peekChar() == '+' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CONCAT, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FPLUS, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CPLUS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.PLUS, string(l.ch))\n\t\t}\n\tcase '-':\n\t\tif l.peekChar() == '>' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.RARROW, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FMINUS, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CMINUS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.MINUS, string(l.ch))\n\t\t}\n\tcase '(':\n\t\ttok = l.newToken(token.LPAREN, string(l.ch))\n\tcase ')':\n\t\ttok = l.newToken(token.RPAREN, string(l.ch))\n\tcase '{':\n\t\ttok = l.newToken(token.LBRACKET, string(l.ch))\n\tcase '}':\n\t\ttok = l.newToken(token.RBRACKET, string(l.ch))\n\tcase '*':\n\t\tif l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FTIMES, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CTIMES, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.TIMES, string(l.ch))\n\t\t}\n\n\tcase '/':\n\t\tif l.peekChar() == '.' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.FDIVIDE, string(ch)+string(l.ch))\n\t\t} else if l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CDIVIDE, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.DIVIDE, string(l.ch))\n\t\t}\n\n\tcase '^':\n\t\ttok = l.newToken(token.TOPOW, string(l.ch))\n\tcase '=':\n\t\ttok = l.newToken(token.EQUALS, string(l.ch))\n\tcase '%':\n\t\ttok = l.newToken(token.MODULO, string(l.ch))\n\tcase '@':\n\t\ttok = l.newToken(token.AT, string(l.ch))\n\tcase '.':\n\t\ttok = l.newToken(token.ACCESS, string(l.ch))\n\tcase ',':\n\t\ttok = l.newToken(token.COMMA, string(l.ch))\n\tcase '$':\n\t\ttok = l.newToken(token.DOLLAR, string(l.ch))\n\tcase '!':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.DIFFERS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.NOT, string(l.ch))\n\t\t}\n\tcase '&':\n\t\tif l.peekChar() == '&' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.LAND, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.ILLEGAL, string(l.ch))\n\t\t}\n\tcase '|':\n\t\tif l.peekChar() == '|' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.OR, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.ILLEGAL, string(l.ch))\n\t\t}\n\tcase ':':\n\t\tif l.peekChar() == ':' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.CONS, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.ANNOT, string(l.ch))\n\t\t}\n\tcase '<':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\tif l.peekChar() == '<' {\n\t\t\t\tch2 := l.ch\n\t\t\t\tl.readChar()\n\t\t\t\ttok = l.newToken(token.COMPOSE, string(ch)+string(ch2)+string(l.ch))\n\t\t\t} else {\n\t\t\t\ttok = l.newToken(token.LESSEQ, string(ch)+string(l.ch))\n\t\t\t}\n\t\t} else {\n\t\t\ttok = l.newToken(token.LESS, string(l.ch))\n\n\t\t}\n\tcase '>':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\tif l.peekChar() == '>' {\n\t\t\t\tch2 := l.ch\n\t\t\t\tl.readChar()\n\t\t\t\ttok = l.newToken(token.PIPE, string(ch)+string(ch2)+string(l.ch))\n\t\t\t} else {\n\t\t\t\ttok = l.newToken(token.GREATEREQ, string(ch)+string(l.ch))\n\t\t\t}\n\t\t} else if l.peekChar() == '>' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = l.newToken(token.SEQUENCE, string(ch)+string(l.ch))\n\t\t} else {\n\t\t\ttok = l.newToken(token.GREATER, string(l.ch))\n\n\t\t}\n\tcase ';':\n\t\ttok = l.newToken(token.SEMI, string(l.ch))\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\n\t// Now the next token must either be and identifier, a number\n\t// Or an invalid token\n\tdefault:\n\t\tif isIdentifier(l.ch) {\n\t\t\tlit := l.readIdentifier()\n\t\t\ttok = l.newToken(token.LookupIdent(lit), lit)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\tkind, value := l.readNumber(false)\n\t\t\ttok = l.newToken(kind, value)\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = l.newToken(token.ILLEGAL, string(l.ch))\n\t\t}\n\t}\n\n\t// Advance by a character\n\tl.readChar()\n\treturn tok\n}", "func (lexer *Lexer) NextToken() token.Token {\n\tvar t token.Token\n\n\tlexer.skipWhitespace()\n\n\tswitch lexer.currentChar {\n\n\t// One-character bytes\n\tcase '(':\n\t\tt = newToken(token.LPAREN, lexer.currentChar)\n\tcase ')':\n\t\tt = newToken(token.RPAREN, lexer.currentChar)\n\tcase ',':\n\t\tt = newToken(token.COMMA, lexer.currentChar)\n\tcase '+':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.PLUSEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tcase '+':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.INCREMENT,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.MINUS, lexer.currentChar)\n\t\t}\n\tcase '{':\n\t\tt = newToken(token.LBRACE, lexer.currentChar)\n\tcase '}':\n\t\tt = newToken(token.RBRACE, lexer.currentChar)\n\tcase '[':\n\t\tt = newToken(token.LBRACKET, lexer.currentChar)\n\tcase ']':\n\t\tt = newToken(token.RBRACKET, lexer.currentChar)\n\tcase '-':\n\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '>':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.OPENBLOCK,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.MINUSEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tcase '-':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.DECREMENT,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.MINUS, lexer.currentChar)\n\n\t\t}\n\n\tcase '/':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.SLASHEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.SLASH, lexer.currentChar)\n\t\t}\n\tcase '*':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '=':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{Type: token.MULEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar)}\n\t\tdefault:\n\t\t\tt = newToken(token.ASTERISK, lexer.currentChar)\n\t\t}\n\tcase '<':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.LTEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.LT, lexer.currentChar)\n\t\t}\n\tcase '>':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.GTEQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.GTEQ, lexer.currentChar)\n\t\t}\n\tcase ';':\n\t\tt = newToken(token.SEMICOLON, lexer.currentChar)\n\tcase ':':\n\t\tt = newToken(token.COLON, lexer.currentChar)\n\n\tcase '#':\n\t\tfor lexer.peekCharacter() != '\\n' && lexer.peekCharacter() != 0 {\n\t\t\tlexer.consumeChar()\n\t\t}\n\t\tlexer.skipWhitespace()\n\t\tlexer.consumeChar()\n\t\treturn lexer.NextToken()\n\n\t// EOF\n\tcase 0:\n\t\tt.Literal = \"\"\n\t\tt.Type = token.EOF\n\n\t// Multiple-character bytes\n\tcase '=':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.EQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.ASSIGN, lexer.currentChar)\n\t\t}\n\tcase '!':\n\t\tif lexer.peekCharacter() == '=' {\n\t\t\tcharacter := lexer.currentChar\n\n\t\t\tlexer.consumeChar()\n\t\t\tt = token.Token{\n\t\t\t\tType: token.NOT_EQ,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\t} else {\n\t\t\tt = newToken(token.BANG, lexer.currentChar)\n\t\t}\n\n\tcase '|':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '|':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.OR,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\tdefault:\n\t\t\tt = newToken(token.ILLEGAL, lexer.currentChar)\n\n\t\t}\n\n\tcase '&':\n\t\tswitch lexer.peekCharacter() {\n\t\tcase '&':\n\t\t\tcharacter := lexer.currentChar\n\t\t\tlexer.consumeChar()\n\n\t\t\tt = token.Token{\n\t\t\t\tType: token.AND,\n\t\t\t\tLiteral: string(character) + string(lexer.currentChar),\n\t\t\t}\n\t\tdefault:\n\t\t\tt = newToken(token.ILLEGAL, lexer.currentChar)\n\n\t\t}\n\n\tcase '\"':\n\t\tt.Type = token.STRING\n\t\tt.Literal = lexer.readString()\n\n\tdefault:\n\t\tif util.IsLetter(lexer.currentChar) {\n\t\t\tt.Literal = lexer.consumeIdentifier()\n\t\t\tt.Type = token.LookupIdent(t.Literal)\n\t\t\treturn t\n\t\t} else if util.IsDigit(lexer.currentChar) {\n\t\t\tt.Literal = lexer.consumeInteger()\n\t\t\tt.Type = token.INT\n\t\t\treturn t\n\t\t} else {\n\t\t\tt = newToken(token.ILLEGAL, lexer.currentChar)\n\t\t}\n\t}\n\tlexer.consumeChar()\n\n\treturn t\n}", "func (tokenizer DictTokenizer[V]) Tokenize(text string) []TextToken {\n\ttokens := []TextToken{}\n\tsegments := Segment(text)\n\tfor _, segment := range segments {\n\t\tif segment.Chinese {\n\t\t\ttokens1 := tokenizer.greedyLtoR(segment.Text)\n\t\t\ttokens2 := tokenizer.greedyRtoL(segment.Text)\n\t\t\tif len(tokens2) < len(tokens1) {\n\t\t\t\ttokens = append(tokens, tokens2...)\n\t\t\t} else {\n\t\t\t\ttokens = append(tokens, tokens1...)\n\t\t\t}\n\t\t} else {\n\t\t\ttoken := TextToken{\n\t\t\t\tToken: segment.Text,\n\t\t\t}\n\t\t\ttokens = append(tokens, token)\n\t\t}\n\t}\n\treturn tokens\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.scanIgnoreWhiteSpace()\n\n\tswitch l.ch {\n\tcase '(':\n\t\ttok = newToken(token.LPAREN, l.ch)\n\tcase ')':\n\t\ttok = newToken(token.RPAREN, l.ch)\n\tcase ';':\n\t\tif l.peekChar() == ';' {\n\t\t\tch := l.ch\n\t\t\tl.scan()\n\t\t\tlit := string(ch) + string(l.ch)\n\t\t\ttok = token.Token{Type: token.EOI, Literal: lit}\n\t\t} else {\n\t\t\ttok = newToken(token.SEMICOLON, l.ch)\n\t\t}\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\tcase '+':\n\t\ttok = newToken(token.PLUS, l.ch)\n\tcase '-':\n\t\ttok = newToken(token.MINUS, l.ch)\n\tcase '*':\n\t\ttok = newToken(token.ASTERISK, l.ch)\n\tcase '/':\n\t\ttok = newToken(token.SLASH, l.ch)\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.ScanIdent()\n\t\t\ttok.Type = token.LookupIdent(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Literal = l.scanNumber()\n\t\t\tif strings.Contains(tok.Literal, \".\") {\n\t\t\t\ttok.Type = token.FLOAT_NUM\n\t\t\t} else {\n\t\t\t\ttok.Type = token.INT\n\t\t\t}\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(token.ILLEGAL, l.ch)\n\t\t}\n\n\t}\n\n\tl.scan()\n\treturn tok\n\n}", "func NewTokens(program string) Tokens {\n\ttks := toTokens(splitSpaces(expand(program)))\n\treturn tks\n}", "func token(name string) lex.Action {\n\treturn func(s *lex.Scanner, m *machines.Match) (interface{}, error) {\n\t\treturn s.Token(TokenIds[name], string(m.Bytes), m), nil\n\t}\n}", "func token(name string) lex.Action {\n\treturn func(s *lex.Scanner, m *machines.Match) (interface{}, error) {\n\t\treturn s.Token(TokenIds[name], string(m.Bytes), m), nil\n\t}\n}", "func (t *infixTokenizer) splitSingleTokenBySingleOperator(tokenValue string, operator string) []token {\n\tresult := make([]token, 0)\n\n\tfor start := 0; start < len(tokenValue); {\n\t\tif end := strings.Index(tokenValue[start:], operator); end == -1 {\n\t\t\tnewValue := tokenValue[start:]\n\t\t\tnewType := t.tokenTypeByValue(newValue)\n\t\t\tresult = append(result, token{newType, newValue})\n\t\t\tbreak\n\t\t} else {\n\t\t\tif end != start {\n\t\t\t\tnewValue := tokenValue[start:end]\n\t\t\t\tnewType := t.tokenTypeByValue(newValue)\n\t\t\t\tresult = append(result, token{newType, newValue})\n\t\t\t}\n\t\t\tnewValue := tokenValue[end : end+len(operator)]\n\t\t\tresult = append(result, token{operatorType, newValue})\n\t\t\tstart = end + len(operator)\n\t\t}\n\t}\n\n\treturn result\n}", "func tokenList(s *scanner.Scanner) []*token {\n\ttokens := []*token{}\n\tfor {\n\t\ttok := s.Scan()\n\t\tif tok == scanner.EOF {\n\t\t\tbreak\n\t\t}\n\t\ttokens = append(tokens, &token{\n\t\t\ttok: tok,\n\t\t\ttext: s.TokenText(),\n\t\t\tLine: s.Position.Line,\n\t\t\tColumn: s.Position.Column,\n\t\t})\n\t}\n\treturn tokens\n}", "func (rd *BertPreTokenizer) PreTokenize(\n\tns *normalizedstring.NormalizedString,\n) ([]pretokenizers.PreToken, error) {\n\ttokens := make([]pretokenizers.PreToken, 0)\n\tword := make([]rune, 0)\n\n\tindex := 0\n\tfor _, r := range ns.Get() {\n\t\tswitch {\n\t\tcase unicode.In(r, unicode.White_Space):\n\t\t\tif len(word) > 0 {\n\t\t\t\ttokens = append(tokens, pretokenizers.PreToken{\n\t\t\t\t\tString: string(word),\n\t\t\t\t\tStart: index - len(word),\n\t\t\t\t\tEnd: index,\n\t\t\t\t})\n\t\t\t\tword = word[:0]\n\t\t\t}\n\t\tcase unicode.In(r, unicode.Punct):\n\t\t\tif len(word) > 0 {\n\t\t\t\ttokens = append(tokens, pretokenizers.PreToken{\n\t\t\t\t\tString: string(word),\n\t\t\t\t\tStart: index - len(word),\n\t\t\t\t\tEnd: index,\n\t\t\t\t})\n\t\t\t\tword = word[:0]\n\t\t\t}\n\t\t\ttokens = append(tokens, pretokenizers.PreToken{\n\t\t\t\tString: string(r),\n\t\t\t\tStart: index,\n\t\t\t\tEnd: index + 1,\n\t\t\t})\n\t\tdefault:\n\t\t\tword = append(word, r)\n\t\t}\n\n\t\tindex++\n\t}\n\n\tif len(word) > 0 {\n\t\tend := ns.Len()\n\t\ttokens = append(tokens, pretokenizers.PreToken{\n\t\t\tString: string(word),\n\t\t\tStart: end - len(word),\n\t\t\tEnd: end,\n\t\t})\n\t}\n\n\treturn tokens, nil\n}", "func TestNextToken(t *testing.T) {\n\tinput := `đặt năm = 5;\nđặt mười = 10;\n\nđặt cộng = hàm(x, y) {\n x + y;\n};\n\nđặt result = cộng(năm, mười);\n!-*/5;\n5 < 10 > 5;\n\nnếu (5 < 10) {\n\ttrả_về đúng;\n} ngược_lại {\n\ttrả_về sai;\n}\n\n10 == 10;\n10 != 9;\n\"foobar\"\n\"foo bar\"\n[1, 2];\n{\"foo\": \"bar\"}\n3.14\n`\n\n\ttests := []struct {\n\t\texpectedType token.TokenType\n\t\texpectedLiteral string\n\t}{\n\t\t{token.LET, \"đặt\"},\n\t\t{token.IDENT, \"năm\"},\n\t\t{token.ASSIGN, \"=\"},\n\t\t{token.INT, \"5\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.LET, \"đặt\"},\n\t\t{token.IDENT, \"mười\"},\n\t\t{token.ASSIGN, \"=\"},\n\t\t{token.INT, \"10\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.LET, \"đặt\"},\n\t\t{token.IDENT, \"cộng\"},\n\t\t{token.ASSIGN, \"=\"},\n\t\t{token.FUNCTION, \"hàm\"},\n\t\t{token.LPAREN, \"(\"},\n\t\t{token.IDENT, \"x\"},\n\t\t{token.COMMA, \",\"},\n\t\t{token.IDENT, \"y\"},\n\t\t{token.RPAREN, \")\"},\n\t\t{token.LBRACE, \"{\"},\n\t\t{token.IDENT, \"x\"},\n\t\t{token.PLUS, \"+\"},\n\t\t{token.IDENT, \"y\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.RBRACE, \"}\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.LET, \"đặt\"},\n\t\t{token.IDENT, \"result\"},\n\t\t{token.ASSIGN, \"=\"},\n\t\t{token.IDENT, \"cộng\"},\n\t\t{token.LPAREN, \"(\"},\n\t\t{token.IDENT, \"năm\"},\n\t\t{token.COMMA, \",\"},\n\t\t{token.IDENT, \"mười\"},\n\t\t{token.RPAREN, \")\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.BANG, \"!\"},\n\t\t{token.MINUS, \"-\"},\n\t\t{token.ASTERISK, \"*\"},\n\t\t{token.SLASH, \"/\"},\n\t\t{token.INT, \"5\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.INT, \"5\"},\n\t\t{token.LT, \"<\"},\n\t\t{token.INT, \"10\"},\n\t\t{token.GT, \">\"},\n\t\t{token.INT, \"5\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.IF, \"nếu\"},\n\t\t{token.LPAREN, \"(\"},\n\t\t{token.INT, \"5\"},\n\t\t{token.LT, \"<\"},\n\t\t{token.INT, \"10\"},\n\t\t{token.RPAREN, \")\"},\n\t\t{token.LBRACE, \"{\"},\n\t\t{token.RETURN, \"trả_về\"},\n\t\t{token.TRUE, \"đúng\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.RBRACE, \"}\"},\n\t\t{token.ELSE, \"ngược_lại\"},\n\t\t{token.LBRACE, \"{\"},\n\t\t{token.RETURN, \"trả_về\"},\n\t\t{token.FALSE, \"sai\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.RBRACE, \"}\"},\n\t\t{token.INT, \"10\"},\n\t\t{token.EQ, \"==\"},\n\t\t{token.INT, \"10\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.INT, \"10\"},\n\t\t{token.NOT_EQ, \"!=\"},\n\t\t{token.INT, \"9\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.STRING, \"foobar\"},\n\t\t{token.STRING, \"foo bar\"},\n\t\t{token.LBRACKET, \"[\"},\n\t\t{token.INT, \"1\"},\n\t\t{token.COMMA, \",\"},\n\t\t{token.INT, \"2\"},\n\t\t{token.RBRACKET, \"]\"},\n\t\t{token.SEMICOLON, \";\"},\n\t\t{token.LBRACE, \"{\"},\n\t\t{token.STRING, \"foo\"},\n\t\t{token.COLON, \":\"},\n\t\t{token.STRING, \"bar\"},\n\t\t{token.RBRACE, \"}\"},\n\t\t{token.FLOAT, \"3.14\"},\n\t\t{token.EOF, \"\"},\n\t}\n\n\tl := New(strings.NewReader(input), \"test\")\n\n\tvar tok token.Token\n\tfor i, tt := range tests {\n\t\tfor {\n\t\t\ttok = l.NextToken()\n\t\t\tif tok.Type != token.NEWLINE {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"*** %q *** \\n\", tok.Type)\n\t\tif tok.Type != tt.expectedType {\n\t\t\tt.Fatalf(\"tests[%d] - tokentype wrong. expected=%q, got=%q\",\n\t\t\t\ti, tt.expectedType, tok.Type)\n\t\t}\n\n\t\tif tok.Literal != tt.expectedLiteral {\n\t\t\tt.Fatalf(\"tests[%d] - literal wrong. expected=%q, got=%q\",\n\t\t\t\ti, tt.expectedLiteral, tok.Literal)\n\t\t}\n\t}\n}", "func New(l *lexer.Lexer) *Parser {\n\tp := &Parser{l: l}\n\tp.readNextToken()\n\tp.readNextToken() // To set the init value of curToken and the nextToken.\n\tp.ParseFnForPrefixToken = make(map[string]prefixTokenParseFn) // Need to assign a non-nil map, otherwise cannot assign to a nil nap.\n\tp.registerParseFuncForPrefixToken(token.IDENTIFIER, p.parseIdentifier)\n\tp.registerParseFuncForPrefixToken(token.INT, p.parseIntegerLiteral)\n\tp.registerParseFuncForPrefixToken(token.STRING, p.parseStringLiteral)\n\tp.registerParseFuncForPrefixToken(token.BANG, p.parsePrefixExpression)\n\tp.registerParseFuncForPrefixToken(token.MINUS, p.parsePrefixExpression)\n\tp.registerParseFuncForPrefixToken(token.TRUE, p.parseBooleanLiteral)\n\tp.registerParseFuncForPrefixToken(token.FALSE, p.parseBooleanLiteral)\n\tp.registerParseFuncForPrefixToken(token.LPAREN, p.parseGroupedExpression)\n\tp.registerParseFuncForPrefixToken(token.IF, p.parseIfExpression)\n\tp.registerParseFuncForPrefixToken(token.FUNCTION, p.parseFunctionLiteralExpression)\n\tp.ParseFnForInfixToken = make(map[string]infixTokenParseFn)\n\tp.registerParseFuncForInfixToken(token.PLUS, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.MINUS, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.ASTERISK, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.LT, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.GT, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.EQ, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.NOTEQ, p.parseInfixExpression)\n\tp.registerParseFuncForInfixToken(token.LPAREN, p.parseCallExpression)\n\tp.registerParseFuncForInfixToken(token.SLASH, p.parseInfixExpression)\n\treturn p\n}", "func lexText(l *Lexer) stateFn {\n\tfor {\n\t\tswitch r := l.next(); {\n\t\tcase r == '\\n':\n\t\t\tLineno++\n\n\t\t\tl.emit(itemEndStatement)\n\t\t\t//l.ignore()\n\t\tcase r == '\\t':\n\t\t\tl.ignore()\n\t\tcase isSpace(r): // Check whether this is a space (which we ignore)\n\t\t\tl.ignore()\n\t\tcase isAlphaNumeric(r) || r == '_': // Check if it's alpha numeric (var, if, else etc)\n\t\t\tl.backup()\n\n\t\t\treturn lexStatement\n\t\tcase isNumber(r): // Check if it's a number (constant)\n\t\t\tl.backup()\n\n\t\t\treturn lexNumber\n\t\tcase r == '{': // Block check\n\t\t\tl.emit(itemLeftBrace)\n\t\tcase r == '}':\n\t\t\tl.emit(itemRightBrace)\n\t\tcase r == '[':\n\t\t\tl.emit(itemLeftBracket)\n\t\tcase r == ']':\n\t\t\tl.emit(itemRightBracket)\n\t\tcase r == '(':\n\t\t\tl.emit(itemLeftPar)\n\t\tcase r == ')':\n\t\t\tl.emit(itemRightPar)\n\t\tcase r == '.':\n\t\t\tl.emit(itemDot)\n\t\tcase r == ',':\n\t\t\tl.emit(itemComma)\n\t\tcase r == '\"':\n\t\t\tl.emit(itemQuote)\n\n\t\t\treturn lexInsideString\n\t\tcase r == '/', r == '#':\n\t\t\treturn lexComment\n\t\tcase r == ';':\n\t\t\tl.emit(itemEndStatement)\n\t\tcase r == ':':\n\t\t\tl.emit(itemColon)\n\t\tcase isOperator(r):\n\t\t\tl.backup()\n\n\t\t\treturn lexOperator\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t *infixTokenizer) splitTokensByOperators(tokens []token) []token {\n\tvar lengths []int\n\tfor length := range t.operatorsByLength {\n\t\tlengths = append(lengths, length)\n\t}\n\tsort.Ints(lengths)\n\n\tresult := tokens\n\n\tfor _, length := range lengths {\n\t\toperatorsOfTheSameLength := t.operatorsByLength[length]\n\t\tfor operatorName := range operatorsOfTheSameLength {\n\t\t\tresult = t.splitTokensBySingleOperator(result, operatorName)\n\t\t}\n\t}\n\n\treturn result\n}", "func Tokenize(instrArr []string, labelMap map[string]int) ([][]string, error) {\n\t// Map instructions\n\tasm := make([][]string, len(instrArr))\n\tfor i, instr := range instrArr {\n\t\t// Get rid of labels and whitespace\n\t\tprefixRe := regexp.MustCompile(`^(\\s*\\w+:)?\\s*`)\n\t\tif indices := prefixRe.FindStringIndex(instr); indices != nil {\n\t\t\tend := indices[1]\n\t\t\tinstr = instr[end:]\n\t\t}\n\n\t\t// Convert instr strings to tokens\n\t\tif len(instr) == 0 {\n\t\t\t// <Label>:\n\t\t\tasm[i] = []string{\"NOP\"}\n\t\t} else if m := regexp.MustCompile(`^#.*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// #<Comment>\n\t\t\tasm[i] = []string{\"NOP\"}\n\t\t} else if m := regexp.MustCompile(`^(NOP|SWP|SAV|NEG)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// NOP|SWP|SAV|NEG\n\t\t\tasm[i] = []string{m[1]}\n\t\t} else if m := regexp.MustCompile(`^MOV\\s+(-?\\d+)\\s*,\\s+(ACC|NIL)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// MOV <VAL>, <DST>\n\t\t\tasm[i] = []string{\"MOV_VAL_LOCAL\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^MOV\\s+(-?\\d+)\\s*,\\s+(\\w+:R[0123])\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// MOV <VAL>, <DST>\n\t\t\tasm[i] = []string{\"MOV_VAL_NETWORK\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^MOV\\s+(ACC|NIL|R[0123])\\s*,\\s+(ACC|NIL)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// MOV <SRC>, <DST>\n\t\t\tasm[i] = []string{\"MOV_SRC_LOCAL\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^MOV\\s+(ACC|NIL|R[0123])\\s*,\\s+(\\w+:R[0123])\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// MOV <SRC>, <DST>\n\t\t\tasm[i] = []string{\"MOV_SRC_NETWORK\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^(ADD|SUB)\\s+(-?\\d+)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// ADD|SUB <VAL>\n\t\t\tasm[i] = []string{fmt.Sprintf(\"%s_VAL\", m[1]), m[2]}\n\t\t} else if m := regexp.MustCompile(`^(ADD|SUB)\\s+(ACC|NIL|R[0123])\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// ADD|SUB <SRC>\n\t\t\tasm[i] = []string{fmt.Sprintf(\"%s_SRC\", m[1]), m[2]}\n\t\t} else if m := regexp.MustCompile(`^(JMP|JEZ|JNZ|JGZ|JLZ)\\s+(\\w+)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// JMP|JEZ|JNZ|JGZ|JLZ <LABEL>\n\t\t\tlabel := strings.ToUpper(m[2])\n\t\t\tif _, ok := labelMap[label]; ok {\n\t\t\t\tasm[i] = []string{m[1], label}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"line %v, label '%s' was not declared\", i, label)\n\t\t\t}\n\t\t} else if m := regexp.MustCompile(`^JRO\\s+(-?\\d+)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// JRO <VAL>\n\t\t\tasm[i] = []string{\"JRO_VAL\", m[1]}\n\t\t} else if m := regexp.MustCompile(`^JRO\\s+(ACC|NIL|R[0123])\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// JRO <SRC>\n\t\t\tasm[i] = []string{\"JRO_SRC\", m[1]}\n\t\t} else if m := regexp.MustCompile(`^PUSH\\s+(-?\\d+)\\s*,\\s+(\\w+)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// PUSH <VAL>, <DST>\n\t\t\tasm[i] = []string{\"PUSH_VAL\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^PUSH\\s+(ACC|NIL|R[0123])\\s*,\\s+(\\w+)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// PUSH <SRC>, <DST>\n\t\t\tasm[i] = []string{\"PUSH_SRC\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^POP\\s+(\\w+)\\s*,\\s+(ACC|NIL)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// POP <SRC>, <DST>\n\t\t\tasm[i] = []string{\"POP\", m[1], m[2]}\n\t\t} else if m := regexp.MustCompile(`^IN\\s+(ACC|NIL)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// IN <DST>\n\t\t\tasm[i] = []string{\"IN\", m[1]}\n\t\t} else if m := regexp.MustCompile(`^OUT\\s+(-?\\d+)\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// OUT <VAL>\n\t\t\tasm[i] = []string{\"OUT_VAL\", m[1]}\n\t\t} else if m := regexp.MustCompile(`^OUT\\s+(ACC|NIL|R[0123])\\s*$`).FindStringSubmatch(instr); len(m) > 0 {\n\t\t\t// OUT <SRC>\n\t\t\tasm[i] = []string{\"OUT_SRC\", m[1]}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"line %v, '%s' not a valid instruction\", i, instr)\n\t\t}\n\t}\n\n\treturn asm, nil\n}", "func (vl *VarLiteral) TokenLiteral() token.Token { return vl.Token }", "func Tokenize(sentence string) []*japanese.Token {\n\tvar tokens []*japanese.Token\n\n\tfor _, token := range globalTokenizer.Tokenize(sentence) {\n\t\t// Ignore start and end of sentence tokens\n\t\tif token.Class == kagome.DUMMY {\n\t\t\tcontinue\n\t\t}\n\n\t\tfeatures := token.Features()\n\t\thiragana := \"\"\n\t\tkatakana := \"\"\n\t\tromaji := \"\"\n\n\t\tif len(features) >= 9 {\n\t\t\tkatakana = features[8]\n\t\t\tromaji = kana.KanaToRomaji(katakana)\n\t\t\thiragana = kana.RomajiToHiragana(romaji)\n\t\t}\n\n\t\t// Create token\n\t\ttoken := &japanese.Token{\n\t\t\tOriginal: token.Surface,\n\t\t\tHiragana: hiragana,\n\t\t\tKatakana: katakana,\n\t\t\tRomaji: romaji,\n\t\t}\n\t\ttoken.Furigana = NeedsFurigana(token)\n\n\t\t// Add to token list\n\t\ttokens = append(tokens, token)\n\t}\n\n\treturn tokens\n}", "func (lr *Lexer) NextToken() ([]rune, Token, error) {\n\tif lr.normal {\n\t\ttext, err := lr.nextTextToken()\n\t\tif err != nil {\n\t\t\treturn nil, UnknownToken, err\n\t\t}\n\t\treturn text, TextToken, nil\n\t}\n\tb, ok := lr.top()\n\tif !ok {\n\t\treturn nil, UnknownToken, ErrUnclosedScript\n\t}\n\tswitch b {\n\tcase '(', ',':\n\t\tlr.offset++\n\t\tb, ok := lr.top()\n\t\tif !ok {\n\t\t\treturn nil, UnknownToken, ErrUnclosedParenthesis\n\t\t}\n\t\tif b == ')' {\n\t\t\treturn lr.NextToken()\n\t\t}\n\t\treturn lr.nextArg()\n\tcase ')':\n\t\tlr.offset++\n\t\tnext, ok := lr.top()\n\t\tif !ok || next != '}' {\n\t\t\treturn nil, UnknownToken, ErrUnclosedScript\n\t\t}\n\t\tlr.offset++\n\t\tlr.normal = true\n\t\treturn lr.NextToken()\n\tdefault:\n\t\ttoken, err := lr.nextName()\n\t\tif err != nil {\n\t\t\treturn nil, UnknownToken, err\n\t\t}\n\t\tb, ok := lr.top()\n\t\tif !ok {\n\t\t\treturn nil, UnknownToken, ErrUnclosedScript\n\t\t}\n\t\tif b == '}' {\n\t\t\tlr.offset++\n\t\t\tlr.normal = true\n\t\t\treturn token, VariableNameToken, nil\n\t\t}\n\t\treturn token, FuncNameToken, nil\n\t}\n}", "func eval(expression TokenStream) (value int) {\n\ts := stack.New()\n\n\tfor _, token := range expression {\n\t\tif token.kind == OPERAND {\n\t\t\ts.Push(token)\n\t\t} else {\n\t\t\top1 := s.Pop().(Token)\n\t\t\top2 := s.Pop().(Token)\n\t\t\tvar result int\n\t\t\tswitch token.sValue {\n\t\t\tcase \"+\":\n\t\t\t\tresult = op1.iValue + op2.iValue\n\t\t\tcase \"*\":\n\t\t\t\tresult = op1.iValue * op2.iValue\n\t\t\t}\n\t\t\ts.Push(Token{kind: OPERAND, iValue: result})\n\t\t}\n\t}\n\n\tt := s.Pop().(Token)\n\tvalue = t.iValue\n\n\treturn\n}", "func fToken(value, tokenType string, parts []Part) Token {\n\treturn Token{\n\t\tTValue: value,\n\t\tTType: tokenType,\n\t\tParts: parts,\n\t}\n}", "func analyze(text string) []string {\n\ttokens := DefaultSplitString(text)\n\n\ttokens = loadFilter(tokens)\n\treturn tokens\n}", "func (p *Parser) lookahead(context ParserContext) (Token, string) {\n\ttok, lit := p.scannedItems[p.position].tok, p.scannedItems[p.position].literal\n\tif context == Values {\n\t\tswitch tok {\n\t\tcase InToken, NotInToken:\n\t\t\ttok = IdentifierToken\n\t\t}\n\t}\n\treturn tok, lit\n}", "func (p *Parser) lookahead(context ParserContext) (Token, string) {\n\ttok, lit := p.scannedItems[p.position].tok, p.scannedItems[p.position].literal\n\tif context == Values {\n\t\tswitch tok {\n\t\tcase InToken, NotInToken:\n\t\t\ttok = IdentifierToken\n\t\t}\n\t}\n\treturn tok, lit\n}", "func (c *DataSet) Tokens() []string {\n\ttoks := map[string]bool{}\n\tfor _, samples := range c.TrainingSamples {\n\t\tfor _, sample := range samples {\n\t\t\tfor tok := range sample {\n\t\t\t\ttoks[tok] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tres := make([]string, 0, len(toks))\n\tfor tok := range toks {\n\t\tres = append(res, tok)\n\t}\n\tsort.Strings(res)\n\treturn res\n}", "func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal }", "func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal }", "func (cl *CharLiteral) TokenLiteral() token.Token { return cl.Token }", "func (s *Scanner) tok(typ Type, text string) *Token {\n\ts.peekRunes = nil\n\treturn mkToken(typ, text)\n}", "func New(l *lexer.Lexer, context string) *Parser {\n\tp := &Parser{\n\t\tl: l,\n\t\tContext: context,\n\t\terrors: []string{},\n\t}\n\n\tp.prefixParseFns = make(map[token.Type]prefixParseFn)\n\tp.registerPrefix(token.Ident, p.parseIdentifier)\n\tp.registerPrefix(token.Int, p.parseIntegerLiteral)\n\tp.registerPrefix(token.String, p.parseStringLiteral)\n\tp.registerPrefix(token.Bang, p.parsePrefixExpression)\n\tp.registerPrefix(token.Minus, p.parsePrefixExpression)\n\tp.registerPrefix(token.True, p.parseBoolean)\n\tp.registerPrefix(token.False, p.parseBoolean)\n\tp.registerPrefix(token.Lparen, p.parseGroupedExpression)\n\tp.registerPrefix(token.If, p.parseIfExpression)\n\tp.registerPrefix(token.Function, p.parseFunctionLiteral)\n\tp.registerPrefix(token.Lbracket, p.parseArray)\n\n\tp.infixParseFns = make(map[token.Type]infixParseFn)\n\tp.registerInfix(token.Plus, p.parseInfixExpression)\n\tp.registerInfix(token.Minus, p.parseInfixExpression)\n\tp.registerInfix(token.Slash, p.parseInfixExpression)\n\tp.registerInfix(token.Astersik, p.parseInfixExpression)\n\tp.registerInfix(token.EQ, p.parseInfixExpression)\n\tp.registerInfix(token.NEQ, p.parseInfixExpression)\n\tp.registerInfix(token.LT, p.parseInfixExpression)\n\tp.registerInfix(token.GT, p.parseInfixExpression)\n\tp.registerInfix(token.LTE, p.parseInfixExpression)\n\tp.registerInfix(token.GTE, p.parseInfixExpression)\n\tp.registerInfix(token.Lparen, p.parseCallExpression)\n\tp.registerInfix(token.Dot, p.parseInfixCallExpression)\n\tp.registerInfix(token.Assign, p.parseAssignmentExpression)\n\n\tp.nextToken() // set currToken\n\tp.nextToken() // set peekToken\n\n\treturn p\n}", "func ScanTokens(input string) []def.Token {\n\ttokens = []def.Token{}\n\tsource = make([]rune, len(input))\n\tfor i, r := range input {\n\t\tsource[i] = r\n\t}\n\tstart, current, line = 0, 0, 1\n\n\tfor !isAtEnd() {\n\t\tstart = current\n\t\tscanToken()\n\t}\n\n\ttokens = append(tokens, def.Token{Type: def.EOF, Lexeme: \"\", Literal: nil, Line: line})\n\treturn tokens\n}", "func (il *IntLiteral) TokenLiteral() token.Token { return il.Token }", "func (l *Lexer) Lex() (*Token, error) {\n\t// keep looping until we return a token\n\tfor {\n\t\tr, _, err := l.reader.ReadRune()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn &Token{l.pos, EOF, \"\"}, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// update the column to the position of the newly read in rune\n\t\tl.pos.Column++\n\n\t\tswitch r {\n\t\tcase '.':\n\t\t\treturn &Token{l.pos, PATH, tokens[PATH]}, nil\n\t\tcase '|':\n\t\t\treturn &Token{l.pos, PIPE, tokens[PIPE]}, nil\n\t\tcase '=':\n\t\t\tif l.lexEqual() {\n\t\t\t\treturn &Token{l.pos, EQUAL, tokens[EQUAL]}, nil\n\t\t\t}\n\t\t\treturn &Token{l.pos, ASSIGN, tokens[ASSIGN]}, nil\n\t\tcase '\"':\n\t\t\tstartPos := l.pos\n\t\t\tlit := l.lexString()\n\t\t\treturn &Token{startPos, STRING, lit}, nil\n\t\tdefault:\n\t\t\tif unicode.IsSpace(r) {\n\t\t\t\tcontinue // nothing to do here, just move on\n\t\t\t} else if unicode.IsDigit(r) {\n\t\t\t\t// backup and let lexInt rescan the beginning of the int\n\t\t\t\tstartPos := l.pos\n\t\t\t\tl.backup()\n\t\t\t\tlit := l.lexInt()\n\t\t\t\treturn &Token{startPos, INT, lit}, nil\n\t\t\t} else if unicode.IsLetter(r) || r == '-' {\n\t\t\t\t// backup and let lexIdent rescan the beginning of the ident\n\t\t\t\tstartPos := l.pos\n\t\t\t\tl.backup()\n\t\t\t\tlit := l.lexIdent()\n\t\t\t\treturn &Token{startPos, IDENT, lit}, nil\n\t\t\t} else {\n\t\t\t\treturn &Token{l.pos, ILLEGAL, string(r)}, nil\n\t\t\t}\n\t\t}\n\t}\n}", "func extractContext(s string) string {\n z := html.NewTokenizer(strings.NewReader(s))\n\tfor {\n\t\ttt := z.Next()\n\t\tswitch tt {\n\t\t\tcase html.ErrorToken:\n syslog.Critf(\"Step1 extractContext() error: %s\", z.Err())\n fmt.Println(\"Step1 extractContext() error\", z.Err())\n\t\t\t\treturn \"Step1 extractContext() error\"\n\t\t\tcase html.TextToken:\n\t\t\t\ttext := string(z.Text())\n\t\t\t\treturn text\n\t\t}\n\t}\n}", "func lexerFunction(thread int, ruleNum int, yytext string, genSym *symbol) int {\n\tswitch ruleNum {\n\tcase 0:\n\t\t{\n\t\t\t*genSym = symbol{LPAR, 0, nil, nil, nil}\n\t\t\treturn _LEX_CORRECT\n\t\t}\n\tcase 1:\n\t\t{\n\t\t\t*genSym = symbol{RPAR, 0, nil, nil, nil}\n\t\t\treturn _LEX_CORRECT\n\t\t}\n\tcase 2:\n\t\t{\n\t\t\t*genSym = symbol{TIMES, 0, nil, nil, nil}\n\t\t\treturn _LEX_CORRECT\n\t\t}\n\tcase 3:\n\t\t{\n\t\t\t*genSym = symbol{PLUS, 0, nil, nil, nil}\n\t\t\treturn _LEX_CORRECT\n\t\t}\n\tcase 4:\n\t\t{\n\t\t\tnum := lexerInt64Pools[thread].Get()\n\t\t\terr := error(nil)\n\t\t\t*num, err = strconv.ParseInt(yytext, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn _ERROR\n\t\t\t}\n\t\t\t*genSym = symbol{NUMBER, 0, num, nil, nil}\n\t\t\treturn _LEX_CORRECT\n\t\t}\n\tcase 5:\n\t\t{\n\t\t\treturn _SKIP\n\t\t}\n\tcase 6:\n\t\t{\n\t\t\treturn _SKIP\n\t\t}\n\tcase 7:\n\t\t{\n\t\t\treturn _ERROR\n\t\t}\n\t}\n\treturn _ERROR\n}", "func (l *Lexer) NextToken() token.Token {\n\tvar tok token.Token\n\n\tl.skipWhitespace()\n\ttok.LineNo = l.lineNo\n\ttok.CharNo = l.charNo\n\n\tswitch l.ch {\n\n\tcase ';':\n\t\ttok = newToken(token.SEMICOLON, l.ch, l.charNo, l.lineNo)\n\tcase '.':\n\t\ttok = newToken(token.DOT, l.ch, l.charNo, l.lineNo)\n\tcase '(':\n\t\ttok = newToken(token.LPAREN, l.ch, l.charNo, l.lineNo)\n\tcase ')':\n\t\ttok = newToken(token.RPAREN, l.ch, l.charNo, l.lineNo)\n\tcase ',':\n\t\ttok = newToken(token.COMMA, l.ch, l.charNo, l.lineNo)\n\tcase '+':\n\t\ttok = newToken(token.PLUS, l.ch, l.charNo, l.lineNo)\n\tcase '{':\n\t\ttok = newToken(token.LBRACE, l.ch, l.charNo, l.lineNo)\n\tcase '}':\n\t\ttok = newToken(token.RBRACE, l.ch, l.charNo, l.lineNo)\n\tcase '-':\n\t\ttok = newToken(token.MINUS, l.ch, l.charNo, l.lineNo)\n\n\tcase '*':\n\t\ttok = newToken(token.ASTERISK, l.ch, l.charNo, l.lineNo)\n\tcase '/':\n\t\ttok = newToken(token.SLASH, l.ch, l.charNo, l.lineNo)\n\tcase '=':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.EQ, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.ASSIGN, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '!':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.NOT_EQ, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.BANG, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '<':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.LTE, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.LT, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '>':\n\t\tif l.peekChar() == '=' {\n\t\t\tch := l.ch\n\t\t\tl.readChar()\n\t\t\ttok = token.Token{Type: token.GTE, Literal: string(ch) + string(l.ch), CharNo: l.charNo, LineNo: l.lineNo}\n\t\t} else {\n\t\t\ttok = newToken(token.GT, l.ch, l.charNo, l.lineNo)\n\t\t}\n\tcase '\"':\n\t\ttok.Type = token.STRING\n\t\ttok.Literal = l.readString()\n\tcase ':':\n\t\ttok = newToken(token.COLON, l.ch, l.charNo, l.lineNo)\n\tcase '[':\n\t\ttok = newToken(token.LBRACKET, l.ch, l.charNo, l.lineNo)\n\tcase ']':\n\t\ttok = newToken(token.RBRACKET, l.ch, l.charNo, l.lineNo)\n\tcase 0:\n\t\ttok.Literal = \"\"\n\t\ttok.Type = token.EOF\n\tdefault:\n\t\tif isLetter(l.ch) {\n\t\t\ttok.Literal = l.readIdentifier()\n\t\t\ttok.Type = token.LookupIdent(tok.Literal)\n\t\t\treturn tok\n\t\t} else if isDigit(l.ch) {\n\t\t\ttok.Type, tok.Literal = l.readNumber()\n\t\t\treturn tok\n\t\t} else {\n\t\t\ttok = newToken(token.ILLEGAL, l.ch, l.charNo, l.lineNo)\n\t\t}\n\t}\n\tl.readChar()\n\treturn tok\n}", "func fTokens() Tokens {\n\treturn Tokens{\n\t\tIndex: -1,\n\t}\n}", "func (c *Call) TokenLiteral() token.Token { return c.Token }", "func (p *parser) token() tree.Token {\n\treturn tree.Token{\n\t\tType: p.tok,\n\t\tPrefix: p.pre,\n\t\tOffset: p.off,\n\t\tBytes: p.lit,\n\t}\n}", "func (ds *DefaultSyntax) validateTokens(token string) error {\n\t// split each token on the comma\n\tt := strings.Split(token, \",\")\n\tfor _, str := range t {\n\t\tisValid := ds.regExpTokenValidator.MatchString(str)\n\t\tif !isValid {\n\t\t\treturn errors.New(fmt.Sprintf(\"Invalid input string '%s' please check the correct syntax\", ds.input))\n\t\t}\n\t}\n\treturn nil\n}", "func EmitTokens(reader *bufio.Reader, out chan<- Token) {\n\tfrags := make(chan string, 100)\n\tgo emitFragments(reader, frags)\n\tfor word := range frags {\n\t\t// Emit as many phrase tokens as possible\n\t\tfor ok := true; ok; {\n\t\t\tword, ok = parsePhraseToken(word, frags, out)\n\t\t}\n\t\tswitch {\n\t\tcase word == \"\": // end of input\n\t\t\tclose(out)\n\t\t\treturn\n\t\tcase word == \"WIN\": // TROOF literal\n\t\t\tout <- Token{Literal, true}\n\t\tcase word == \"FAIL\":\n\t\t\tout <- Token{Literal, false}\n\t\tcase word == \"NOOB\": // NOOB is a literal; casting to type NOOB is not allowed\n\t\t\tout <- Token{Literal, nil}\n\t\tcase word[0] == '\"': // yarn literal\n\t\t\tout <- yarnLiteralToToken(word)\n\t\tcase isIdentifier(word):\n\t\t\tout <- Token{Ident, word}\n\t\tdefault:\n\t\t\tif numbr, err := strconv.ParseInt(word, 0, 64); err == nil {\n\t\t\t\tout <- Token{Literal, numbr}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif numbar, err := strconv.ParseFloat(word, 64); err == nil {\n\t\t\t\tout <- Token{Literal, numbar}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tout <- Token{Err, \"Syntax error: unexpected token \" + word}\n\t\t}\n\t}\n}", "func (t *infixTokenizer) convertExpressionsIntoAtoms(tokens []token) {\n\tfor i := range tokens {\n\t\tif tokens[i].Type == expressionType {\n\t\t\ttokens[i].Type = atomType\n\t\t}\n\t}\n}" ]
[ "0.6739857", "0.6652426", "0.6560778", "0.6519955", "0.6415867", "0.6381054", "0.6336418", "0.6074973", "0.6074295", "0.60185516", "0.59861237", "0.59165454", "0.58904195", "0.5833101", "0.58267784", "0.5766809", "0.57505447", "0.5721691", "0.5713765", "0.56996644", "0.567599", "0.5675485", "0.5672603", "0.566519", "0.56649774", "0.56430596", "0.56180733", "0.5613564", "0.5593655", "0.55652714", "0.55484027", "0.5520077", "0.5499349", "0.549911", "0.54973584", "0.54941994", "0.5490986", "0.54769784", "0.54535663", "0.5442452", "0.5436564", "0.54293513", "0.5421651", "0.54161304", "0.5403327", "0.53684556", "0.5349103", "0.53431946", "0.5308464", "0.53049934", "0.52862036", "0.52483606", "0.5212864", "0.52127117", "0.5156363", "0.5155488", "0.51553136", "0.5129712", "0.51234305", "0.51049185", "0.5072807", "0.506437", "0.5064127", "0.5063977", "0.5058523", "0.5058523", "0.5053079", "0.5050258", "0.5037605", "0.50331074", "0.5027246", "0.5023365", "0.50208473", "0.50130004", "0.4994306", "0.498328", "0.49739644", "0.49719086", "0.49700063", "0.49623707", "0.4960376", "0.4960376", "0.4954423", "0.49490628", "0.49490628", "0.49207708", "0.4918786", "0.4913093", "0.49046537", "0.48992038", "0.48929322", "0.4892754", "0.48855826", "0.48845956", "0.4866159", "0.48429272", "0.48408663", "0.48377824", "0.48270124", "0.48232982" ]
0.78800166
0
In go a main function is automatically called.
func main() { /**This is the shortform syntax for declaring a variable. It infers the type automatically, but still adheres to the precepts of static typing; NO implicit type casting. NOTE: This only works INSIDE functions, you cannot define global scope variables this way*/ name := "John Doe" greet(name, greeting) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\tif err := run(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}", "func Main(args ...interface{}) {\n\n\t// ...\n}", "func main() {\n\tgimain.Main(func() {\n\t\tmainrun()\n\t})\n}", "func main() {\n\tgimain.Main(func() {\n\t\tmainrun()\n\t})\n}", "func main() {\n\tgimain.Main(func() {\n\t\tmainrun()\n\t})\n}", "func main() {\n\tgimain.Main(func() {\n\t\tmainrun()\n\t})\n}", "func main() {\n\tgimain.Main(func() {\n\t\tmainrun()\n\t})\n}", "func main(){\n\tfmt.Println(\"Hi there!\")\n}", "func main() {\n\tcore.Start()\n}", "func main() {\n\tif err := run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tif err := run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\n\t\n}", "func main(){\n\t//Basic Hello World example\n\tfmt.Println(\"Hello World\")\n}", "func main() {\n\tcmd.Run()\n}", "func main() {\n\tif err := realMain(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tfmt.Println(\"Hi there!\")\n}", "func main() {\n\tfmt.Println(\"Hi there!\")\n}", "func main() {\n\terr := run(os.Args)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\tfmt.Println(\"we here\")\n}", "func main(){\n\tfmt.Println(\"Hello\")\n}", "func main() {\n\tdebugln(\"main!\")\n}", "func main(){\n\tfmt.Println(\"test\")\n}", "func main() {\n\tos.Exit(run())\n}", "func main() {\n\terr := run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func main() {\n\treturn\n}", "func main() {\n\treturn\n}", "func main() {\n\tfmt.Println(\"Hello, World!\")\n}", "func main() {\n\tfmt.Println(\"Hello, World!\")\n}", "func main() {\n\tfmt.Println(\"Hello, world\")\n}", "func main() {\n\t\n}", "func main() {\n\t\n}", "func main() {\n\tfmt.Println(\"Hello world\")\n}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {}", "func main() {\n\tapplication.Application()\n}", "func main() {\n\tfmt.Println(\"Hola berracos!\")\n}", "func main() {\n\tif err := run(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\tif err := run(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}", "func main() {\r\n\r\n}", "func main() {\n\tfmt.Println(\"Hello World!\")\n}", "func main() {\n\tfmt.Println(\"Hello World!\")\n}", "func main() {\n\tfmt.Println(\"Hello World!!!\")\n}", "func main() {\n\thelloWorld()\n}", "func main() {\n\tos.Exit(realMain())\n}", "func main() {\n\tos.Exit(realMain())\n}", "func main() {\n //The main() function is a special type of function and it is the entry point of the executable programs. \n //It does not take any argument nor return anything.\n\tfmt.Println(\"HEllo world!\")\n}", "func main() {\n\tbase()\n}", "func main() {\n\tapp := cli.NewCLI() // Get a new CLI\n\n\terr := app.Run(os.Args) // Run the CLI\n\tif err != nil { // Check for errors\n\t\tlog.Fatal(err) // Panic\n\t}\n}", "func main() {\n\tapp := getRootCmd()\n\n\t// ignore error so we don't exit non-zero and break gfmrun README example tests\n\t_ = app.Execute()\n}", "func main() { /* Do something*/ }", "func main()", "func main()", "func main()", "func Main() {\n\tflag.Parse()\n\n\tif err := run(); err != nil {\n\t\tlog.Warningf(\"%v\", err)\n\t\tos.Exit(1)\n\t}\n}", "func main() {\n\tfmt.Println(\"Hi, from main()\")\n\thello()\n\twassup()\n\tawesome()\n}", "func main() {\n\tfmt.Println(\"Welcome to origourls!\")\n}", "func main() {\n\n\tcli := CLI{}\n\tcli.Run()\n}", "func main() {\n\twf.Run(run)\n}", "func main(){\n\tprintln(\"Test\")\n}", "func main(){\n\n}", "func main() {\n\t//Clears screen for better readability\n\tCallClear()\n\t//Calls function to start program\n\tmenu()\n}", "func Main() {\n\tos.Exit(Run(os.Args, os.Stdin, os.Stdout, os.Stderr))\n}", "func main() {\n\tperform()\n}", "func main() {\n\tapp.StartApp()\n}", "func main() {\n\terr := mainInner()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err.Error())\n\t\tos.Exit(2)\n\t}\n}", "func main() {\n\tcli.CommandLineInterface()\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}", "func main() {\n\n}" ]
[ "0.83128273", "0.81733865", "0.8166593", "0.8166593", "0.8166593", "0.8166593", "0.8166593", "0.8113298", "0.8093467", "0.8060706", "0.8060706", "0.8047963", "0.80479354", "0.79819757", "0.79602563", "0.7953302", "0.7953302", "0.7948158", "0.79363006", "0.7931229", "0.7930159", "0.7929124", "0.7918791", "0.7893592", "0.78927433", "0.78927433", "0.78763664", "0.78763664", "0.78681225", "0.78677547", "0.78677547", "0.7864732", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78573465", "0.78556", "0.785434", "0.7843284", "0.7843284", "0.78343505", "0.7832689", "0.7832689", "0.7828504", "0.7820625", "0.77861816", "0.77861816", "0.77792966", "0.7770831", "0.7762681", "0.774876", "0.77463984", "0.7738521", "0.7738521", "0.7738521", "0.7735164", "0.77201885", "0.77180564", "0.77007455", "0.76938736", "0.7677654", "0.76742", "0.7635845", "0.7599388", "0.7590917", "0.75831497", "0.75790644", "0.75742793", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657", "0.75624657" ]
0.0
-1
A simple function declaration that takes two parameters and prints them
func greet(name string, greeting string) { fmt.Println(greeting, name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func functionName2(param1 string, param2 int) {\n\tfmt.Println(param1, param2)\n}", "func functionName3(param1, param2 int) {\n\tfmt.Print(param1, param2)\n}", "func main() {\n\tfmt.Println(first, second)\n}", "func printTwoString(message, messageTwo string){\n\tfmt.Println(message,messageTwo)\n}", "func SampleFunc() {\n\n\t// variable declaration\n\tmsg := \"hello world\"\n\tdisplay := fmt.Println\n\n\tif x > 10 {\n\t\tdisplay(\"x is greater than 10\")\n\t} else {\n\t\tfmt.Println(\"x is smaller than 10\")\n\t}\n\n\tdisplay(msg)\n\tconversion(&msg)\n\tdisplay(msg)\n\tfmt.Printf(\"value of ax is %v\", ax)\n\tfmt.Printf(\"\\nvalue of a is %.2f\", a) // handle decimal precision\n\tdisplay(\"\\nHello \" + \", I'm Vikas Rawat\")\n\tfmt.Printf(\"%c\", 33)\n}", "func greet1(fname string, lname string) {\n\tfmt.Println(fname, lname)\n}", "func myPrint(s string){\nfmt.Print(s)\n}", "func sum(a, b int) int {\n fmt.Printf(\"value of a in sum() = %d\\n\", a);\n fmt.Printf(\"value of b in sum() = %d\\n\", b);\n\n return a + b;\n}", "func print(str string) { fmt.Println(str) }", "func print(str string) { fmt.Println(str) }", "func main() {\n\tfmt.Println(\"add(42, 13)=\", add(42, 13))\n\n\tfmt.Println(\"addThree(23, 45, 5.6):\", addThree(23, 45, 5.6))\n}", "func main() {\n\n\t// (Print - Println) - Printf\n\n\t/* \tfmt.Println(\"Merhaba\")\n\t \tfmt.Print(\"Merhaba\")\n\t \tfmt.Println(\"\")\n\t \tfmt.Printf(\"Merhaba\")\t */\n\n\t/* name := \"Arin\" */\n\n\t/* \tfmt.Print(name)\n\t \tfmt.Println(name)\n\t \tfmt.Printf(name) */\n\n\t/* \tfmt.Print(\"Benim Adım\", name)\n\t \tfmt.Println(\"\")\n\t \tfmt.Println(\"Benim Adım \", name)\n\t \tfmt.Printf(\"Benim Adım %X %T\", name, name)\n\n\t\t// the value in a default format\n\t\t// %T\ta Go-syntax representation of the type of the value */\n\n\t/* \tx := 100\n\t \ty := 20\n\t \tz := 30\n\n\t \tfmt.Printf(\"%b %d %o\", x, y, z) */\n\n\t// %b\tbase 2\n\t// %d\tbase 10\n\t// %o\tbase 8\n\n\t/* name, age := \"Alperen\", 23 */\n\n\t// fmt.Print(\"Benim Adım \", name, \", ve ben \", age, \" yaşındayım.\")\n\t// fmt.Println(\"Benim Adım\", name, \"ve ben\", age, \"yaşındayım.\")\n\t// fmt.Printf(\"Benim Adım %v, ve ben %v yaşındayım\", name, age)\n\n\t//VISIBILITY\n\n\t/* \tfmt.Println(x)\n\n\t \tmyFunc() */\n\n\t/* \tvar coin string // count - customer - coin\n\t \t// Go camel case isimlendirme kullanılır.\n\t \tvar coinType string\n\t \tvar custName string\n\t \t// kısaltmalar büyük harflerle yazılır\n\t \tvar URL // Url değil\n\t \tvar HTTP // http değil \"xyzHTTP\" */\n\n}", "func printWith(p func(string), msg string) {\n\tp(msg)\n}", "func testabc(a,b int){\n\n}", "func main() {\n\tx := 42\n\ty := 13\n\n\tprintln(x + y) // this should be add(x,y)!\n}", "func Display(_ string) {\n}", "func main() {\n\targ1 := \"asd\"\n\targ2 := \"def\"\n\tfunc2(&arg1, &arg2)\n\tfmt.Println(arg2)\n}", "func hello(name string){\n\tfmt.Println(\"Hello\" , name)\n}", "func basicFuntionOne() {\n\tfmt.Println(\"Basic function #1\")\n}", "func main() {\n\tx := 42\n\ty := \"James Bond\"\n\tz := true\n\n\tfmt.Println(x, y, z)\n\tfmt.Println(x)\n\tfmt.Println(y)\n\tfmt.Println(z)\n}", "func printRes() {\n\tfmt.Printf(\"%d %d\\n\", pAlice, pBob)\n}", "func main() {\n\tprintln(\"add:\", add(2, 3))\n}", "func PrintFaint(format string, a ...interface{}) { fmt.Println(Faint(format, a...)) }", "func Print(greet, name string) {\n\tfmt.Printf(\"%v, %v!\\n\", greet, name)\n}", "func returnArgs(a, b string ){\n\tfmt.Println(a + \" \" + b)\n}", "func Printf(format string, v ...interface{}) {\n Std.Output(LevelInfo, CallDepth, fmt.Sprintf(format, v...))\n}", "func printMulti(v int, function func(x int) int) {\n\tfmt.Println(function(v))\n}", "func (p FloatFormalParam) Print() string {\n\t// TODO we will want more custom formatting based on the type here\n\treturn \"std::cout << \\\"\" + p.Name + \" \\\" << \" + p.Reference() + \" << std::endl;\"\n}", "func printOperations(a int, f func(int) int) {\n\tfmt.Println(f(a))\n}", "func greet2(fname, lname string) (s string){\n\ts = fmt.Sprint(fname, lname)\n\treturn\n}", "func main() {\n\tfooValue := foo()\n\tbarValueInt, barValueString := bar()\n\n\tfmt.Printf(\"Foo stores %v, barValue stores an int which is %v, and also a string which is %v\\n\", fooValue, barValueInt, barValueString)\n}", "func StdoutAs(funcName, format string, a ...interface{}) {\n\tfmt.Printf(GetOutputPrefix(funcName)+format+\"\\n\", a...)\n}", "func Print(vs ...interface{}) {\n\tstd.Print(vs...)\n}", "func f () {\r\n\tvar a1 int \r\n\tvar a2 []int \r\n\r\n\tprint (a1, a2)\r\n}", "func myPrintFunction(custom string) myPrintType{\nreturn func(s string){\nfmt.Println(s +custom)\n}\n}", "func Stdout(format string, a ...interface{}) {\n\tfmt.Printf(GetOutputPrefix(GetFuncName(1))+format+\"\\n\", a...)\n}", "func greet(firstName, lastName string) (string, string) {\n\treturn fmt.Sprint(firstName, firstName), fmt.Sprint(lastName, lastName)\n}", "func PrintBasicArithmeticResultForSingleInput(function string, x, v int) {\n\tfmt.Printf(\"%s(%d) = %d\\n\", function, x, v)\n\tfmt.Println(\"===============================================================\")\n}", "func prt(args ...interface{}) {\n\tfmt.Println(append([]interface{}{\"-------------> DEMO\"}, args...)...)\n}", "func demo(greeting string) {\n\tfmt.Println(greeting)\n}", "func Printf(format string, v ...interface{}) {\n\tstd.Output(std.callDepth, fmt.Sprintf(format, v...), std.level)\n}", "func Print(v ...interface{}) {\n Std.Output(LevelInfo, CallDepth, sout(v...))\n}", "func Hello(name string){\n\tfmt.Printf(\"Hello %s\\n\", name)\n}", "func Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, a...) }", "func example2(a string, val ...int) {\n\tfmt.Println(a)\n\tfmt.Println(val)\n}", "func (f *LambdaFunc) printf(format string, args ...any) {\n\tmsg := fmt.Sprintf(format, args...)\n\tlog.Printf(\"%s [FUNC %s]\", strings.TrimRight(msg, \"\\n\"), f.name)\n}", "func bar(s string) {\n\tfmt.Println(\"hello,\", s)\n}", "func Print(x ...interface{}) {\n\tfmt.Println(x...)\n}", "func PrintArg1(arg string) {\n\tArg = arg\n\tArgNum = 1\n\tfmt.Println(\"Hello \", Arg)\n}", "func Print(a ...interface{}) (n int, err error) { return fmt.Print(a...) }", "func dosomething(random int, a func(), b func()) {\n\t fmt.Println(\"Details passed to dosomething function :\")\n\t fmt.Printf(\"\\t\\t\\t\\t%v\\t%v\\t%v\\n\",random,a,b)\n if random % 2 == 0{\n \ta()\n\t\t}else{\n b()\n\t\t}\n}", "func (f SprinterFunc) Sprint(any Any) string { return f(any) }", "func functionName1() {\n\tfmt.Println(\"Simple Function\")\n}", "func Stdf(format string, a ...interface{}) {\n\tfmt.Printf(format, a...)\n}", "func dumbfunc() (string, int) {\n return \"Alex Herrmann\", 19\n}", "func SayHi(name string) {\n fmt.Printf(\"Hi, %s\\n\", name)\n}", "func Printf(z []byte, params ...interface{}) string {\n\tp := newParametizer(z)\n\tdefer p.reset()\n\n\t// make sure we always have 9 parameters -- makes it easier\n\t// later to skip checks and its faster\n\tfor i := 0; i < len(p.params) && i < len(params); i++ {\n\t\tp.params[i] = params[i]\n\t}\n\n\treturn p.exec()\n}", "func Println(args ...interface{}){\n\tfmt.Println(args...)\n}", "func main() {\n\tentero, cadena, booleano := 2, \"Hola\", true\n\tfmt.Println(entero, cadena, booleano) // imprimir en nueva linea\n}", "func printPair(pair Pair) {\n\tfmt.Print(\" < \")\n\tprintVector(pair.V1)\n\tfmt.Print(\" , \")\n\tprintVector(pair.V2)\n\tfmt.Print(\" > \")\n}", "func TestA(){\n fmt.Printf(\"%v\\n\", a)\n fmt.Printf(\"%v\\n\", b)\n}", "func (st *Student) display2() {\n\tfmt.Println()\n\tfmt.Printf(\"Name: %s - Age: %d - Address: %s\", st.student_name, st.student_age, st.student_address)\n}", "func printf(topic string, params ...interface{}) {\n\tfmt.Printf(fmt.Sprintf(\"%s\\n\", topic), params...)\n}", "func PrintBright(format string, a ...interface{}) { fmt.Println(Bright(format, a...)) }", "func Greet(name string) {\n fmt.Println(\"Hello, \" + name)\n}", "func Print(function interface{}, a ...interface{}) {\n\tif !isPrint {\n\t\treturn\n\t}\n\tdebug.LogInfo(os.Stdout, debug.GetShortPackageAndFunctionName(function)+\":\", a)\n}", "func Print(args ...interface{}) {\n\tglobal.Print(args...)\n}", "func print(args []types.HWType) types.HWType {\n\tfmt.Println(printer.PrintStr(args[0]))\n\treturn types.MakeNullImplicit()\n}", "func P(vs ...interface{}) {\n\tstd.Print(vs...)\n}", "func F(f string, v ...interface{}) {\n\t// log.Printf(f, v...)\n\tspewInstance.Printf(f+\"\\n\", v...)\n}", "func main() {\n\tfirst, last := greet(\"Luis \", \"Benavides \")\n\tfmt.Printf(\"%s %s \\n\", first, last)\n}", "func PrintDeb(s ...interface{}) {\n\tname, line := procName(false, 2)\n\tfmt.Print(\"=> \", name, \" \", line, \": \")\n\tfmt.Println(s...)\n\treturn\n}", "func Printf(args ...interface{}) {\n\tNewDefaultEntry().Print(args...)\n}", "func (pl ProdLogger) Printf(format string, args ...interface{}) {\n\n}", "func Haha1() {\r\n\tfmt.Print(\"Ha ha ebitut\\n\")\r\n}", "func Add(a,b int) (sum int ,result string) {\n\n\tsum = a+b\n\n\treturn sum, \"This is addition\"\n\n//fmt.Println(\"Addition\")\n\n}", "func main() {\n\t// To declare and assign a value within a function\n\t// use the short declaration operator.\n\tv := 2\n\n\tfmt.Println(o, v)\n}", "func main() {\n\toddOrEven(10)\n\toddOrEven(7)\n\tf.Println(\"Value from sumTheNumbers is \", sumTheNumbers(10, y))\n\tf.Println(\"Value from sumAndDiffOprationOnNumbers are:\")\n\tf.Println(sumAndDiffOprationsOnTwoNumbers(3, y))\n\t// https://stackoverflow.com/questions/52653779/how-to-parse-multiple-returns-in-golang\n\t// Check the above to print as the below\n\t//f.Printf(\"Value from sumAndDiffOprationsOnNumbers are:\\nSum = %v\\nDiff = %v\\n\", sumAndDiffOprationsOnTwoNumbers(3, y))\n\tf.Println(\"Value from variadicFunction is \", variadicFunction(1, 2, 3))\n\tf.Println(\"Value from variadicFunctionRecursion is \", variadicFunctionRecursion(1, 2, 3))\n\n\t// Example of an anonymous function\n\tfunc() {\n\t\tf.Println(\"Hi I'm an anonmous function. They call me that, because I don't have a name -- like lambda\")\n\t}()\n}", "func Print(v ...interface{}) {\n\tstd.Output(std.callDepth, fmt.Sprint(v...), std.level)\n}", "func main() {\r\n out := test1.DoubleValue(8) // call function in package\r\n fmt.Printf(\"Double, out = %d\\n\", out) // should print \"..out = 16\"\r\n// out := test1.TripleVariable(8), call function in package\r\n// fmt.Printf(\"Triple, out = %d\\n, out\") // should print \"..out = 16\"\r\n}", "func main() {\n\tx := 5\n\tw := 3\n\ty := 4\n\ta := `amen `\n\tb := `sister`\n\tc := `we are love`\n\tvar q int\n\tfmt.Print(`how old are u ?`)\n\tfmt.Scanln(&q)\n\tfmt.Println(`i am `, q, ` years old`)\n\n\tfmt.Println(onefunc(c))\n\tfmt.Println(stringop(a, b))\n\t//start(w, y)\n\tzero(x)\n\tfmt.Println(x) // x is still 5\n\tfmt.Println(start(w, y))\n}", "func greet(fname, lname string) string {\n\treturn fmt.Sprint(fname, \" \", lname)\n}", "func Printf(format string, a ...interface{}) {\n\tfmt.Fprintf(Noticer, format, a...)\n}", "func main() {\n\tfmt.Println(foo())\n\tfmt.Println(bar())\n}", "func foo(x ...int) {\n\tfmt.Println(x)\n\tfmt.Printf(\"%T\\n\", x)\n}", "func Printf(format string, v ...interface{}) { std.lprintf(INFO, format, v...) }", "func main() {\n\taFunc := func(x int) (int, bool) {\n\t\treturn x / 2, x%2 == 0\n\t}\n\tvar h, e = aFunc(10)\n\tfmt.Println(h, e)\n}", "func main() {\n\tfmt.Print(\"My weight on the surface of Mars is \")\n\tfmt.Print(230.4 * 0.3783)\n\tfmt.Print(\" lbs, and I would be \")\n\tfmt.Print(63 * 365 / 687)\n\tfmt.Print(\" years old.\\n\")\n\t// Using Printf gives better control over output\n\tfmt.Printf(\"My weight on the surface of Mars is %v lbs,\", 230.4*0.3783)\n\tfmt.Printf(\" and I would be %v years old.\\n\", 63*365/687)\n\t// Using Println puts a return on the line\n\tfmt.Println(\"If used Print I would need a return character. With Println I don't\")\n\t// Multiple format verbs can be used in the with Print f\n\tfmt.Printf(\"My weight on the surface of %v is %v lbs.\\n\", \"Earth\", 154.0)\n\t// Printf can also help aligning text\n\tfmt.Printf(\"%-15v $%4v\\n\", \"SpaceX\", 94)\n\tfmt.Printf(\"%-15v $%4v\\n\", \"Virgin Galactic\", 100)\n\n}", "func main() {\n\tfmt.Printf(\"%T\\n%T\\n%T\\n\", x, y, z)\n\tfmt.Println(x)\n\tfmt.Println(y)\n\tfmt.Println(z)\n}", "func Printf(format string, args ...interface{}) {\n\tglobal.Printf(format, args...)\n}", "func Print(args lisp.Object) {\n\tlisp.Call(\"princ\", lisp.MapConcat(lisp.Prin1ToString, args, \"\"))\n}", "func twoInt(values ...int) { // expected two params\n\tfmt.Println(values)\n}", "func addition(a , b int) int {\n\tfmt.Println(\"Adding two numbers\",a,b)\n\treturn a + b\n}", "func Printf(format string, a ...interface{}) {\n\tPrint(\n\t\tfmt.Sprintf(\n\t\t\tformat, a...,\n\t\t),\n\t)\n}", "func exerciseTwo() {\n\tfmt.Printf(\"\\n\\n---- 2 ----- \\n\")\n\n\tfmt.Println(x)\n\tfmt.Println(y)\n\tfmt.Println(z)\n\n}", "func main() {\n // The fmt package provides functions for formatting data with io streams, strings, and the console.\n fmt.Println(\"Hello,\", \"gopher!\") // Arguments will be converted to strings and concatenated together with spaces in between.\n fmt.Printf(\"Goodbye, %s.\\n\", \"gopher\") // Does what you would think if you are familiar with printf in other languages.\n\n // Go's Printf() is really friendly.\n fmt.Printf(\"%f is %s\", \"fred\")\n // Unused variables will not compile\n //var i int = 0\n}", "func ExampleMyFunc() {\n\tMyFunc()\n\n\t// Output:\n\t// MyFunc\n}", "func main() {\n\n\t// There is a function we called that shorthand but this we can prevent globally define value to call.\n\t// Always remember if value is declare but not used it will raise an error in Golang\n\t// This will print the output\n\tname := \"Gautam\"\n\tage := 34\n\tprice := 11.1\n\tcontact, email := 98765432, \"[email protected]\"\n\tfmt.Println(value1)\n\tfmt.Println(age)\n\tfmt.Println(price)\n\tfmt.Println(name)\n\tfmt.Println(contact)\n\tfmt.Println(email)\n\n\n}", "func (l ZkLoggerFunc) Printf(format string, args ...interface{}) {\n\tl(format, args...)\n}", "func main() {\n fmt.Println(add(23,34)) \n}" ]
[ "0.7193864", "0.7145628", "0.659819", "0.6474157", "0.64014083", "0.6371635", "0.63422257", "0.6295856", "0.6172505", "0.6172505", "0.6147449", "0.61148703", "0.61049265", "0.60778385", "0.6029526", "0.60243577", "0.60058254", "0.5994484", "0.5975014", "0.5965018", "0.595032", "0.5944794", "0.59317505", "0.5921967", "0.5909128", "0.58904785", "0.5868309", "0.58658874", "0.5832346", "0.5827956", "0.58141094", "0.5806408", "0.58017236", "0.57840246", "0.5780496", "0.57756734", "0.5774067", "0.57640517", "0.57620406", "0.57619715", "0.5736095", "0.57196784", "0.5716375", "0.5708114", "0.5707736", "0.5701117", "0.5694851", "0.56888634", "0.5675658", "0.5669671", "0.56667227", "0.56648785", "0.5663763", "0.56425154", "0.563048", "0.56258285", "0.5606742", "0.5603438", "0.559906", "0.55871344", "0.5580501", "0.55798644", "0.55759096", "0.5574033", "0.55724597", "0.5568283", "0.5564314", "0.5558864", "0.5556007", "0.5549902", "0.5545678", "0.5544895", "0.5542513", "0.55365556", "0.55296034", "0.5529412", "0.5529101", "0.5527764", "0.5527027", "0.5524592", "0.5500378", "0.54967684", "0.54958075", "0.5490906", "0.54908305", "0.5489015", "0.5487244", "0.548477", "0.54830235", "0.54797965", "0.54774886", "0.547655", "0.54736733", "0.5468822", "0.54684925", "0.5460433", "0.5441788", "0.5437441", "0.5436186", "0.54216564" ]
0.59283566
23
NewInterRegionTrafficQosQueue registers a new resource with the given unique name, arguments, and options.
func NewInterRegionTrafficQosQueue(ctx *pulumi.Context, name string, args *InterRegionTrafficQosQueueArgs, opts ...pulumi.ResourceOption) (*InterRegionTrafficQosQueue, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.Dscps == nil { return nil, errors.New("invalid value for required argument 'Dscps'") } if args.RemainBandwidthPercent == nil { return nil, errors.New("invalid value for required argument 'RemainBandwidthPercent'") } if args.TrafficQosPolicyId == nil { return nil, errors.New("invalid value for required argument 'TrafficQosPolicyId'") } opts = internal.PkgResourceDefaultOpts(opts) var resource InterRegionTrafficQosQueue err := ctx.RegisterResource("alicloud:cen/interRegionTrafficQosQueue:InterRegionTrafficQosQueue", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewQueue(ctx *pulumi.Context,\n\tname string, args *QueueArgs, opts ...pulumi.ResourceOption) (*Queue, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.HoursOfOperationArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'HoursOfOperationArn'\")\n\t}\n\tif args.InstanceArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InstanceArn'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Queue\n\terr := ctx.RegisterResource(\"aws-native:connect:Queue\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewQueue(qname string, taskId string) (*Queue, error) {\n q := &Queue{}\n q.StdoutChan = make(chan []byte, QUEUE_SIZE)\n q.StderrChan = make(chan []byte, QUEUE_SIZE)\n q.exitChan = make(chan string)\n q.finishChan = make(chan bool)\n\n s, err := aws.NewSqs(qname, taskId)\n q.awsSqs = s\n\n return q, err\n}", "func New(cfg Config, pubSub pubSub, metrics metricsProvider) (*Queue, error) {\n\tmsgChan, err := pubSub.SubscribeWithOpts(context.Background(), topic, spi.WithPool(cfg.PoolSize))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"subscribe to topic [%s]: %w\", topic, err)\n\t}\n\n\tq := &Queue{\n\t\tpubSub: pubSub,\n\t\tmsgChan: msgChan,\n\t\tjsonMarshal: json.Marshal,\n\t\tjsonUnmarshal: json.Unmarshal,\n\t\tmetrics: metrics,\n\t}\n\n\tq.Lifecycle = lifecycle.New(\"operation-queue\",\n\t\tlifecycle.WithStart(q.start),\n\t\tlifecycle.WithStop(q.stop),\n\t)\n\n\tq.Start()\n\n\treturn q, nil\n}", "func GetInterRegionTrafficQosQueue(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *InterRegionTrafficQosQueueState, opts ...pulumi.ResourceOption) (*InterRegionTrafficQosQueue, error) {\n\tvar resource InterRegionTrafficQosQueue\n\terr := ctx.ReadResource(\"alicloud:cen/interRegionTrafficQosQueue:InterRegionTrafficQosQueue\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewQueue(client redis.UniversalClient) Queue {\n\t// https://github.com/mperham/sidekiq/blob/e3839682a3d219b8a3708feab607c74241bc06b8/lib/sidekiq/client.rb#L190\n\tenqueueScript := redis.NewScript(`\n\tlocal sidekiq_ns = ARGV[1]\n\tlocal sidekiq_queue = ARGV[2]\n\n\tlocal queues_key = \"queues\"\n\tlocal queue_key = table.concat({\"queue\", sidekiq_queue}, \":\")\n\tif sidekiq_ns ~= \"\" then\n\t\tqueues_key = table.concat({sidekiq_ns, queues_key}, \":\")\n\t\tqueue_key = table.concat({sidekiq_ns, queue_key}, \":\")\n\tend\n\n\tlocal lpush_args = {}\n\n\tfor i = 3,table.getn(ARGV) do\n\t\tlocal jobm = ARGV[i]\n\n\t\t-- enqueue\n\t\ttable.insert(lpush_args, jobm)\n\tend\n\tredis.call(\"sadd\", queues_key, sidekiq_queue)\n\treturn redis.call(\"lpush\", queue_key, unpack(lpush_args))\n\t`)\n\n\tenqueueInScript := redis.NewScript(`\n\tlocal sidekiq_ns = ARGV[1]\n\tlocal schedule_key = \"schedule\"\n\tif sidekiq_ns ~= \"\" then\n\t\tschedule_key = table.concat({sidekiq_ns, schedule_key}, \":\")\n\tend\n\n\tlocal zadd_args = {}\n\n\tfor i = 2,table.getn(ARGV),2 do\n\t\tlocal at = tonumber(ARGV[i])\n\t\tlocal jobm = ARGV[i+1]\n\n\t\t-- enqueue\n\t\ttable.insert(zadd_args, at)\n\t\ttable.insert(zadd_args, jobm)\n\tend\n\treturn redis.call(\"zadd\", schedule_key, unpack(zadd_args))\n\t`)\n\n\t// https://github.com/mperham/sidekiq/blob/455e9d56f46f0299eaf3b761596207e15f906a39/lib/sidekiq/fetch.rb#L37\n\t// This improves OSS version of sidekiq and will not lose sidekiq jobs.\n\tdequeueScript := redis.NewScript(`\n\tlocal queue_ns = ARGV[1]\n\tlocal queue_id = ARGV[2]\n\n\tlocal queue_key = table.concat({queue_ns, queue_id}, \":\")\n\treturn redis.call(\"lindex\", queue_key, -1)\n\t`)\n\n\tackScript := redis.NewScript(`\n\tlocal queue_ns = ARGV[1]\n\tlocal queue_id = ARGV[2]\n\tlocal jobm = ARGV[3]\n\n\tlocal queue_key = table.concat({queue_ns, queue_id}, \":\")\n\treturn redis.call(\"lrem\", queue_key, -1, jobm)\n\t`)\n\n\tdequeueStartScript := redis.NewScript(`\n\tlocal sidekiq_ns = ARGV[1]\n\tlocal sidekiq_queue = ARGV[2]\n\tlocal queue_ns = ARGV[3]\n\tlocal queue_id = ARGV[4]\n\tlocal at = tonumber(ARGV[5])\n\tlocal expire_in_sec = tonumber(ARGV[6])\n\n\tlocal pullers_key = table.concat({queue_ns, \"pullers\"}, \":\")\n\tif redis.call(\"zadd\", pullers_key, \"nx\", at + expire_in_sec, queue_id) == 0 then\n\t\treturn 0\n\tend\n\tlocal puller_queue_key = table.concat({queue_ns, queue_id}, \":\")\n\tlocal old_queue_ids = redis.call(\"zrangebyscore\", pullers_key, \"-inf\", at, \"limit\", 0, 1)\n\tfor i, old_queue_id in pairs(old_queue_ids) do\n\t\tlocal old_puller_queue_key = table.concat({queue_ns, old_queue_id}, \":\")\n\t\tif redis.call(\"exists\", old_puller_queue_key) == 1 then\n\t\t\tredis.call(\"rename\", old_puller_queue_key, puller_queue_key)\n\t\tend\n\t\tredis.call(\"zrem\", pullers_key, old_queue_id)\n\t\treturn 1\n\tend\n\n\tlocal queue_key = table.concat({\"queue\", sidekiq_queue}, \":\")\n\tif sidekiq_ns ~= \"\" then\n\t\tqueue_key = table.concat({sidekiq_ns, queue_key}, \":\")\n\tend\n\tif redis.call(\"exists\", queue_key) == 1 then\n\t\tredis.call(\"rename\", queue_key, puller_queue_key)\n\tend\n\treturn 1\n\t`)\n\n\tdequeueStopScript := redis.NewScript(`\n\tlocal queue_ns = ARGV[1]\n\tlocal queue_id = ARGV[2]\n\n\tlocal puller_queue_key = table.concat({queue_ns, queue_id}, \":\")\n\tlocal pullers_key = table.concat({queue_ns, \"pullers\"}, \":\")\n\tif redis.call(\"llen\", puller_queue_key) == 0 then\n\t\tredis.call(\"del\", puller_queue_key)\n\t\treturn redis.call(\"zrem\", pullers_key, queue_id)\n\tend\n\treturn 0\n\t`)\n\n\tdequeueHeartbeatScript := redis.NewScript(`\n\tlocal queue_ns = ARGV[1]\n\tlocal queue_id = ARGV[2]\n\tlocal at = tonumber(ARGV[3])\n\tlocal expire_in_sec = tonumber(ARGV[4])\n\n\tlocal pullers_key = table.concat({queue_ns, \"pullers\"}, \":\")\n\treturn redis.call(\"zadd\", pullers_key, \"xx\", at + expire_in_sec, queue_id)\n\t`)\n\n\tscheduleScript := redis.NewScript(`\n\tlocal sidekiq_ns = ARGV[1]\n\tlocal at = tonumber(ARGV[2])\n\n\t-- move scheduled jobs\n\tlocal schedule_key = \"schedule\"\n\tlocal queues_key = \"queues\"\n\tif sidekiq_ns ~= \"\" then\n\t\tschedule_key = table.concat({sidekiq_ns, schedule_key}, \":\")\n\t\tqueues_key = table.concat({sidekiq_ns, queues_key}, \":\")\n\tend\n\n\tlocal zrem_args = redis.call(\"zrangebyscore\", schedule_key, \"-inf\", at)\n\tfor i, jobm in pairs(zrem_args) do\n\t\tlocal job = cjson.decode(jobm)\n\t\tlocal queue_key = table.concat({\"queue\", job.queue}, \":\")\n\t\tif sidekiq_ns ~= \"\" then\n\t\t\tqueue_key = table.concat({sidekiq_ns, queue_key}, \":\")\n\t\tend\n\t\tredis.call(\"sadd\", queues_key, job.queue)\n\t\tredis.call(\"lpush\", queue_key, jobm)\n\tend\n\tif table.getn(zrem_args) > 0 then\n\t\tredis.call(\"zrem\", schedule_key, unpack(zrem_args))\n\tend\n\treturn table.getn(zrem_args)\n\t`)\n\n\treturn &sidekiqQueue{\n\t\tRedisQueue: work.NewRedisQueue(client),\n\t\tclient: client,\n\t\tenqueueScript: enqueueScript,\n\t\tenqueueInScript: enqueueInScript,\n\t\tdequeueScript: dequeueScript,\n\t\tackScript: ackScript,\n\t\tdequeueStartScript: dequeueStartScript,\n\t\tdequeueStopScript: dequeueStopScript,\n\t\tdequeueHeartbeatScript: dequeueHeartbeatScript,\n\t\tscheduleScript: scheduleScript,\n\t}\n}", "func MyQueueConstructor() MyQueue {\n\treturn MyQueue{}\n}", "func NewQueue(id string, persistent bool, conn net.Conn) (Queue, error) {\n\tservice := broker.GetService(ServiceName).(*QueueService)\n\treturn service.newQueue(id, persistent, conn)\n}", "func newQueueMeta(conf *Conf) *queueMeta {\n\treturn &queueMeta{conf: conf}\n}", "func NewQueue() *Queue {\n return &Queue{member: make([]interface{}, 0)}\n}", "func NewQueue(l int) *Queue {\n\tif l == -1 {\n\t\treturn &Queue{\n\t\t\tQueue: make([]types.Event, 0),\n\t\t\tL: int(^uint(0) >> 1), // max integer value, architecture independent\n\t\t}\n\t}\n\tq := &Queue{\n\t\tQueue: make([]types.Event, 0, l),\n\t\tL: l,\n\t}\n\tlog.WithFields(log.Fields{\"Capacity\": q.L}).Debugf(\"Creating queue\")\n\treturn q\n}", "func (t *UseCase_UseCase_UseCase) NewQos(Qos string) (*UseCase_UseCase_UseCase_Qos, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Qos == nil {\n\t\tt.Qos = make(map[string]*UseCase_UseCase_UseCase_Qos)\n\t}\n\n\tkey := Qos\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Qos[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Qos\", key)\n\t}\n\n\tt.Qos[key] = &UseCase_UseCase_UseCase_Qos{\n\t\tQos: &Qos,\n\t}\n\n\treturn t.Qos[key], nil\n}", "func newExecQueue(capacity int) *execQueue {\n\tq := &execQueue{funcs: make([]func(), 0, capacity)}\n\tq.cond = syncPtr.NewCond(&q.mu)\n\tgo q.loop()\n\treturn q\n}", "func NewCfnQueue_Override(c CfnQueue, scope awscdk.Construct, id *string, props *CfnQueueProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_mediaconvert.CfnQueue\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Queues) NewQueue(Name string) (*OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Queue == nil {\n\t\tt.Queue = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Queue[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Queue\", key)\n\t}\n\n\tt.Queue[key] = &OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue{\n\t\tName: &Name,\n\t}\n\n\treturn t.Queue[key], nil\n}", "func NewQueue(\n\tservers []string,\n\topts QueueOptions,\n) (Queue, error) {\n\tq, err := newQueue(servers, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq.initConnections(servers)\n\tgo q.reportMetrics()\n\n\treturn q, nil\n}", "func (e *EnqueueRequestForNamespaces) Create(ctx context.Context, evt event.CreateEvent, q workqueue.RateLimitingInterface) {\n\te.add(ctx, evt.Object, q)\n}", "func New(name string, c config.Config) *Queue {\n\treturn &Queue{\n\t\tname: name,\n\t\tconf: c,\n\t}\n}", "func (t *Qos_Qos) NewQos(Id string) (*Qos_Qos_Qos, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Qos == nil {\n\t\tt.Qos = make(map[string]*Qos_Qos_Qos)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Qos[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Qos\", key)\n\t}\n\n\tt.Qos[key] = &Qos_Qos_Qos{\n\t\tId: &Id,\n\t}\n\n\treturn t.Qos[key], nil\n}", "func (t *Tap) initializeQos() error {\n\tt.Qos = &qos{}\n\tt.Qos.limit = strconv.FormatUint(defaultNetemLimit, 10)\n\tcmd := []string{\n\t\t\"tc\", \"qdisc\", \"add\", \"dev\", t.Name,\n\t\t\"root\", \"handle\", \"1:\", \"netem\", \"limit\", t.Qos.limit,\n\t}\n\treturn t.qosCmd(cmd)\n}", "func NewQueue(name string, itemType reflect.Type, maxQueueSize uint32) Queue {\n\tq := queue{\n\t\tname: name,\n\t\titemType: itemType,\n\t\tchannel: make(chan interface{}, maxQueueSize),\n\t}\n\treturn &q\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues) NewQueue(Name string) (*OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Queue == nil {\n\t\tt.Queue = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Queue[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Queue\", key)\n\t}\n\n\tt.Queue[key] = &OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue{\n\t\tName: &Name,\n\t}\n\n\treturn t.Queue[key], nil\n}", "func NewQueue(ch *amqp.Channel, n string) amqp.Queue {\n\tq, err := ch.QueueDeclare(\n\t\tn,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tnil,\n\t)\n\tfailOnError(err, \"Failed to declare a queue\")\n\treturn q\n}", "func (o InterRegionTrafficQosQueueOutput) InterRegionTrafficQosQueueName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringPtrOutput { return v.InterRegionTrafficQosQueueName }).(pulumi.StringPtrOutput)\n}", "func NewQueue(args []func(http.ResponseWriter, *http.Request) (http.ResponseWriter, *http.Request)) *Queue {\n\tq := &Queue{}\n\tfor _, f := range args {\n\t\tq.list = append(q.list, f)\n\t}\n\treturn q\n}", "func New(name string) (*Queue, error) {\n\tqueue := Queue{Name: name}\n\terr := queue.Init()\n\n\treturn &queue, err\n}", "func Constructor() MyQueue {\n\treturn MyQueue{}\n}", "func Constructor() MyQueue {\n\treturn MyQueue{}\n}", "func NewCfnQueue(scope awscdk.Construct, id *string, props *CfnQueueProps) CfnQueue {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnQueue{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_mediaconvert.CfnQueue\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func NewQueue(cap int) Queue {\n\treturn &queue{\n\t\tcap: cap,\n\t\thead: -1,\n\t\tdata: make([]interface{}, cap),\n\t\tlimit: int(^uint(0) >> 1), // max int\n\t}\n}", "func New(opt *Options) *Queue {\n\tif client == nil {\n\t\tredisOpt := &redis.Options{\n\t\t\tAddr: opt.Connection.Addr,\n\t\t\tPassword: opt.Connection.Password,\n\t\t\tDB: opt.Connection.DB,\n\t\t\tMaxRetries: opt.Connection.MaxRetries,\n\t\t\tDialTimeout: opt.Connection.DialTimeout,\n\t\t\tReadTimeout: opt.Connection.ReadTimeout,\n\t\t\tWriteTimeout: opt.Connection.WriteTimeout,\n\t\t\tPoolSize: opt.Connection.PoolSize,\n\t\t\tPoolTimeout: opt.Connection.PoolTimeout,\n\t\t\tIdleTimeout: opt.Connection.IdleTimeout,\n\t\t}\n\t\tclient = redis.NewClient(redisOpt)\n\t}\n\n\treturn &Queue{\n\t\tjobChannel: make(chan string, 1000),\n\t\tconcurrency: opt.Concurrency,\n\t\tqueueName: opt.QueueName,\n\t\tprocessor: opt.Processor,\n\t\terrorHandler: opt.ErrorHandler,\n\t}\n}", "func (service *SQSService) Create(attributes map[string]*string) (string, error) {\n\tinput := &sqs.CreateQueueInput{\n\t\tAttributes: attributes,\n\t\tQueueName: &service.QueueName,\n\t}\n\n\toutput, err := service.CreateQueue(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif output.QueueUrl == nil {\n\t\treturn \"\", errors.New(\"QueueUrl is null\")\n\t}\n\n\treturn *output.QueueUrl, nil\n}", "func Constructor() MyQueue {\n\treturn MyQueue{stack: NewStack()}\n}", "func createQueue(subID string) (queueUrl string, retErr error) {\n\n\t//Creo un service client SQS\n\tsvc := sqs.New(common.Sess)\n\n\t//Creo la coda\n\tresult, err := svc.CreateQueue(&sqs.CreateQueueInput{\n\t\tQueueName: aws.String(subID + \".fifo\"),\n\t\tAttributes: map[string]*string{\n\t\t\t\"MessageRetentionPeriod\": \taws.String(\"345600\"),\n\t\t\t\"ReceiveMessageWaitTimeSeconds\": \taws.String(strconv.FormatInt(common.Config.PollingTime, 10)),\n\t\t\t\"FifoQueue\":\t\t\t\t\t\taws.String(\"true\"),\t\t//Coda FIFO\n\t\t},\n\t})\n\tif err != nil {\n\t\tcommon.Warning(\"[BROKER] Errore nella creazione della coda\\n\" + err.Error())\n\t\treturn \"\", err\n\t}\n\n\tcommon.Info(\"[BROKER] Coda creata con successo all'URL \" + *result.QueueUrl)\n\n\treturn *result.QueueUrl, nil\n}", "func (t *OpenconfigQos_Qos_Queues) NewQueue(Name string) (*OpenconfigQos_Qos_Queues_Queue, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Queue == nil {\n\t\tt.Queue = make(map[string]*OpenconfigQos_Qos_Queues_Queue)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Queue[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Queue\", key)\n\t}\n\n\tt.Queue[key] = &OpenconfigQos_Qos_Queues_Queue{\n\t\tName: &Name,\n\t}\n\n\treturn t.Queue[key], nil\n}", "func New(\n\tlogger *zap.SugaredLogger,\n\tflushFunc, closeFunc func(),\n\topts Options,\n) *Queue {\n\tif flushFunc == nil {\n\t\tflushFunc = func() {}\n\t}\n\tif closeFunc == nil {\n\t\tcloseFunc = func() {}\n\t}\n\tif opts.Rate == 0 {\n\t\topts.Rate = 5 * time.Second\n\t}\n\n\tvar counter = int32(0)\n\treturn &Queue{\n\t\tl: logger,\n\n\t\tcloseFunc: closeFunc,\n\t\tflushFunc: flushFunc,\n\n\t\tpendingC: make(chan func(), 3*opts.BatchSize),\n\t\tpending: &counter,\n\t\trate: opts.Rate,\n\t\tbatchSize: opts.BatchSize,\n\n\t\tstopC: make(chan bool, 1),\n\t\tstopped: false,\n\t}\n}", "func NewBounded(capacity int) IntStack {\n\tq := &BoundedQueue{capacity: capacity}\n\tq.hasSpace = sync.NewCond(q)\n\tq.hasItems = sync.NewCond(q)\n\treturn q\n}", "func NewQueue(action WorkAction, options ...QueueOption) *Queue {\n\tq := Queue{\n\t\tLatch: NewLatch(),\n\t\tAction: action,\n\t\tContext: context.Background(),\n\t\tMaxWork: DefaultQueueMaxWork,\n\t\tParallelism: runtime.NumCPU(),\n\t}\n\tfor _, option := range options {\n\t\toption(&q)\n\t}\n\treturn &q\n}", "func New(hint int) *Queue {\n\treturn &Queue{\n\t\titems: make([]interface{}, 0, hint),\n\t}\n}", "func NewPriorityQueue(inCh <-chan *pb.Flow, outCh chan<- *pb.Flow) {\n\tt := time.NewTicker(time.Second)\n\t// TODO write logic to return flows depending in the number of flows\n\t// received per second. (i.e., if we receive 100 flows/s and we are not receiving\n\t// 1 flow/s we should keep returning 100 flows/s and decreasing the number\n\t// of flows/s until we reach 1 flow/s\n\tNewPriorityQueueWith(inCh, outCh, t.C)\n}", "func NewQueue(cap int) *Queue {\n\treturn &Queue{\n\t\tnodes: make([]*Node, cap),\n\t\tcap: cap,\n\t\tlength: 0,\n\t\thead: 0,\n\t\ttail: 0,\n\t}\n}", "func (service *ContrailService) CreateQosQueue(\n\tctx context.Context,\n\trequest *models.CreateQosQueueRequest) (*models.CreateQosQueueResponse, error) {\n\tmodel := request.QosQueue\n\tif model.UUID == \"\" {\n\t\tmodel.UUID = uuid.NewV4().String()\n\t}\n\tauth := common.GetAuthCTX(ctx)\n\tif auth == nil {\n\t\treturn nil, common.ErrorUnauthenticated\n\t}\n\n\tif model.FQName == nil {\n\t\tif model.DisplayName != \"\" {\n\t\t\tmodel.FQName = []string{auth.DomainID(), auth.ProjectID(), model.DisplayName}\n\t\t} else {\n\t\t\tmodel.FQName = []string{auth.DomainID(), auth.ProjectID(), model.UUID}\n\t\t}\n\t}\n\tmodel.Perms2 = &models.PermType2{}\n\tmodel.Perms2.Owner = auth.ProjectID()\n\tif err := common.DoInTransaction(\n\t\tservice.DB,\n\t\tfunc(tx *sql.Tx) error {\n\t\t\treturn db.CreateQosQueue(ctx, tx, request)\n\t\t}); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"resource\": \"qos_queue\",\n\t\t}).Debug(\"db create failed on create\")\n\t\treturn nil, common.ErrorInternal\n\t}\n\treturn &models.CreateQosQueueResponse{\n\t\tQosQueue: request.QosQueue,\n\t}, nil\n}", "func New(opts Options) (*Queue, error) {\n\tif opts.HardLimit <= 0 || opts.HardLimit < opts.SoftQuota {\n\t\treturn nil, errHardLimit\n\t}\n\tif opts.BurstCredit < 0 {\n\t\treturn nil, errBurstCredit\n\t}\n\tif opts.SoftQuota <= 0 {\n\t\topts.SoftQuota = opts.HardLimit\n\t}\n\tif opts.BurstCredit == 0 {\n\t\topts.BurstCredit = float64(opts.SoftQuota)\n\t}\n\tsentinel := new(entry)\n\tq := &Queue{\n\t\tsoftQuota: opts.SoftQuota,\n\t\thardLimit: opts.HardLimit,\n\t\tcredit: opts.BurstCredit,\n\t\tback: sentinel,\n\t\tfront: sentinel,\n\t}\n\tq.nempty = sync.NewCond(&q.mu)\n\treturn q, nil\n}", "func newQuotaPool(q int) *quotaPool {\n\tqp := &quotaPool{\n\t\tacquireChannel: make(chan int, 1),\n\t}\n\tif q > 0 {\n\t\tqp.acquireChannel <- q\n\t} else {\n\t\tqp.quota = q\n\t}\n\treturn qp\n}", "func NewQueue(queueCapacity int) (*Queue, error) {\n\tif queueCapacity < 0 {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"negative capacity value: %d\", queueCapacity)\n\t}\n\n\tdata := make([]interface{}, 0, queueCapacity)\n\n\treturn &Queue{\n\t\tdata: data,\n\t}, nil\n}", "func NewQueue(client *elastic.Client, options ...Option) *Queue {\n\tqueue := &Queue{\n\t\terrorHandler: defaultErrorHandler,\n\t\tcloser: make(chan struct{}),\n\t\ttimeout: time.Second * 5,\n\t}\n\n\tfor _, option := range options {\n\t\toption(queue)\n\t}\n\n\tif queue.requester == nil {\n\t\tqueue.requester = &ClientRequester{Client: client, Timeout: queue.timeout}\n\t}\n\n\tif len(queue.conditions) == 0 {\n\t\tpanic(\"mixer/elasticqueue: write conditions were passed, the client will buffer \" +\n\t\t\t\"infinitely! Use WithCondition() to pass one or more options to NewQueue()\")\n\t}\n\n\tgo queue.listenToConditions()\n\n\treturn queue\n}", "func New() Queue {\n\tc := make(chan uint16, size)\n\treturn Queue(c)\n}", "func (client *Client) CreateQueueWithAttributes(name string, attributes CreateQueueAttributes) (string, error) {\n\tvar parsedResponse CreateQueueResult\n\turl := buildCreateQueueURL(client.EndPointURL, name, attributes)\n\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn \"\", errors.New(string(body))\n\t}\n\n\terr = xml.Unmarshal(body, &parsedResponse)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn parsedResponse.QueueURL, nil\n}", "func newBalanceRegionScheduler(opController *schedule.OperatorController, opts ...BalanceRegionCreateOption) schedule.Scheduler {\n\tbase := newBaseScheduler(opController)\n\ts := &balanceRegionScheduler{\n\t\tbaseScheduler: base,\n\t\topController: opController,\n\t}\n\tfor _, opt := range opts {\n\t\topt(s)\n\t}\n\treturn s\n}", "func New() *APQ {\n\treturn &APQ{\n\t\th: &itemHeap{},\n\t\tlocations: make(map[interface{}]*item),\n\t}\n}", "func (ooc *MockOpenoltClient) CreateTrafficQueues(ctx context.Context, in *tech_profile.TrafficQueues, opts ...grpc.CallOption) (*openolt.Empty, error) {\n\treturn &openolt.Empty{}, nil\n}", "func NewRegionAutoscaler(ctx *pulumi.Context,\n\tname string, args *RegionAutoscalerArgs, opts ...pulumi.ResourceOption) (*RegionAutoscaler, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Region == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Region'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"project\",\n\t\t\"region\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource RegionAutoscaler\n\terr := ctx.RegisterResource(\"google-native:compute/v1:RegionAutoscaler\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func newQueue(size int) metricQueue {\n\treturn metricQueue{elt: make([]MetricElt, size), start: 0, currentSize: 0, size: size}\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Output_Queues) NewQueue(Name string) (*OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Queue == nil {\n\t\tt.Queue = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Queue[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Queue\", key)\n\t}\n\n\tt.Queue[key] = &OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue{\n\t\tName: &Name,\n\t}\n\n\treturn t.Queue[key], nil\n}", "func Constructor() MyQueue {\n\treturn MyQueue{sIn: newStack(), sOut: newStack()}\n}", "func (c *restClient) CreateQueue(ctx context.Context, req *cloudtaskspb.CreateQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) {\n\tm := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}\n\tbody := req.GetQueue()\n\tjsonReq, err := m.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v2beta3/%v/queues\", req.GetParent())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"parent\", url.QueryEscape(req.GetParent()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).CreateQueue[0:len((*c.CallOptions).CreateQueue):len((*c.CallOptions).CreateQueue)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &cloudtaskspb.Queue{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"POST\", baseUrl.String(), bytes.NewReader(jsonReq))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (service *ContrailService) RESTCreateQosQueue(c echo.Context) error {\n\trequestData := &models.CreateQosQueueRequest{}\n\tif err := c.Bind(requestData); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"resource\": \"qos_queue\",\n\t\t}).Debug(\"bind failed on create\")\n\t\treturn echo.NewHTTPError(http.StatusBadRequest, \"Invalid JSON format\")\n\t}\n\tctx := c.Request().Context()\n\tresponse, err := service.CreateQosQueue(ctx, requestData)\n\tif err != nil {\n\t\treturn common.ToHTTPError(err)\n\t}\n\treturn c.JSON(http.StatusCreated, response)\n}", "func New(ctx context.Context, cfg models.Config) (*Queue, error) {\n\tconn, err := connect(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to connect to RabbitMQ \")\n\t}\n\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to open a channel \")\n\t}\n\n\t_, err = ch.QueueDeclare(\"ItemQueue\", false, false, false, false, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to declare a queue \")\n\t}\n\n\treturn &Queue{ch, conn}, nil\n}", "func ConstructTimeoutQueue( workers int ) chan *packet_metadata {\n\n timeoutQueue := make(chan *packet_metadata, 1000000)\n return timeoutQueue\n}", "func NewQueue(storage Storage, reQueueTimeout time.Duration) Queue {\n\tif reQueueTimeout < 1 {\n\t\treQueueTimeout = time.Minute * 30\n\t}\n\n\tname := \"gocelery\"\n\tq := &queue{\n\t\tstorage: storage,\n\t\thead: 0,\n\t\ttail: 0,\n\t\trequeueTimeout: reQueueTimeout,\n\t\tqueuePrefix: fmt.Sprintf(\"%s-queue-\", name),\n\t\tqueueAckPrefix: fmt.Sprintf(\"%s-ack-\", name),\n\t}\n\n\t// restore the old state from the DB\n\tq.loadHeadTail()\n\treturn q\n}", "func Constructor() MyQueue {\n\treturn MyQueue{\n\t\tin: New(),\n\t\tout: New(),\n\t}\n}", "func New(ctx context.Context, rate, timespan int) (Bucket, error) {\n\tq := make(chan struct{}, rate)\n\tb := Bucket{ctx: ctx, queue: q, rate: rate, timespan: timespan}\n\tgo b.leak()\n\treturn b, nil // maybe return pointer?\n}", "func New(cfg config.Queue, n notifier) *Queue {\n\tq := &Queue{\n\t\taddCh: make(chan struct{}, cfg.QueueSize),\n\t\tpopCh: make(chan struct{}, cfg.GoRoutinesSize),\n\t\taddMessage: make(chan entity.NotifierMessage, 1),\n\t\tpopMessage: make(chan entity.NotifierMessage, 1),\n\t\tnotifier: n,\n\t}\n\n\tgo q.pop()\n\tgo q.add()\n\n\treturn q\n}", "func newEventQ(conf *config.Config) *eventQ {\n\tq := &eventQ{\n\t\tconf: conf,\n\t\tStats: internal.NewStats(),\n\t\tin: make(chan *protocol.Request, 1000),\n\t\tstopC: make(chan error),\n\t\tshutdownC: make(chan error, 1),\n\t\tpartArgBuf: newPartitionArgList(conf.MaxPartitions),\n\t\tbatchScanner: protocol.NewBatchScanner(conf, nil),\n\t\ttmpBatch: protocol.NewBatch(conf),\n\t\tflushState: newFlushState(conf),\n\t\tconfResp: protocol.NewConfigResponse(conf),\n\t}\n\n\treturn q\n}", "func NewQueue(size int) *Queue {\r\n\treturn &Queue{\r\n\t\tnodes: make([]*Cust, size),\r\n\t\tsize: size,\r\n\t}\r\n}", "func (o InterRegionTrafficQosQueueOutput) InterRegionTrafficQosQueueDescription() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringPtrOutput {\n\t\treturn v.InterRegionTrafficQosQueueDescription\n\t}).(pulumi.StringPtrOutput)\n}", "func New[Item any](capacity int) *PubSub[Item] {\n\tps := &PubSub[Item]{\n\t\tcmdChan: make(chan cmd[Item], 0),\n\t\tmsgChan: make(chan msgenvelope[Item], capacity),\n\t\tcapacity: capacity,\n\t}\n\tgo ps.start()\n\treturn ps\n}", "func (client QuotaRequestClient) CreatePreparer(ctx context.Context, subscriptionID string, providerID string, location string, resourceName string, createQuotaRequest CurrentQuotaLimitBase, ifMatch string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"location\": autorest.Encode(\"path\", location),\n\t\t\"providerId\": autorest.Encode(\"path\", providerID),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", subscriptionID),\n\t}\n\n\tconst APIVersion = \"2019-07-19-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsPut(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/providers/Microsoft.Capacity/resourceProviders/{providerId}/locations/{location}/serviceLimits/{resourceName}\", pathParameters),\n\t\tautorest.WithJSON(createQuotaRequest),\n\t\tautorest.WithQueryParameters(queryParameters),\n\t\tautorest.WithHeader(\"If-Match\", autorest.String(ifMatch)))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func newQueueService(c *orgbot.Config) (*queueService, error) {\n\tsess, err := cmd.NewAWSSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &queueService{\n\t\tconfig: c,\n\t\tsqsClient: sqs.New(sess),\n\t}, nil\n\n}", "func New(callback func(interface{}), duration time.Duration) *Queue {\r\n\treturn &Queue{\r\n\t\tm: make(map[interface{}]*element),\r\n\t\tduration: duration,\r\n\t\tcb: callback,\r\n\t}\r\n}", "func (client QuotaRequestClient) Create(ctx context.Context, subscriptionID string, providerID string, location string, resourceName string, createQuotaRequest CurrentQuotaLimitBase, ifMatch string) (result QuotaRequestCreateFuture, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/QuotaRequestClient.Create\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response() != nil {\n\t\t\t\tsc = result.Response().StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.CreatePreparer(ctx, subscriptionID, providerID, location, resourceName, createQuotaRequest, ifMatch)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"reservations.QuotaRequestClient\", \"Create\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresult, err = client.CreateSender(req)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"reservations.QuotaRequestClient\", \"Create\", result.Response(), \"Failure sending request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func NewQueue() *queue {\n q := new(queue)\n q.head = new(task)\n q.tail = q.head\n\treturn q\n}", "func (t *Application_Application_Application) NewQos(Qos string) (*Application_Application_Application_Qos, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Qos == nil {\n\t\tt.Qos = make(map[string]*Application_Application_Application_Qos)\n\t}\n\n\tkey := Qos\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Qos[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Qos\", key)\n\t}\n\n\tt.Qos[key] = &Application_Application_Application_Qos{\n\t\tQos: &Qos,\n\t}\n\n\treturn t.Qos[key], nil\n}", "func NewQueue(name string) *Queue {\n\tredisClient := GetRedisClientFromConfig()\n\tqueue := &Queue{Name: name, RedisClient: redisClient}\n\treturn queue\n}", "func NewQueue() Queue {\n\treturn Queue{}\n}", "func CreateStackResources(stackID string, subscription dynamodb.APISubscription) error {\n\n\t// Create a new CloudFormation template\n\ttemplate := cloudformation.NewTemplate()\n\n\t//Generate GUID\n\tid := stackID\n\n\ttags := []tags.Tag{\n\t\ttags.Tag{\n\t\t\tKey: \"Product\",\n\t\t\tValue: \"MaxEdge\",\n\t\t},\n\t\t// tags.Tag{\n\t\t// \tKey: \"Subscription_ID\",\n\t\t// \tValue: subscription.Name,\n\t\t// },\n\t}\n\n\t// AWS ECS Prpoperties\n\tvarRequiresCompatibilities := []string{\"FARGATE\"}\n\n\t// Lambda Environment Variables //\n\n\t// AWS Account ID\n\tvar varAwsAccountID = os.Getenv(\"AWS_ACCOUNT_ID\")\n\n\t// Task Definition\n\tvar varExecutionRoleArn = os.Getenv(\"EXECUTION_ROLE\")\n\tvar varTaskRoleArn = os.Getenv(\"TASK_ROLE\")\n\tvar varEcsTaskDefinitionRef = os.Getenv(\"CLOUDFORMATION_TASK_DEFINITION_REF\")\n\n\t// Container Definition\n\tvar varImage = os.Getenv(\"CONTAINER_IMAGE\")\n\n\t//Network Definition\n\tvar varSecurityGroup = os.Getenv(\"SECURITY_GROUP\")\n\tvar varSubnet1 = os.Getenv(\"SUBNET_1\")\n\tvar varSubnet2 = os.Getenv(\"SUBNET_2\")\n\tvar varSubnet3 = os.Getenv(\"SUBNET_3\")\n\n\t//ECS Service\n\tvar varClusterName = os.Getenv(\"CLUSTER_NAME\")\n\tvar varEcsRef = os.Getenv(\"CLOUDFORMATION_ECS_SERVICE_REF\")\n\n\t//Secret\n\tvar varSecretRef = os.Getenv(\"CLOUDFORMATION_SECRET_REF\")\n\n\t// Create IAM User\n\ttemplate.Resources[\"IAMUSER\"] = &iam.User{\n\t\tUserName: string(id),\n\t\tTags: tags,\n\t}\n\n\t// Assigning the subscribers ID to a string so it can be added to the policy\n\tbucket := fmt.Sprintf(\"\\\"arn:aws:s3:::maxedgecloudtocloudpoc-sandbox/%s/*\\\"\", id)\n\tvar roleName string = \"ROLE_\" + id\n\tvar policyName string = \"Policy\" + id\n\n\t// S3 GetObject policy for the created IAM user for a subscription\n\t// User will assume the role\n\t// Action is to Assume the sts role\n\ttemplate.Resources[\"IAMPolicy\"] = &iam.Policy{\n\t\tPolicyName: policyName,\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"sts:AssumeRole\\\",\\\"Resource\\\":\\\"arn:aws:iam::\" + varAwsAccountID + \":role/\" + roleName + \"\\\"}]}\"),\n\t\tUsers: []string{id},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t}\n\n\tp := iam.Role_Policy{\n\t\tPolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:GetObject\\\",\\\"Resource\\\":\" + bucket + \"}]}\"),\n\t\tPolicyName: id,\n\t}\n\n\t// Assume Role or Trust Policy\n\ttemplate.Resources[\"IAMROLE\"] = &iam.Role{\n\t\tAssumeRolePolicyDocument: (\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\": \\\"arn:aws:iam::\" + varAwsAccountID + \":user/\" + id + \"\\\"},\\\"Action\\\":[\\\"sts:AssumeRole\\\"]}]}\"),\n\t\tRoleName: roleName,\n\t\tPolicies: []iam.Role_Policy{p},\n\t\tAWSCloudFormationDependsOn: []string{\"IAMUSER\"},\n\t\tTags: tags,\n\t}\n\n\t// Task Definition Secret - sets the value for the container based on what was\n\t// created in the template.\n\tTaskDefSecret := []ecs.TaskDefinition_Secret{}\n\tvarTaskDefSecret := ecs.TaskDefinition_Secret{\n\t\t//Referance to the ARNs created when the secret is created\n\t\tName: cloudformation.Ref(varSecretRef),\n\t\tValueFrom: cloudformation.Ref(varSecretRef),\n\t}\n\tTaskDefSecret = append(TaskDefSecret, varTaskDefSecret)\n\n\t// TargetName come from the DynamoDB table and stores the cloud platform\n\t// endpoint for the data destination\n\tgroup := \"/MaxEdge/CloudToCloud/\" + subscription.Target\n\n\tcwLog := &ecs.TaskDefinition_LogConfiguration{\n\t\tLogDriver: \"awslogs\",\n\t\tOptions: map[string]string{\"awslogs-create-group\": \"true\", \"awslogs-group\": group, \"awslogs-region\": \"us-east-1\", \"awslogs-stream-prefix\": id},\n\t}\n\n\t//Task Definition Container Definition - Setting properties\n\tTaskDefConDef := []ecs.TaskDefinition_ContainerDefinition{}\n\tvarTaskDef := ecs.TaskDefinition_ContainerDefinition{\n\t\tImage: varImage,\n\t\tName: id,\n\t\tSecrets: TaskDefSecret,\n\t\tLogConfiguration: cwLog,\n\t}\n\tTaskDefConDef = append(TaskDefConDef, varTaskDef)\n\n\t// Create an Amazon ECS Task Definition - Setting properties\n\ttemplate.Resources[varEcsTaskDefinitionRef] = &ecs.TaskDefinition{\n\t\tExecutionRoleArn: varExecutionRoleArn,\n\t\tTaskRoleArn: varTaskRoleArn,\n\t\tMemory: \"1024\",\n\t\tNetworkMode: \"awsvpc\",\n\t\tRequiresCompatibilities: varRequiresCompatibilities,\n\t\tCpu: \"512\",\n\t\tContainerDefinitions: TaskDefConDef,\n\t\tTags: tags,\n\t}\n\n\t// ECS Service Network configuration\n\tsnc := &ecs.Service_NetworkConfiguration{\n\t\tAwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{\n\n\t\t\t// Required to access ECR\n\t\t\tAssignPublicIp: \"ENABLED\",\n\t\t\t// The Security Group needs to allow traffic via port :443\n\t\t\tSecurityGroups: []string{varSecurityGroup},\n\t\t\tSubnets: []string{varSubnet1, varSubnet2, varSubnet3},\n\t\t},\n\t}\n\n\t// Create Amazon ECS Service\n\ttemplate.Resources[varEcsRef] = &ecs.Service{\n\t\tLaunchType: \"FARGATE\",\n\t\tCluster: varClusterName,\n\t\tTaskDefinition: cloudformation.Ref(varEcsTaskDefinitionRef),\n\t\tServiceName: id,\n\t\tDesiredCount: 1,\n\t\tNetworkConfiguration: snc,\n\t\tSchedulingStrategy: \"REPLICA\",\n\t\tTags: tags,\n\t\tPropagateTags: \"TASK_DEFINITION\",\n\t}\n\n\t// Create an Amazon Secret\n\ttemplate.Resources[varSecretRef] = &secretsmanager.Secret{\n\t\tName: id,\n\t\tDescription: \"Metadata for companies\",\n\t\tTags: tags,\n\t}\n\n\t// Get JSON form of AWS CloudFormation template\n\tj, err := template.JSON()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to generate JSON: %s\\n\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"Template creation for %s Done.\\n\", id)\n\tfmt.Println(\"=====\")\n\tfmt.Println(\"Generated template:\")\n\tfmt.Printf(\"%s\\n\", string(j))\n\tfmt.Println(\"=====\")\n\n\t// Initialize a session that the SDK uses to load\n\t// credentials from the shared credentials file ~/.aws/credentials\n\t// and configuration from the shared configuration file ~/.aws/config.\n\t// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/\n\tsess := session.Must(session.NewSessionWithOptions(session.Options{\n\t\tSharedConfigState: session.SharedConfigEnable,\n\t}))\n\n\t// Create the stack\n\terr = createStackFromBody(sess, j, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewTaskQueue(syncFn func(string) error) *taskQueue {\n\treturn &taskQueue{\n\t\tqueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),\n\t\tsync: syncFn,\n\t\tworkerDone: make(chan struct{}),\n\t}\n}", "func CreateNew(val interface{}) (*Queue, error) {\r\n\treturn &Queue{\r\n\t\tQueueList: []interface{}{val},\r\n\t}, nil\r\n}", "func newZmqBUF(\n\tchannel chan metric.Metric,\n\tinitialInterval int,\n\tinitialBufferSize int,\n\tinitialTimeout time.Duration,\n\tlog *l.Entry) Handler {\n\tinst := new(ZmqBUF)\n\tinst.name = \"ZmqBUF\"\n\tinst.interval = initialInterval\n\tinst.maxBufferSize = initialBufferSize\n\tinst.timeout = initialTimeout\n\tinst.log = log\n\tinst.channel = channel\n\n\treturn inst\n}", "func NewWithCapacity(workers, capacity int) Interface {\n\ti, _ := NewWithContext(context.Background(), workers, capacity)\n\treturn i\n}", "func New() *Queue {\r\n\treturn &Queue{nil,nil,0}\r\n}", "func New(ctx context.Context, servsHandler services.Handler) Queue {\n\tqueue := &senderWorkQueue{\n\t\tmainCtx: ctx,\n\t\twakeUp: make(chan int),\n\t\tqueue: map[string]*openapi.Event{},\n\t\tservsHandler: servsHandler,\n\t}\n\n\tgo queue.work()\n\n\treturn queue\n}", "func createQueue(t *testing.T, connectionString string, queueProperties *QueueProperties) (string, func()) {\n\tnanoSeconds := time.Now().UnixNano()\n\tqueueName := fmt.Sprintf(\"queue-%X\", nanoSeconds)\n\n\tadminClient, err := NewAdminClientWithConnectionString(connectionString, nil)\n\trequire.NoError(t, err)\n\n\tif queueProperties == nil {\n\t\tqueueProperties = &QueueProperties{}\n\t}\n\n\tqueueProperties.Name = queueName\n\t_, err = adminClient.AddQueueWithProperties(context.Background(), queueProperties)\n\trequire.NoError(t, err)\n\n\treturn queueName, func() {\n\t\tif _, err := adminClient.DeleteQueue(context.TODO(), queueProperties.Name); err != nil {\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t}\n}", "func Constructor() MyQueue {\n\treturn Myqueue{list: listNew()}\n}", "func New(priority Priority, tag string) (*Writer, error) {}", "func newNamespaceIndexInsertQueue(\n\tindexBatchFn nsIndexInsertBatchFn,\n\tnamespaceMetadata namespace.Metadata,\n\tnowFn clock.NowFn,\n\tscope tally.Scope,\n) namespaceIndexInsertQueue {\n\tsubscope := scope.SubScope(\"insert-queue\")\n\tq := &nsIndexInsertQueue{\n\t\tnamespaceMetadata: namespaceMetadata,\n\t\tindexBatchBackoff: defaultIndexBatchBackoff,\n\t\tindexPerSecondLimit: defaultIndexPerSecondLimit,\n\t\tindexBatchFn: indexBatchFn,\n\t\tnowFn: nowFn,\n\t\tsleepFn: time.Sleep,\n\t\tnotifyInsert: make(chan struct{}, 1),\n\t\tcloseCh: make(chan struct{}, 1),\n\t\tmetrics: newNamespaceIndexInsertQueueMetrics(subscope),\n\t}\n\tq.currBatch = q.newBatch()\n\treturn q\n}", "func NewGCPPubSubQueue(ctx context.Context, logger logger.Logger, projectID, topicName string) (*GCPPubSubQueue, error) {\n\tq := &GCPPubSubQueue{logger: logger}\n\n\tif projectID == \"\" {\n\t\treturn nil, errors.New(\"projectID must not be empty\")\n\t}\n\n\t// create a context with a timeout for exclusive use of connection setup to\n\t// ensure connnection setup doesn't block and can fail early.\n\tcxnCtx, cancel := context.WithTimeout(ctx, cxnTimeout)\n\tdefer cancel()\n\n\tclient, err := pubsub.NewClient(cxnCtx, projectID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not create client\")\n\t}\n\n\tif topicName == \"\" {\n\t\ttopicName = defaultTopicName\n\t}\n\ttopicName += \"-v\" + version\n\n\tlogger.Infof(\"creating topic %q\", topicName)\n\tq.topic, err = client.CreateTopic(cxnCtx, topicName)\n\tif code := grpc.Code(err); code != codes.OK && code != codes.AlreadyExists {\n\t\treturn nil, errors.Wrap(err, \"could not create topic\")\n\t}\n\n\tsubName := topicName + \"-\" + defaultSubName\n\n\tlogger.Infof(\"creating subscription %q\", subName)\n\tq.subscription, err = client.CreateSubscription(cxnCtx, subName, pubsub.SubscriptionConfig{\n\t\tTopic: q.topic,\n\t\tAckDeadline: 0,\n\t})\n\tif code := grpc.Code(err); code != codes.OK && code != codes.AlreadyExists {\n\t\treturn nil, errors.Wrap(err, \"could not create subscription\")\n\t}\n\n\tq.subscription.ReceiveSettings.MaxOutstandingMessages = 1 // limit concurrency\n\n\treturn q, nil\n}", "func NewQueue(maximumCapacity int, initialCapacity int, factory TokenFactory) *Queue {\n\tq := &Queue{\n\t\tmaxCapacity: maximumCapacity,\n\t\tavailableTokens: make(chan (Token), maximumCapacity),\n\t\tcommittedTokens: make(chan (Token), maximumCapacity),\n\t\tdiscardTokens: make(chan (Token), maximumCapacity),\n\t\tcloseTokens: make(chan (Token)),\n\t}\n\n\tfor i := 0; i < maximumCapacity; i++ {\n\t\ttoken := factory()\n\t\tif token == nil {\n\t\t\treturn nil\n\t\t}\n\t\tq.discardTokens <- token\n\t\tq.validTokens = append(q.validTokens, token)\n\t}\n\n\tq.EnableDisableTokens(initialCapacity)\n\n\treturn q\n}", "func New(region string, config *ReadConfig, logger machine.Logger) (machine.Subscription, error) {\n\ts := session.Must(session.NewSession())\n\tsvc := ps.New(s, aws.NewConfig().WithRegion(region))\n\n\treturn &sqs{\n\t\tsubscription: svc,\n\t\tconfig: config,\n\t\tlogger: logger,\n\t}, nil\n}", "func newQueue() *Queue {\n\tl := list.New()\n\treturn &Queue{Elements: l}\n}", "func newScanQueue() *scanQueue {\n\tsq := &scanQueue{}\n\tsq.baseQueue = newBaseQueue(\"scan\", sq.shouldQueue, sq.process, scanQueueMaxSize)\n\treturn sq\n}", "func (T *ThreeParDriver) CreateQoSRules(requestId, targetName string, targetType int8, qosRules map[string]interface{}) (err error) {\n\trequest := map[string]interface{}{\"name\": targetName, \"type\": targetType}\n\tif qosRules != nil {\n\t\tfor k, v := range qosRules {\n\t\t\trequest[k] = v\n\t\t}\n\t}\n\tjsonBytes, err := json.Marshal(request)\n\tif err != nil {\n\t\tlogger.Log.Error1(requestId, \"Failed to marshal json:\", err)\n\t\treturn\n\t}\n\trequestUrl := fmt.Sprintf(\"%s/qos\", T.ServerPath)\n\treq, err := http.NewRequest(\"POST\", requestUrl, bytes.NewReader(jsonBytes))\n\tif err != nil {\n\t\tlogger.Log.Error1(requestId, \"NewRequest error:\", err)\n\t\treturn\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(sessionCookieName, T.SessionKey)\n\tlogger.Log.Info1(requestId, \"CreateQoSRules Request to three_par:\", requestUrl)\n\tresp, err := T.HttpClient.Do(req)\n\tif err != nil {\n\t\tlogger.Log.Error1(requestId, \"Failed to request three_par:\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 201 {\n\t\tresult, err := checkHttpResponseOfSessionKey(resp)\n\t\tif result {\n\t\t\terr = T.InitSessionKey()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.Error1(requestId, \"Failed to init three_par:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = T.CreateQoSRules(requestId, targetName, targetType, qosRules)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.Error1(requestId, \"Failed to CreateQoSRules:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tvar response HttpResponseBody\n\t\t\terr = readJsonBody(resp.Body, &response)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log.Error1(requestId, \"ReadJsonBody error:\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlogger.Log.Info1(requestId, \"Failed to create QoSRules,three_par response:\", response.String())\n\n\t\t\tif response.Code == ExistentQoSRule {\n\t\t\t\treturn ErrQoSRuleExistent\n\t\t\t}\n\n\t\t\terr = errors.New(\"Failed to create QoSRules,three_par response:\" + response.String())\n\t\t\treturn err\n\t\t}\n\t}\n\treturn\n}", "func newCQT(sz, maxSz int) *cQT {\n\tif sz <= 0 || uint32(sz)&(uint32(sz)-1) != 0 ||\n\t\tuint32(maxSz)&(uint32(maxSz)-1) != 0 ||\n\t\tmaxSz < sz {\n\t\tpanic(\"Invalid Q size\")\n\t}\n\tcq := &cQT{\n\t\tsz: uint32(sz), maxSz: uint32(maxSz),\n\t\tm: uint32(sz) - 1,\n\t\ts: 0, e: 0,\n\t}\n\tcq.b = make([]T, sz)\n\treturn cq\n}", "func NewTask(ctx *pulumi.Context,\n\tname string, args *TaskArgs, opts ...pulumi.ResourceOption) (*Task, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.QueueId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'QueueId'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"location\",\n\t\t\"project\",\n\t\t\"queueId\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Task\n\terr := ctx.RegisterResource(\"google-native:cloudtasks/v2:Task\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewBucket(ctx *pulumi.Context,\n\tname string, args *BucketArgs, opts ...pulumi.ResourceOpt) (*Bucket, error) {\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"accelerationStatus\"] = nil\n\t\tinputs[\"acl\"] = nil\n\t\tinputs[\"arn\"] = nil\n\t\tinputs[\"bucket\"] = nil\n\t\tinputs[\"bucketPrefix\"] = nil\n\t\tinputs[\"corsRules\"] = nil\n\t\tinputs[\"forceDestroy\"] = nil\n\t\tinputs[\"hostedZoneId\"] = nil\n\t\tinputs[\"lifecycleRules\"] = nil\n\t\tinputs[\"loggings\"] = nil\n\t\tinputs[\"objectLockConfiguration\"] = nil\n\t\tinputs[\"policy\"] = nil\n\t\tinputs[\"region\"] = nil\n\t\tinputs[\"replicationConfiguration\"] = nil\n\t\tinputs[\"requestPayer\"] = nil\n\t\tinputs[\"serverSideEncryptionConfiguration\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t\tinputs[\"versioning\"] = nil\n\t\tinputs[\"website\"] = nil\n\t\tinputs[\"websiteDomain\"] = nil\n\t\tinputs[\"websiteEndpoint\"] = nil\n\t} else {\n\t\tinputs[\"accelerationStatus\"] = args.AccelerationStatus\n\t\tinputs[\"acl\"] = args.Acl\n\t\tinputs[\"arn\"] = args.Arn\n\t\tinputs[\"bucket\"] = args.Bucket\n\t\tinputs[\"bucketPrefix\"] = args.BucketPrefix\n\t\tinputs[\"corsRules\"] = args.CorsRules\n\t\tinputs[\"forceDestroy\"] = args.ForceDestroy\n\t\tinputs[\"hostedZoneId\"] = args.HostedZoneId\n\t\tinputs[\"lifecycleRules\"] = args.LifecycleRules\n\t\tinputs[\"loggings\"] = args.Loggings\n\t\tinputs[\"objectLockConfiguration\"] = args.ObjectLockConfiguration\n\t\tinputs[\"policy\"] = args.Policy\n\t\tinputs[\"region\"] = args.Region\n\t\tinputs[\"replicationConfiguration\"] = args.ReplicationConfiguration\n\t\tinputs[\"requestPayer\"] = args.RequestPayer\n\t\tinputs[\"serverSideEncryptionConfiguration\"] = args.ServerSideEncryptionConfiguration\n\t\tinputs[\"tags\"] = args.Tags\n\t\tinputs[\"versioning\"] = args.Versioning\n\t\tinputs[\"website\"] = args.Website\n\t\tinputs[\"websiteDomain\"] = args.WebsiteDomain\n\t\tinputs[\"websiteEndpoint\"] = args.WebsiteEndpoint\n\t}\n\tinputs[\"bucketDomainName\"] = nil\n\tinputs[\"bucketRegionalDomainName\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:s3/bucket:Bucket\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Bucket{s: s}, nil\n}", "func NewTag(ctx *pulumi.Context,\n\tname string, args *TagArgs, opts ...pulumi.ResourceOption) (*Tag, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.DisplayName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'DisplayName'\")\n\t}\n\tif args.ResourceGroupName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ResourceGroupName'\")\n\t}\n\tif args.ServiceName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ServiceName'\")\n\t}\n\taliases := pulumi.Aliases([]pulumi.Alias{\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20190101:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20170301:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20170301:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20180101:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20180101:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20180601preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20180601preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20191201:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20191201:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20191201preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20191201preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20200601preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20200601preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20201201:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20201201:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-native:apimanagement/v20210101preview:Tag\"),\n\t\t},\n\t\t{\n\t\t\tType: pulumi.String(\"azure-nextgen:apimanagement/v20210101preview:Tag\"),\n\t\t},\n\t})\n\topts = append(opts, aliases)\n\tvar resource Tag\n\terr := ctx.RegisterResource(\"azure-native:apimanagement/v20190101:Tag\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewResourceGroup(ctx *pulumi.Context,\n\tname string, args *ResourceGroupArgs, opts ...pulumi.ResourceOpt) (*ResourceGroup, error) {\n\tif args == nil || args.Tags == nil {\n\t\treturn nil, errors.New(\"missing required argument 'Tags'\")\n\t}\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"tags\"] = nil\n\t} else {\n\t\tinputs[\"tags\"] = args.Tags\n\t}\n\tinputs[\"arn\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:inspector/resourceGroup:ResourceGroup\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ResourceGroup{s: s}, nil\n}", "func NewTaskQueue(size int) *TaskQueue {\n\treturn &TaskQueue{\n\t\tNodes: make([]int, size),\n\t\tSize: size,\n\t}\n}", "func New() *Queue {\n\tq := new(Queue)\n\tq.length = 0\n\tq.s1 = stack.New()\n\tq.s2 = stack.New()\n\n\treturn q\n}", "func Constructor() MyQueue {\n\treturn MyQueue{\n\t\tinStack: make([]int, 0),\n\t\toutStack: make([]int, 0),\n\t}\n}", "func CreateResourceQuota(parent *tenancyv1alpha1.TanzuNamespace) (metav1.Object, error) {\n\n\tfmap := template.FuncMap{\n\t\t\"defaultResourceQuotaCPURequests\": defaultResourceQuotaCPURequests,\n\t\t\"defaultResourceQuotaMemoryRequests\": defaultResourceQuotaMemoryRequests,\n\t\t\"defaultResourceQuotaCPULimits\": defaultResourceQuotaCPULimits,\n\t\t\"defaultResourceQuotaMemoryLimits\": defaultResourceQuotaMemoryLimits,\n\t}\n\n\tchildContent, err := runTemplate(\"tanzu-resource-quota\", resourceResourceQuota, parent, fmap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdecode := scheme.Codecs.UniversalDeserializer().Decode\n\tobj, _, err := decode([]byte(childContent), nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresourceObj := obj.(*k8s_api.ResourceQuota)\n\tresourceObj.Namespace = defaultNamespace(parent.Name, &parent.Spec)\n\n\treturn resourceObj, nil\n}" ]
[ "0.61182225", "0.5922367", "0.5234103", "0.5177013", "0.50431615", "0.49678585", "0.48655295", "0.4863346", "0.48462552", "0.4834142", "0.4833258", "0.4809173", "0.4791956", "0.47916126", "0.4789563", "0.4777478", "0.47687298", "0.4752891", "0.474635", "0.4737543", "0.4733976", "0.47319272", "0.47207615", "0.47063744", "0.46920586", "0.46909273", "0.46909273", "0.46779913", "0.46758932", "0.46656224", "0.46609622", "0.46609426", "0.4655607", "0.46516162", "0.46451342", "0.46381408", "0.462138", "0.46179152", "0.46154281", "0.46080768", "0.46058008", "0.46040723", "0.46039698", "0.45964485", "0.45906383", "0.45898342", "0.45874196", "0.4587301", "0.45760164", "0.4573838", "0.45718697", "0.45699576", "0.45691657", "0.4564425", "0.45607254", "0.455314", "0.45484602", "0.45445654", "0.4532828", "0.4528729", "0.45216385", "0.45115447", "0.4507114", "0.4506615", "0.45043227", "0.45039758", "0.449006", "0.44846767", "0.44832882", "0.4480477", "0.44791356", "0.4478973", "0.44772673", "0.44661242", "0.44642434", "0.44556093", "0.44507137", "0.44412607", "0.441966", "0.44153932", "0.44062883", "0.4403575", "0.44005522", "0.43802184", "0.43793735", "0.43785343", "0.43748385", "0.4369111", "0.43682948", "0.436697", "0.4351619", "0.43431312", "0.43420717", "0.43369862", "0.43349767", "0.43245807", "0.43242732", "0.43234673", "0.43224978", "0.4321164" ]
0.7100234
0
GetInterRegionTrafficQosQueue gets an existing InterRegionTrafficQosQueue resource's state with the given name, ID, and optional state properties that are used to uniquely qualify the lookup (nil if not required).
func GetInterRegionTrafficQosQueue(ctx *pulumi.Context, name string, id pulumi.IDInput, state *InterRegionTrafficQosQueueState, opts ...pulumi.ResourceOption) (*InterRegionTrafficQosQueue, error) { var resource InterRegionTrafficQosQueue err := ctx.ReadResource("alicloud:cen/interRegionTrafficQosQueue:InterRegionTrafficQosQueue", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewInterRegionTrafficQosQueue(ctx *pulumi.Context,\n\tname string, args *InterRegionTrafficQosQueueArgs, opts ...pulumi.ResourceOption) (*InterRegionTrafficQosQueue, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Dscps == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Dscps'\")\n\t}\n\tif args.RemainBandwidthPercent == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'RemainBandwidthPercent'\")\n\t}\n\tif args.TrafficQosPolicyId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'TrafficQosPolicyId'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource InterRegionTrafficQosQueue\n\terr := ctx.RegisterResource(\"alicloud:cen/interRegionTrafficQosQueue:InterRegionTrafficQosQueue\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o InterRegionTrafficQosQueueOutput) InterRegionTrafficQosQueueName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringPtrOutput { return v.InterRegionTrafficQosQueueName }).(pulumi.StringPtrOutput)\n}", "func GetQueue(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *QueueState, opts ...pulumi.ResourceOption) (*Queue, error) {\n\tvar resource Queue\n\terr := ctx.ReadResource(\"aws-native:connect:Queue\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o InterRegionTrafficQosQueueOutput) InterRegionTrafficQosQueueDescription() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringPtrOutput {\n\t\treturn v.InterRegionTrafficQosQueueDescription\n\t}).(pulumi.StringPtrOutput)\n}", "func (service *ContrailService) GetQosQueue(ctx context.Context, request *models.GetQosQueueRequest) (response *models.GetQosQueueResponse, err error) {\n\tspec := &models.ListSpec{\n\t\tLimit: 1,\n\t\tFilters: []*models.Filter{\n\t\t\t&models.Filter{\n\t\t\t\tKey: \"uuid\",\n\t\t\t\tValues: []string{request.ID},\n\t\t\t},\n\t\t},\n\t}\n\tlistRequest := &models.ListQosQueueRequest{\n\t\tSpec: spec,\n\t}\n\tvar result *models.ListQosQueueResponse\n\tif err := common.DoInTransaction(\n\t\tservice.DB,\n\t\tfunc(tx *sql.Tx) error {\n\t\t\tresult, err = db.ListQosQueue(ctx, tx, listRequest)\n\t\t\treturn err\n\t\t}); err != nil {\n\t\treturn nil, common.ErrorInternal\n\t}\n\tif len(result.QosQueues) == 0 {\n\t\treturn nil, common.ErrorNotFound\n\t}\n\tresponse = &models.GetQosQueueResponse{\n\t\tQosQueue: result.QosQueues[0],\n\t}\n\treturn response, nil\n}", "func (o InterRegionTrafficQosQueueOutput) TrafficQosPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringOutput { return v.TrafficQosPolicyId }).(pulumi.StringOutput)\n}", "func GetQueue(config *Configuration) (*Queue, error) {\n\tvar wg sync.WaitGroup\n\tvar wk int\n\n\tq := Queue{&wg, false, nil, nil, nil, nil, &wk}\n\n\tq.Config = config\n\n\tconn, err := amqp.Dial(config.Host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq.connection = conn\n\tq.Connected = true\n\tch, err := q.connection.Channel()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq.channel = ch\n\tq.channel.Qos(config.PrefetchCount, config.PrefetchByteSize, true)\n\n\tiq, err := q.channel.QueueDeclare(config.RoutingKey, config.Durable, config.DeleteIfUnused, config.Exclusive, config.NoWait, config.arguments)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.Exchange != \"\" {\n\t\terr = q.bind()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tq.internalQueue = &iq\n\n\treturn &q, nil\n}", "func (c *QueueClient) Get(ctx context.Context, id int) (*Queue, error) {\n\treturn c.Query().Where(queue.ID(id)).Only(ctx)\n}", "func GetQueue(id string) Queue {\n\tservice := broker.GetService(ServiceName).(*QueueService)\n\treturn service.getQueue(id)\n}", "func (q *QLearning) GetQ(a Action, s State) float64 {\n\treturn q.qt[s][int(a)]\n}", "func NewQueue(qname string, taskId string) (*Queue, error) {\n q := &Queue{}\n q.StdoutChan = make(chan []byte, QUEUE_SIZE)\n q.StderrChan = make(chan []byte, QUEUE_SIZE)\n q.exitChan = make(chan string)\n q.finishChan = make(chan bool)\n\n s, err := aws.NewSqs(qname, taskId)\n q.awsSqs = s\n\n return q, err\n}", "func (ClearTrans) GetQueue() string {\n\treturn \"cy_rubik_clearTrans\"\n}", "func (q *priorityLocalQueue) Get(ctx context.Context, name string) (amboy.Job, bool) {\n\treturn q.storage.Get(name)\n}", "func createQueue(subID string) (queueUrl string, retErr error) {\n\n\t//Creo un service client SQS\n\tsvc := sqs.New(common.Sess)\n\n\t//Creo la coda\n\tresult, err := svc.CreateQueue(&sqs.CreateQueueInput{\n\t\tQueueName: aws.String(subID + \".fifo\"),\n\t\tAttributes: map[string]*string{\n\t\t\t\"MessageRetentionPeriod\": \taws.String(\"345600\"),\n\t\t\t\"ReceiveMessageWaitTimeSeconds\": \taws.String(strconv.FormatInt(common.Config.PollingTime, 10)),\n\t\t\t\"FifoQueue\":\t\t\t\t\t\taws.String(\"true\"),\t\t//Coda FIFO\n\t\t},\n\t})\n\tif err != nil {\n\t\tcommon.Warning(\"[BROKER] Errore nella creazione della coda\\n\" + err.Error())\n\t\treturn \"\", err\n\t}\n\n\tcommon.Info(\"[BROKER] Coda creata con successo all'URL \" + *result.QueueUrl)\n\n\treturn *result.QueueUrl, nil\n}", "func (service *ContrailService) RESTGetQosQueue(c echo.Context) error {\n\tid := c.Param(\"id\")\n\trequest := &models.GetQosQueueRequest{\n\t\tID: id,\n\t}\n\tctx := c.Request().Context()\n\tresponse, err := service.GetQosQueue(ctx, request)\n\tif err != nil {\n\t\treturn common.ToHTTPError(err)\n\t}\n\treturn c.JSON(http.StatusOK, response)\n}", "func (c *restClient) GetQueue(ctx context.Context, req *cloudtaskspb.GetQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v2beta3/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\tif req.GetReadMask() != nil {\n\t\treadMask, err := protojson.Marshal(req.GetReadMask())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparams.Add(\"readMask\", string(readMask[1:len(readMask)-1]))\n\t}\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\topts = append((*c.CallOptions).GetQueue[0:len((*c.CallOptions).GetQueue):len((*c.CallOptions).GetQueue)], opts...)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tresp := &cloudtaskspb.Queue{}\n\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, opts...)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\treturn resp, nil\n}", "func (pq *PrefixQueue) getOrCreateQueue(prefix []byte) (*queue, error) {\n\t// Try to get the queue gob value.\n\tqval, err := pq.db.Get(generateKeyPrefixData(prefix), nil)\n\tif err == errors.ErrNotFound {\n\t\treturn &queue{}, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Decode gob to our queue type.\n\tq := &queue{}\n\tbuffer := bytes.NewBuffer(qval)\n\tdec := gob.NewDecoder(buffer)\n\treturn q, dec.Decode(q)\n}", "func (mq *MessageQueue) Read() (interface{}, error) {\n\tmq.m.Lock()\n\tdefer mq.m.Unlock()\n\tif mq.closed {\n\t\treturn nil, ErrQueueClosed\n\t}\n\tif mq.isEmpty() {\n\t\treturn nil, ErrQueueEmpty\n\t}\n\tval := mq.messages[0]\n\tmq.messages[0] = nil\n\tmq.messages = mq.messages[1:]\n\treturn val, nil\n}", "func (s *service) GetOrCreateQueue(id string) Queue {\n\ts.logger.Info(\"create kafka queue\", logging.QueueID, id)\n\n\treturn s.createQueueInternal(id)\n}", "func (this *MyQueue) Peek() int {\n return this.q[0]\n}", "func GetInfoFromQueue(q amqp.Queue) QueueInfo {\n\n\treturn QueueInfo{\n\t\tName: q.Name,\n\t\tConsumers: q.Consumers,\n\t\tMessages: q.Messages,\n\t}\n}", "func (q *Queue) Peek(num uint) (operation.QueuedOperationsAtTime, error) {\n\tif q.State() != lifecycle.StateStarted {\n\t\treturn nil, lifecycle.ErrNotStarted\n\t}\n\n\tq.mutex.RLock()\n\tdefer q.mutex.RUnlock()\n\n\tn := int(num)\n\tif len(q.pending) < n {\n\t\tn = len(q.pending)\n\t}\n\n\treturn asQueuedOperations(q.pending[0:n]), nil\n}", "func NewQueue(id string, persistent bool, conn net.Conn) (Queue, error) {\n\tservice := broker.GetService(ServiceName).(*QueueService)\n\treturn service.newQueue(id, persistent, conn)\n}", "func findBestQueueSub(sl []*subState) *subState {\n\tvar (\n\t\tleastOutstanding = int(^uint(0) >> 1)\n\t\trsub *subState\n\t)\n\tfor _, sub := range sl {\n\n\t\tsub.RLock()\n\t\tsOut := len(sub.acksPending)\n\t\tsStalled := sub.stalled\n\t\tsHasFailedHB := sub.hasFailedHB\n\t\tsub.RUnlock()\n\n\t\t// Favor non stalled subscribers and clients that do not have failed heartbeats\n\t\tif !sStalled && !sHasFailedHB {\n\t\t\tif sOut < leastOutstanding {\n\t\t\t\tleastOutstanding = sOut\n\t\t\t\trsub = sub\n\t\t\t}\n\t\t}\n\t}\n\n\tlen := len(sl)\n\tif rsub == nil && len > 0 {\n\t\trsub = sl[0]\n\t}\n\tif len > 1 && rsub == sl[0] {\n\t\tcopy(sl, sl[1:len])\n\t\tsl[len-1] = rsub\n\t}\n\n\treturn rsub\n}", "func getQueueUrl(id string) (queueUrl string, retErr error) {\n\n\t//Creazione client DynamoDB\n\tsvc := dynamodb.New(common.Sess)\n\n\tresult, err := svc.GetItem(&dynamodb.GetItemInput{\n\t\tTableName: aws.String(subTableName),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"SubID\": {\n\t\t\t\tS: aws.String(id),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tcommon.Warning(\"[BROKER] Errore nel retreive del subscriber con ID: \" + id + \".\\n\" + err.Error())\n\t\treturn \"\", err\n\t}\n\n\titem := common.SubscriberEntry{}\n\n\terr = dynamodbattribute.UnmarshalMap(result.Item, &item)\n\tif err != nil {\n\t\tcommon.Warning(\"[BROKER] Errore nell'unmarshaling del risultato\")\n\t\treturn \"\", err\n\t}\n\tif item.SubID == \"\" {\n\t\tcommon.Warning(\"[BROKER] Nessun subscriber trovato con id \" + id)\n\t\treturn \"\", errors.New(\"no item found\")\n\t}\n\n\tcommon.Info(\"[BROKER] Subscriber trovato: \" + item.SubID + \"\\n\\t\" + item.QueueURL)\n\n\treturn item.QueueURL, nil\n}", "func (p *Process) CmdGetQueue(pac teoapi.Packet) (err error) {\n\tdata := pac.RemoveTrailingZero(pac.Data())\n\trequest := cdb.KeyValue{Cmd: pac.Cmd()}\n\tif err = request.UnmarshalText(data); err != nil {\n\t\treturn\n\t}\n\t// Return only Value for text requests and all fields for json\n\tresponce := request\n\tif responce.Value, err = p.tcdb.GetQueue(request.Key); err != nil {\n\t\treturn\n\t} else if !request.RequestInJSON {\n\t\t_, err = p.tcdb.con.SendAnswer(pac, pac.Cmd(), responce.Value)\n\t} else if retdata, err := responce.MarshalText(); err == nil {\n\t\t_, err = p.tcdb.con.SendAnswer(pac, pac.Cmd(), retdata)\n\t}\n\treturn\n}", "func (t *TopicCache) GetQueue(projectName, serviceName string) []string {\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\tif len(t.inQueue[projectName+serviceName]) >= 100 {\n\t\treturn t.inQueue[projectName+serviceName][:99]\n\t}\n\n\treturn t.inQueue[projectName+serviceName]\n}", "func (taskBolt *TaskBolt) ReadQueue(n int) []*ga4gh_task_exec.Job {\n\tjobs := make([]*ga4gh_task_exec.Job, 0)\n\ttaskBolt.db.View(func(tx *bolt.Tx) error {\n\n\t\t// Iterate over the JobsQueued bucket, reading the first `n` jobs\n\t\tc := tx.Bucket(JobsQueued).Cursor()\n\t\tfor k, _ := c.First(); k != nil && len(jobs) < n; k, _ = c.Next() {\n\t\t\tid := string(k)\n\t\t\tjob := getJob(tx, id)\n\t\t\tjobs = append(jobs, job)\n\t\t}\n\t\treturn nil\n\t})\n\treturn jobs\n}", "func NewCfnQueue(scope awscdk.Construct, id *string, props *CfnQueueProps) CfnQueue {\n\t_init_.Initialize()\n\n\tj := jsiiProxy_CfnQueue{}\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_mediaconvert.CfnQueue\",\n\t\t[]interface{}{scope, id, props},\n\t\t&j,\n\t)\n\n\treturn &j\n}", "func NewQueue(ctx *pulumi.Context,\n\tname string, args *QueueArgs, opts ...pulumi.ResourceOption) (*Queue, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.HoursOfOperationArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'HoursOfOperationArn'\")\n\t}\n\tif args.InstanceArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InstanceArn'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Queue\n\terr := ctx.RegisterResource(\"aws-native:connect:Queue\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *service) createQueueInternal(id string) Queue {\n\treturn NewQueue(id, s.config, s.kafkaClientFactory)\n}", "func (c *QueueClient) GetX(ctx context.Context, id int) *Queue {\n\tq, err := c.Get(ctx, id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn q\n}", "func NewQueue(ctx context.Context, queueID string, db *sql.DB, conf QueueConfig) (*Queue, error) {\n\tq := &Queue{ID: queueID}\n\tq.repo = repo.NewRepository(db)\n\tq.PollRate = 100 * time.Millisecond // Default\n\tq.queueSize = 10000 // Default\n\tq.retries = 3 // Default\n\tq.IsMultiQueue = conf.IsMultiQueue\n\tq.baseDelay = 3 * time.Second // Default\n\n\tif conf.PollingRate > 0 {\n\t\tq.PollRate = conf.PollingRate\n\t}\n\tif conf.Qsize > 0 {\n\t\tq.queueSize = conf.Qsize\n\t}\n\tif conf.BaseDelay > 0 {\n\t\tq.baseDelay = conf.BaseDelay\n\t}\n\tif conf.Retries >= 0 {\n\t\tq.retries = conf.Retries\n\t}\n\t// Multilevel Queue/channel created\n\ttemp := mlQueue{}\n\ttemp.notifier = make([]chan JobChan, 1)\n\ttemp.notifier[0] = make(chan JobChan, q.queueSize)\n\ttemp.total = 1\n\tq.mq = temp\n\n\tm := make(map[string][]worker.Worker)\n\tq.workers = m\n\tvar wg sync.WaitGroup\n\tq.wg = &wg\n\n\t// resume stopped jobs\n\terr := q.ResumePendingJobs(ctx)\n\tif err != nil {\n\t\tlogger.Log.Error(\"Unable to resume jobs from bucket: %s\", zap.Error(err))\n\t\t// Don't fail out, this isn't really fatal. But maybe it should be?\n\t}\n\treturn q, nil\n}", "func NewGetaspecificCallQueueRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/callqueues/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (c *PatientClient) QueryQueue(pa *Patient) *QueueQuery {\n\tquery := &QueueQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := pa.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(patient.Table, patient.FieldID, id),\n\t\t\tsqlgraph.To(queue.Table, queue.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, patient.QueueTable, patient.QueueColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(pa.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func SelectQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) (q *Queue, err error) {\n\tredisClient := redis.NewTCPClient(&redis.Options{\n\t\tAddr: redisHost + \":\" + redisPort,\n\t\tPassword: redisPassword,\n\t\tDB: redisDB,\n\t})\n\tdefer redisClient.Close()\n\n\tisMember, err := redisClient.SIsMember(masterQueueKey(), name).Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !isMember {\n\t\treturn nil, fmt.Errorf(\"q with this name doesn't exist\")\n\t}\n\n\treturn newQueue(redisHost, redisPort, redisPassword, redisDB, name), nil\n}", "func (a *Client) GetSitesSiteidQos(params *GetSitesSiteidQosParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSitesSiteidQosOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSitesSiteidQosParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"getSitesSiteidQos\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/sites/{siteId}/qos\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetSitesSiteidQosReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetSitesSiteidQosOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getSitesSiteidQos: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *TowerClient) initActiveQueue(s *wtdb.ClientSession) *sessionQueue {\n\t// Initialize the session queue, providing it with all of the resources\n\t// it requires from the client instance.\n\tsq := c.newSessionQueue(s)\n\n\t// Add the session queue as an active session so that we remember to\n\t// stop it on shutdown.\n\tc.activeSessions.Add(sq)\n\n\t// Start the queue so that it can be active in processing newly assigned\n\t// tasks or to upload previously committed updates.\n\tsq.Start()\n\n\treturn sq\n}", "func (d *Device) GetQueue(qf *QueueFamily) *Queue {\n\n\tvar vkq vk.Queue\n\n\tvk.GetDeviceQueue(d.VKDevice, uint32(qf.Index), 0, &vkq)\n\n\tvar queue Queue\n\tqueue.QueueFamily = qf\n\tqueue.Device = d\n\tqueue.VKQueue = vkq\n\n\treturn &queue\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue_State) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue_State\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (psc *PartitionSchedulingContext) GetQueue(queueName string) *SchedulingQueue {\n psc.lock.RLock()\n defer psc.lock.RUnlock()\n\n return psc.queues[queueName]\n}", "func (r *Resource) GetDesiredState(ctx context.Context, azureConfig interface{}) (interface{}, error) {\n\tcr, err := key.ToCustomResource(azureConfig)\n\tif err != nil {\n\t\treturn connections{}, microerror.Mask(err)\n\t}\n\n\tvar (\n\t\thostVPNGateway *network.VirtualNetworkGateway\n\t\tguestVPNGateway *network.VirtualNetworkGateway\n\t)\n\t// Do not check for vpn gateway when deleting. As we do not require tenant\n\t// cluster vpn gateway to be ready in order to delete connection from host\n\t// cluster vpn gateway.\n\tif !key.IsDeleted(&cr) {\n\t\t// In order to make vpn gateway connection work we need 2 vpn gateway. One\n\t\t// on the host cluster and one on the tenant cluster. Here we check for vpn\n\t\t// gateways readiness. In case one of the vpn gateway is not ready we cancel\n\t\t// the resource and try again on the next resync period.\n\t\t{\n\n\t\t\tresourceGroup := key.ResourceGroupName(cr)\n\t\t\tvpnGatewayName := key.VPNGatewayName(cr)\n\n\t\t\tguestVPNGateway, err = r.getGuestVirtualNetworkGateway(ctx, resourceGroup, vpnGatewayName)\n\t\t\tif IsVPNGatewayNotFound(err) {\n\t\t\t\tr.logger.Debugf(ctx, \"tenant vpn gateway was not found\")\n\t\t\t\tresourcecanceledcontext.SetCanceled(ctx)\n\t\t\t\tr.logger.Debugf(ctx, \"canceling resource\")\n\n\t\t\t\treturn connections{}, nil\n\t\t\t} else if err != nil {\n\t\t\t\treturn connections{}, microerror.Mask(err)\n\t\t\t}\n\n\t\t\tprovisioningState := guestVPNGateway.ProvisioningState\n\t\t\tif provisioningState != \"Succeeded\" {\n\t\t\t\tr.logger.Debugf(ctx, \"tenant vpn gateway is in state '%s'\", provisioningState)\n\t\t\t\tresourcecanceledcontext.SetCanceled(ctx)\n\t\t\t\tr.logger.Debugf(ctx, \"canceling resource\")\n\n\t\t\t\treturn connections{}, nil\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tresourceGroup := r.azure.HostCluster.ResourceGroup\n\t\t\tvpnGatewayName := r.azure.HostCluster.VirtualNetworkGateway\n\n\t\t\thostVPNGateway, err = r.getHostVirtualNetworkGateway(ctx, resourceGroup, vpnGatewayName)\n\t\t\tif IsVPNGatewayNotFound(err) {\n\t\t\t\tr.logger.Debugf(ctx, \"host vpn gateway was not found\")\n\t\t\t\tresourcecanceledcontext.SetCanceled(ctx)\n\t\t\t\tr.logger.Debugf(ctx, \"canceling resource\")\n\n\t\t\t\treturn connections{}, nil\n\t\t\t} else if err != nil {\n\t\t\t\treturn connections{}, microerror.Mask(err)\n\t\t\t}\n\n\t\t\tif provisioningState := string(hostVPNGateway.ProvisioningState); provisioningState != \"Succeeded\" {\n\t\t\t\tr.logger.Debugf(ctx, \"host vpn gateway is in state '%s'\", provisioningState)\n\t\t\t\tresourcecanceledcontext.SetCanceled(ctx)\n\t\t\t\tr.logger.Debugf(ctx, \"canceling resource\")\n\n\t\t\t\treturn connections{}, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r.getDesiredState(cr, guestVPNGateway, hostVPNGateway), nil\n}", "func (q *Queue) Peek(n int) (item interface{}) {\n item = q.queue[n]\n return\n}", "func pollRxQueue(memif *Memif, queueID uint8) {\n\tdefer memif.wg.Done()\n\n\tlog.WithFields(logger.Fields{\n\t\t\"ifName\": memif.IfName,\n\t\t\"queue-ID\": queueID,\n\t}).Debug(\"Started queue interrupt polling.\")\n\n\tvar qfd C.int\n\terrCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)\n\terr := getMemifError(int(errCode))\n\tif err != nil {\n\t\tlog.WithField(\"err\", err).Error(\"memif_get_queue_efd() failed\")\n\t\treturn\n\t}\n\n\t// Create epoll file descriptor.\n\tvar event [1]syscall.EpollEvent\n\tepFd, err := syscall.EpollCreate1(0)\n\tif err != nil {\n\t\tlog.WithField(\"err\", err).Error(\"epoll_create1() failed\")\n\t\treturn\n\t}\n\tdefer syscall.Close(epFd)\n\n\t// Add Rx queue interrupt file descriptor.\n\tevent[0].Events = syscall.EPOLLIN\n\tevent[0].Fd = int32(qfd)\n\tif err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {\n\t\tlog.WithField(\"err\", err).Error(\"epoll_ctl() failed\")\n\t\treturn\n\t}\n\n\t// Add file descriptor used to stop this go routine.\n\tevent[0].Events = syscall.EPOLLIN\n\tevent[0].Fd = int32(memif.stopQPollFd)\n\tif err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {\n\t\tlog.WithField(\"err\", err).Error(\"epoll_ctl() failed\")\n\t\treturn\n\t}\n\n\t// Poll for interrupts.\n\tfor {\n\t\t_, err := syscall.EpollWait(epFd, event[:], -1)\n\t\tif err != nil {\n\t\t\terrno, _ := err.(syscall.Errno)\n\t\t\t//EINTR and EAGAIN should not be considered as a fatal error, try again\n\t\t\tif errno == syscall.EINTR || errno == syscall.EAGAIN {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.WithField(\"err\", err).Error(\"epoll_wait() failed\")\n\t\t\tmemif.intErrCh <- err\n\t\t\treturn\n\t\t}\n\n\t\t// Handle Rx Interrupt.\n\t\tif event[0].Fd == int32(qfd) {\n\t\t\t// Consume the interrupt event.\n\t\t\tbuf := make([]byte, 8)\n\t\t\t_, err = syscall.Read(int(qfd), buf[:])\n\t\t\tif err != nil {\n\t\t\t\tlog.WithField(\"err\", err).Warn(\"read() failed\")\n\t\t\t}\n\n\t\t\t// Send signal to memif-global interrupt channel.\n\t\t\tselect {\n\t\t\tcase memif.intCh <- queueID:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Send signal to queue-specific interrupt channel.\n\t\t\tselect {\n\t\t\tcase memif.queueIntCh[queueID] <- struct{}{}:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t// Stop the go routine if requested.\n\t\tif event[0].Fd == int32(memif.stopQPollFd) {\n\t\t\tlog.WithFields(logger.Fields{\n\t\t\t\t\"ifName\": memif.IfName,\n\t\t\t\t\"queue-ID\": queueID,\n\t\t\t}).Debug(\"Stopped queue interrupt polling.\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Project) Queue(name string) (*Queue, error) {\n q := new(Queue)\n err := Mongo.GetOne(\"queue\", bson.M{\"project\": p.ID, \"name\": name}, q)\n return q, err\n}", "func NewBounded(capacity int) IntStack {\n\tq := &BoundedQueue{capacity: capacity}\n\tq.hasSpace = sync.NewCond(q)\n\tq.hasItems = sync.NewCond(q)\n\treturn q\n}", "func queueInProgress(queue, cgroup string) (exWrap, error) {\n\tk, err := queueKeyMarshal(core.Key{Base: queue, Subs: []string{cgroup, \"inprogress\"}})\n\tif err != nil {\n\t\treturn exWrap{}, err\n\t}\n\treturn newExWrap(k), nil\n}", "func NewQueue(storage Storage, reQueueTimeout time.Duration) Queue {\n\tif reQueueTimeout < 1 {\n\t\treQueueTimeout = time.Minute * 30\n\t}\n\n\tname := \"gocelery\"\n\tq := &queue{\n\t\tstorage: storage,\n\t\thead: 0,\n\t\ttail: 0,\n\t\trequeueTimeout: reQueueTimeout,\n\t\tqueuePrefix: fmt.Sprintf(\"%s-queue-\", name),\n\t\tqueueAckPrefix: fmt.Sprintf(\"%s-ack-\", name),\n\t}\n\n\t// restore the old state from the DB\n\tq.loadHeadTail()\n\treturn q\n}", "func GetStack(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *StackState, opts ...pulumi.ResourceOption) (*Stack, error) {\n\tvar resource Stack\n\terr := ctx.ReadResource(\"aws-native:cloudformation:Stack\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (o *VnicEthAdapterPolicyInventory) GetRxQueueSettings() VnicEthRxQueueSettings {\n\tif o == nil || o.RxQueueSettings.Get() == nil {\n\t\tvar ret VnicEthRxQueueSettings\n\t\treturn ret\n\t}\n\treturn *o.RxQueueSettings.Get()\n}", "func GetQOS(container *v1.Container) QOSList {\n\tresourceToQOS := QOSList{}\n\tfor resource := range allResources(container) {\n\t\tswitch {\n\t\tcase isResourceGuaranteed(container, resource):\n\t\t\tresourceToQOS[resource] = v1.PodQOSGuaranteed\n\t\tcase isResourceBestEffort(container, resource):\n\t\t\tresourceToQOS[resource] = v1.PodQOSBestEffort\n\t\tdefault:\n\t\t\tresourceToQOS[resource] = v1.PodQOSBurstable\n\t\t}\n\t}\n\treturn resourceToQOS\n}", "func (o InterRegionTrafficQosQueueOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (consumer *Consumer) RxQueue() *iface.PktQueue {\n\treturn iface.PktQueueFromPtr(unsafe.Pointer(&consumer.rxC.rxQueue))\n}", "func NewPredictableQueue(m *q.Message, err error) q.Queue {\n\treturn &predictableQueue{err: err, msg: m}\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Queues) NewQueue(Name string) (*OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Queue == nil {\n\t\tt.Queue = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Queue[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Queue\", key)\n\t}\n\n\tt.Queue[key] = &OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue{\n\t\tName: &Name,\n\t}\n\n\treturn t.Queue[key], nil\n}", "func (service *ContrailService) ListQosQueue(\n\tctx context.Context,\n\trequest *models.ListQosQueueRequest) (response *models.ListQosQueueResponse, err error) {\n\tif err := common.DoInTransaction(\n\t\tservice.DB,\n\t\tfunc(tx *sql.Tx) error {\n\t\t\tresponse, err = db.ListQosQueue(ctx, tx, request)\n\t\t\treturn err\n\t\t}); err != nil {\n\t\treturn nil, common.ErrorInternal\n\t}\n\treturn response, nil\n}", "func (q *Queue) GetCapacity() int32 {\n\treturn int32(cap(q.mq.notifier[q.mq.pushIndex]))\n}", "func (q APQ) GetPriority(x interface{}) (int, error) {\n\ti, ok := q.locations[x]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"GetPriority(): value %v was not in the queue\", x)\n\t}\n\treturn i.key, nil\n}", "func (b *testBroker) queue(pipe *Pipeline) *testQueue {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tq, ok := b.queues[pipe]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\treturn q\n}", "func New(cfg Config, pubSub pubSub, metrics metricsProvider) (*Queue, error) {\n\tmsgChan, err := pubSub.SubscribeWithOpts(context.Background(), topic, spi.WithPool(cfg.PoolSize))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"subscribe to topic [%s]: %w\", topic, err)\n\t}\n\n\tq := &Queue{\n\t\tpubSub: pubSub,\n\t\tmsgChan: msgChan,\n\t\tjsonMarshal: json.Marshal,\n\t\tjsonUnmarshal: json.Unmarshal,\n\t\tmetrics: metrics,\n\t}\n\n\tq.Lifecycle = lifecycle.New(\"operation-queue\",\n\t\tlifecycle.WithStart(q.start),\n\t\tlifecycle.WithStop(q.stop),\n\t)\n\n\tq.Start()\n\n\treturn q, nil\n}", "func (s *Stack) read() (*cloudformation.Stack, error) {\n\tout, err := s.cfnconn.DescribeStacks(&cloudformation.DescribeStacksInput{\n\t\tStackName: aws.String(s.Name),\n\t})\n\tif err != nil {\n\t\tif e, ok := err.(awserr.Error); ok && e.Code() == \"ValidationError\" {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, errors.Annotatef(err, \"cannot read stack\")\n\t}\n\tif out.Stacks == nil || len(out.Stacks) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn out.Stacks[0], nil\n}", "func (q *Queue) get(repoName string) *queueItem {\n\tif q.items == nil {\n\t\tq.items = map[string]*queueItem{}\n\t\tq.pq = make(pqueue, 0)\n\t}\n\n\titem, ok := q.items[repoName]\n\tif !ok {\n\t\titem = &queueItem{\n\t\t\trepoName: repoName,\n\t\t\theapIdx: -1,\n\t\t}\n\t\tq.items[repoName] = item\n\t}\n\n\treturn item\n}", "func (q *SubmitQueue) Peek() (SubmitRequest, error) {\n\tif len(q.items) < 1 {\n\t\treturn SubmitRequest{}, ErrQueueEmpty\n\t}\n\tif !q.sorted {\n\t\treturn SubmitRequest{}, ErrQueueUnsorted\n\t}\n\titem := q.items[0]\n\treturn item, nil\n}", "func (s *API) GetQueueAttributes(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"GetQueueAttributes\")\n\tw.WriteHeader(http.StatusNotImplemented)\n}", "func newSqsConn(accessKey string, secretKey string, region aws.Region, queueName string) *sqs.Queue {\n\tauth := aws.Auth{AccessKey: accessKey, SecretKey: secretKey}\n\tclient := sqs.New(auth, region)\n\tqueue, err := client.GetQueue(queueName)\n\tif err != nil {\n\t\tlog.Fatalf(\"SQS connection error: %s\\n\", err)\n\t}\n\tlog.Printf(\"Connected to queue: %s\\n\", queue.Url)\n\treturn queue\n}", "func GetConnectionDetails(in v1beta1.Queue) managed.ConnectionDetails {\n\tif in.Status.AtProvider.URL == \"\" {\n\t\treturn nil\n\t}\n\treturn managed.ConnectionDetails{\n\t\txpv1.ResourceCredentialsSecretEndpointKey: []byte(in.Status.AtProvider.URL),\n\t}\n}", "func (q Queue) Peek() (interface{}, error) {\n\tif len(q) <= 0 {\n\t\treturn nil, errors.New(\"Can't peek() from empty queue!\")\n\t}\n\treturn q[0], nil\n}", "func GetDeviceQueueItem(ctx context.Context, db sqlx.Queryer, id int64) (DeviceQueueItem, error) {\n\tvar qi DeviceQueueItem\n\terr := sqlx.Get(db, &qi, \"select * from device_queue where id = $1\", id)\n\tif err != nil {\n\t\treturn qi, handlePSQLError(err, \"select error\")\n\t}\n\treturn qi, nil\n}", "func (service *ContrailService) CreateQosQueue(\n\tctx context.Context,\n\trequest *models.CreateQosQueueRequest) (*models.CreateQosQueueResponse, error) {\n\tmodel := request.QosQueue\n\tif model.UUID == \"\" {\n\t\tmodel.UUID = uuid.NewV4().String()\n\t}\n\tauth := common.GetAuthCTX(ctx)\n\tif auth == nil {\n\t\treturn nil, common.ErrorUnauthenticated\n\t}\n\n\tif model.FQName == nil {\n\t\tif model.DisplayName != \"\" {\n\t\t\tmodel.FQName = []string{auth.DomainID(), auth.ProjectID(), model.DisplayName}\n\t\t} else {\n\t\t\tmodel.FQName = []string{auth.DomainID(), auth.ProjectID(), model.UUID}\n\t\t}\n\t}\n\tmodel.Perms2 = &models.PermType2{}\n\tmodel.Perms2.Owner = auth.ProjectID()\n\tif err := common.DoInTransaction(\n\t\tservice.DB,\n\t\tfunc(tx *sql.Tx) error {\n\t\t\treturn db.CreateQosQueue(ctx, tx, request)\n\t\t}); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"err\": err,\n\t\t\t\"resource\": \"qos_queue\",\n\t\t}).Debug(\"db create failed on create\")\n\t\treturn nil, common.ErrorInternal\n\t}\n\treturn &models.CreateQosQueueResponse{\n\t\tQosQueue: request.QosQueue,\n\t}, nil\n}", "func GetFromQueue(queue string) ([]byte, error) {\n\treturn cache.Get(queue)\n}", "func Get(queueName string, v interface{}) error {\n\treturn b.Get(queueName, v)\n}", "func (this *Queue) GetQueue() (val Mensaje, err error) {\n\t// Primero determina si la cola está vacía\n\tif this.rear == this.front {\n\t\treturn Mensaje{0, \"0\", \"0\"}, errors.New(\"Cola de Mensajes Vacia\")\n\t}\n\tthis.front++\n\tval = this.array[this.front]\n\treturn val, err\n}", "func GetPriorityClass(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *PriorityClassState, opts ...pulumi.ResourceOption) (*PriorityClass, error) {\n\tvar resource PriorityClass\n\terr := ctx.ReadResource(\"kubernetes:scheduling.k8s.io/v1:PriorityClass\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func EnsureQueue(ctx context.Context, cli sqsiface.SQSAPI) (string /*arn*/, error) {\n\tsrc := commonv1alpha1.ReconcilableFromContext(ctx)\n\ttypedSrc := src.(*v1alpha1.AWSS3Source)\n\n\tstatus := &typedSrc.Status\n\n\tif dest := typedSrc.Spec.Destination; dest != nil {\n\t\tif userProvidedQueue := dest.SQS; userProvidedQueue != nil {\n\t\t\tstatus.QueueARN = &userProvidedQueue.QueueARN\n\t\t\treturn userProvidedQueue.QueueARN.String(), nil\n\t\t}\n\t}\n\n\tqueueName := queueName(typedSrc)\n\n\tqueueURL, err := sqs.QueueURL(cli, queueName)\n\tswitch {\n\tcase isNotFound(err):\n\t\tqueueURL, err = sqs.CreateQueue(cli, queueName, queueTags(typedSrc))\n\t\tif err != nil {\n\t\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Unable to create SQS queue\")\n\t\t\treturn \"\", fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedQueue,\n\t\t\t\t\"Error creating SQS queue for event notifications: %s\", toErrMsg(err)))\n\t\t}\n\t\tevent.Normal(ctx, ReasonQueueCreated, \"Created SQS queue %q\", queueURL)\n\n\tcase isAWSError(err):\n\t\t// All documented API errors require some user intervention and\n\t\t// are not to be retried.\n\t\t// https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Request to SQS API got rejected\")\n\t\treturn \"\", controller.NewPermanentError(reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Failed to synchronize SQS queue: %s\", toErrMsg(err)))\n\n\tcase err != nil:\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Cannot synchronize SQS queue\")\n\t\treturn \"\", fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Failed to determine URL of SQS queue: %s\", toErrMsg(err)))\n\t}\n\n\tgetAttrs := []string{awssqs.QueueAttributeNameQueueArn, awssqs.QueueAttributeNamePolicy}\n\tqueueAttrs, err := sqs.QueueAttributes(cli, queueURL, getAttrs)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getting attributes of SQS queue: %w\", err)\n\t}\n\n\tqueueARN := queueAttrs[awssqs.QueueAttributeNameQueueArn]\n\n\tqueueARNStruct, err := arnStrToARN(queueARN)\n\tif err != nil {\n\t\treturn queueARN, fmt.Errorf(\"converting ARN string to structured ARN: %w\", err)\n\t}\n\n\t// it is essential that we propagate the queue's ARN here,\n\t// otherwise BuildAdapter() won't be able to configure the SQS\n\t// adapter properly\n\tstatus.QueueARN = queueARNStruct\n\n\tcurrentPol := unmarshalQueuePolicy(queueAttrs[awssqs.QueueAttributeNamePolicy])\n\tdesiredPol := makeQueuePolicy(queueARN, typedSrc)\n\n\tif err := syncQueuePolicy(cli, queueURL, currentPol, desiredPol); err != nil {\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Cannot synchronize SQS queue\")\n\t\treturn queueARN, fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Error synchronizing policy of SQS queue: %s\", toErrMsg(err)))\n\t}\n\n\treturn queueARN, nil\n}", "func NewCfnQueue_Override(c CfnQueue, scope awscdk.Construct, id *string, props *CfnQueueProps) {\n\t_init_.Initialize()\n\n\t_jsii_.Create(\n\t\t\"monocdk.aws_mediaconvert.CfnQueue\",\n\t\t[]interface{}{scope, id, props},\n\t\tc,\n\t)\n}", "func (rabbitmq *RabbitMQ) Get(get GetStruct) (msg Delivery, ok bool, err error) {\r\n\tif rabbitmq == nil || rabbitmq.Channel == nil {\r\n\t\treturn Delivery{}, false, ErrCursor\r\n\t}\r\n\t// ch, _ := rabbitmq.Connection.Channel()\r\n\t// defer ch.Close()\r\n\r\n\tdelivery, ok, err := rabbitmq.Channel.Get(\r\n\t\tget.Queue,\r\n\t\tget.AutoAck,\r\n\t)\r\n\r\n\tif err != nil || ok == false {\r\n\t\treturn Delivery{}, ok, err\r\n\t}\r\n\treturn castDelivery(delivery), ok, nil\r\n}", "func (t *Qos_Qos) NewQos(Id string) (*Qos_Qos_Qos, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Qos == nil {\n\t\tt.Qos = make(map[string]*Qos_Qos_Qos)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Qos[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Qos\", key)\n\t}\n\n\tt.Qos[key] = &Qos_Qos_Qos{\n\t\tId: &Id,\n\t}\n\n\treturn t.Qos[key], nil\n}", "func (q *messageQueue) getMessage() (msg Message, id int, empty bool) {\n\tif len(q.q) == 0 {\n\t\treturn Message{}, 0, true\n\t}\n\tr := int(rand.Int31n(int32(len(q.q))))\n\tmessage := q.q[r]\n\tt := int(rand.Int31n(int32(len((*message).distributionList))))\n\trecipient := (*message).distributionList[t]\n\tq.q[r].ttl--\n\tif q.q[r].ttl == 0 {\n\t\tq.q = append(q.q[:r], q.q[r+1:]...)\n\t}\n\treturn message.msg, recipient, false\n}", "func (c *TowerClient) getOrInitActiveQueue(s *wtdb.ClientSession) *sessionQueue {\n\tif sq, ok := c.activeSessions[s.ID]; ok {\n\t\treturn sq\n\t}\n\n\treturn c.initActiveQueue(s)\n}", "func (c *Client) GetQueueAttributes(ctx context.Context, params *GetQueueAttributesInput, optFns ...func(*Options)) (*GetQueueAttributesOutput, error) {\n\tif params == nil {\n\t\tparams = &GetQueueAttributesInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"GetQueueAttributes\", params, optFns, c.addOperationGetQueueAttributesMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*GetQueueAttributesOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func (n *resPool) queue(qt QueueType) queue.Queue {\n\tswitch qt {\n\tcase ControllerQueue:\n\t\treturn n.controllerQueue\n\tcase NonPreemptibleQueue:\n\t\treturn n.npQueue\n\tcase PendingQueue:\n\t\treturn n.pendingQueue\n\tcase RevocableQueue:\n\t\treturn n.revocableQueue\n\t}\n\n\t// should never come here\n\treturn nil\n}", "func queueName(src *v1alpha1.AWSS3Source) string {\n\treturn \"s3-events_\" + src.Spec.ARN.Resource\n}", "func (o *VulnUpdateNotification) GetQueueId() string {\n\tif o == nil || o.QueueId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.QueueId\n}", "func (s *LatencyFaultStrategy) SelectOneMessageQueue(topicInfo *TopicPublishInfo, lastBrokerName string) MessageQueue {\n\tqueueNumber := topicInfo.GetQueueNumber()\n\tfor i := 0; i < queueNumber; i++ {\n\t\tmq := topicInfo.GetNextQueue()\n\t\tif s.isBrokerAvaliable(mq.BrokerName) && (lastBrokerName == \"\" || mq.BrokerName == lastBrokerName) {\n\t\t\treturn mq\n\t\t}\n\t}\n\n\tnotBestBroker := s.pickOneBroker()\n\tif notBestBroker != \"\" {\n\t\twriteQueueNums := topicInfo.GetWriteQueueNumber(notBestBroker)\n\t\tif writeQueueNums > 0 {\n\t\t\tmq := topicInfo.GetNextQueue()\n\t\t\tmq.BrokerName = notBestBroker\n\t\t\tmq.QueueID = rand.Intn(writeQueueNums)\n\t\t\treturn mq\n\t\t}\n\t\ts.latencyTable.Delete(notBestBroker)\n\t}\n\treturn topicInfo.GetNextQueue()\n}", "func (s *stateManager) GetByIP(ip *net.IP) (*Allocation, error) {\n\n\tctx, cancel := context.WithTimeout(context.Background(), s.requestTimeout)\n\tdefer cancel()\n\n\tgr, err := s.kv.Get(ctx, fmt.Sprintf(\"%s/lookup/%s\", etcdPrefix, ip.String()))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif gr.Count == 0 {\n\t\treturn nil, fmt.Errorf(\"No allocation for IP %s in index\", ip.String())\n\t}\n\n\tvar uid uuid.UUID\n\tuid, err = uuid.ParseBytes(gr.Kvs[0].Value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.Get(uid)\n\n}", "func (q *Queue) Active() (uint, error) {\n\treturn q.getAcker().Active()\n}", "func NewQueue() *Queue {\n return &Queue{member: make([]interface{}, 0)}\n}", "func (n *NetworkInterface) Get() (string, error) {\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\t//fmt.Println(\"qu len: \", len(n.Queue))\n\tif len(n.Queue) > 0 {\n\t\ttoReturn := n.Queue[0]\n\t\tn.Queue = n.Queue[1:]\n\t\treturn toReturn, nil\n\t}\n\treturn \"\", errors.New(\"Empty\")\n}", "func (a *ProcessorsApiService) GetState(ctx _context.Context, id string) ProcessorsApiApiGetStateRequest {\n\treturn ProcessorsApiApiGetStateRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func (q *Queue) ID() ipc.ID {\n\treturn q.obj.ID\n}", "func (tcdb *Teocdb) GetQueue(key string) (data []byte, err error) {\n\t// Get free value\n\tvar time time.Time\n\tvar random string\n\tif err = tcdb.session.Query(`SELECT time, random, data FROM queue WHERE key = ? AND lock = '' LIMIT 1 ALLOW FILTERING`,\n\t\tkey).Consistency(gocql.One).Scan(&time, &random, &data); err != nil {\n\t\treturn\n\t}\n\n\t// Loc record (to allow concurency)\n\tvar ok bool\n\tvar lock string\n\tif err = tcdb.session.Query(`UPDATE queue SET lock = 'locked' WHERE key = ? AND time = ? AND random = ? IF lock = ''`,\n\t\tkey, time, random).Consistency(gocql.One).Scan(&ok, &lock); err != nil {\n\t\treturn\n\t}\n\tif !ok {\n\t\treturn tcdb.GetQueue(key)\n\t}\n\n\t// Delete locket record from queue and return value\n\terr = tcdb.session.Query(`DELETE FROM queue WHERE key = ? AND time = ? AND random = ?`,\n\t\tkey, time, random).Exec()\n\treturn\n}", "func SelectQueue(redisHost, redisPort, redisPassword string, redisDB int64, name string) (queue *Queue, err error) {\n\tredisClient := redis.NewClient(&redis.Options{\n\t\tAddr: redisHost + \":\" + redisPort,\n\t\tPassword: redisPassword,\n\t\tDB: redisDB,\n\t})\n\tdefer redisClient.Close()\n\n\tisMember, err := redisClient.SIsMember(masterQueueKey(), name).Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !isMember {\n\t\treturn nil, fmt.Errorf(\"queue with this name doesn't exist\")\n\t}\n\n\treturn newQueue(redisHost, redisPort, redisPassword, redisDB, name), nil\n}", "func sendQueueMessage(message sqs.Message, queueUrl string) (retErr error) {\n\n\tid \t\t\t\t:= *message.MessageAttributes[\"ID\"].StringValue\n\ttopic \t\t\t:= *message.MessageAttributes[\"Topic\"].StringValue\n\tpositive\t\t:= *message.MessageAttributes[\"Positive\"].StringValue\n\tpeopleNum \t\t:= *message.MessageAttributes[\"PeopleNum\"].StringValue\n\tmq\t\t \t\t:= *message.MessageAttributes[\"Mq\"].StringValue\n\n\tsvc := sqs.New(common.Sess)\n\n\treg, err := regexp.Compile(\"[^a-zA-Z0-9]+\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t//Utilizzato per la coda FIFO\n\tdeduplication_ID := reg.ReplaceAllString(queueUrl, \"\")\n\n\t_, err = svc.SendMessage(&sqs.SendMessageInput{\n\t\tMessageAttributes: map[string]*sqs.MessageAttributeValue{\n\t\t\t\"ID\": &sqs.MessageAttributeValue{\n\t\t\t\tDataType: aws.String(\"String\"),\n\t\t\t\tStringValue: aws.String(id),\n\t\t\t},\n\t\t\t\"Positive\": &sqs.MessageAttributeValue{\n\t\t\t\tDataType: aws.String(\"String\"),\n\t\t\t\tStringValue: aws.String(positive),\n\t\t\t},\n\t\t\t\"PeopleNum\": &sqs.MessageAttributeValue{\n\t\t\t\tDataType: aws.String(\"String\"),\n\t\t\t\tStringValue: aws.String(peopleNum),\n\t\t\t},\n\t\t\t\"Mq\": &sqs.MessageAttributeValue{\n\t\t\t\tDataType: aws.String(\"String\"),\n\t\t\t\tStringValue: aws.String(mq),\n\t\t\t},\n\t\t\t\"Topic\": &sqs.MessageAttributeValue{\n\t\t\t\tDataType: aws.String(\"String\"),\n\t\t\t\tStringValue: aws.String(topic),\n\t\t\t},\n\t\t},\n\t\tMessageGroupId: aws.String( deduplication_ID + \"groupID\"),\n\t\tMessageDeduplicationId: aws.String(deduplication_ID + strconv.Itoa(time.Now().Nanosecond())),\n\t\tMessageBody: aws.String(*message.Body),\n\t\tQueueUrl: &queueUrl,\n\n\t})\n\tif err != nil {\n\t\tcommon.Warning(\"[BROKER] Errore nell'invio del messaggio. \" + err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func (bq *InMemoryBuildQueue) GetOperation(ctx context.Context, request *buildqueuestate.GetOperationRequest) (*buildqueuestate.GetOperationResponse, error) {\n\tbq.enter(bq.clock.Now())\n\tdefer bq.leave()\n\n\to, ok := bq.operationsNameMap[request.OperationName]\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.NotFound, \"Operation %#v not found\", request.OperationName)\n\t}\n\ts := o.getOperationState(bq)\n\ts.Name = \"\"\n\treturn &buildqueuestate.GetOperationResponse{\n\t\tOperation: s,\n\t}, nil\n}", "func (f *ccFixture) popQueue() {\n\tf.T().Helper()\n\n\tdone := make(chan error)\n\tgo func() {\n\t\titem, _ := f.q.Get()\n\t\t_, err := f.tfr.Reconcile(f.ctx, item.(reconcile.Request))\n\t\tf.q.Done(item)\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-time.After(time.Second):\n\t\tf.T().Fatal(\"timeout waiting for workqueue\")\n\tcase err := <-done:\n\t\tassert.NoError(f.T(), err)\n\t}\n}", "func makeQueuePolicy(queueARN string, src *v1alpha1.AWSS3Source) iam.Policy {\n\tbucketARN := s3.RealBucketARN(src.Spec.ARN)\n\taccID := src.Spec.ARN.AccountID\n\n\treturn iam.NewPolicy(\n\t\tnewS3ToSQSPolicyStatement(queueARN, bucketARN, accID),\n\t)\n}", "func (r DescribeBandwidthsRequest) GetRegionId() string {\n return \"\"\n}", "func (a *Client) GetMsgVpnQueue(params *GetMsgVpnQueueParams, authInfo runtime.ClientAuthInfoWriter) (*GetMsgVpnQueueOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetMsgVpnQueueParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getMsgVpnQueue\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/msgVpns/{msgVpnName}/queues/{queueName}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetMsgVpnQueueReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\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.(*GetMsgVpnQueueOK), nil\n\n}", "func NewPriorityQueue(inCh <-chan *pb.Flow, outCh chan<- *pb.Flow) {\n\tt := time.NewTicker(time.Second)\n\t// TODO write logic to return flows depending in the number of flows\n\t// received per second. (i.e., if we receive 100 flows/s and we are not receiving\n\t// 1 flow/s we should keep returning 100 flows/s and decreasing the number\n\t// of flows/s until we reach 1 flow/s\n\tNewPriorityQueueWith(inCh, outCh, t.C)\n}", "func (pq TimeToExpirePriorityQueue) Peek() *ItemToExpire {\n\treturn pq[0]\n}" ]
[ "0.6420932", "0.5977712", "0.5420494", "0.53960836", "0.5246199", "0.48895094", "0.47974697", "0.4722064", "0.4676575", "0.45463547", "0.45444638", "0.45172334", "0.4422663", "0.43709758", "0.43634933", "0.43407527", "0.43357632", "0.4238608", "0.42307967", "0.4191139", "0.41882056", "0.4182098", "0.418085", "0.41756102", "0.41725394", "0.41586414", "0.4158321", "0.41522166", "0.41465425", "0.413632", "0.41277578", "0.41264924", "0.41233465", "0.41095227", "0.41046017", "0.40974087", "0.40888113", "0.40873536", "0.4084625", "0.4084247", "0.40831095", "0.4073419", "0.4064001", "0.40531227", "0.40517524", "0.404864", "0.40470043", "0.40308943", "0.40189847", "0.40155917", "0.40118468", "0.40092707", "0.40012118", "0.3990536", "0.39891505", "0.39837813", "0.39820427", "0.39815572", "0.39744633", "0.39726022", "0.3968337", "0.39629403", "0.3946842", "0.39460742", "0.39444956", "0.39389336", "0.39334488", "0.39304736", "0.3925374", "0.39208892", "0.39106986", "0.39066544", "0.39062992", "0.3905521", "0.3903948", "0.3903481", "0.3901006", "0.3894378", "0.3888265", "0.3887713", "0.38872814", "0.38802382", "0.38770506", "0.38662127", "0.38645974", "0.38617492", "0.386117", "0.38577998", "0.38534185", "0.38523147", "0.3851924", "0.38412717", "0.383326", "0.3831673", "0.3827921", "0.38276193", "0.38211888", "0.38198796", "0.38177356", "0.3817561" ]
0.77743757
0
The DSCP value of the traffic packet to be matched in the current queue, ranging from 0 to 63.
func (o InterRegionTrafficQosQueueOutput) Dscps() pulumi.StringArrayOutput { return o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringArrayOutput { return v.Dscps }).(pulumi.StringArrayOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p UDPPort) Value() int32 {\n\treturn p.port\n}", "func getCNTFRQ() TSCValue", "func (p TCPPort) Value() int32 {\n\treturn p.port\n}", "func (p FlowProtocol) Value() int32 {\n\treturn int32(p)\n}", "func (this *VlqBase128Be) Value() (v int, err error) {\n\tif (this._f_value) {\n\t\treturn this.value, nil\n\t}\n\ttmp3, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttmp4, err := this.Groups[tmp3].Value()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar tmp5 int;\n\ttmp6, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp6 >= 1) {\n\t\ttmp7, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp8, err := this.Groups[(tmp7 - 1)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp5 = (tmp8 << 7)\n\t} else {\n\t\ttmp5 = 0\n\t}\n\tvar tmp9 int;\n\ttmp10, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp10 >= 2) {\n\t\ttmp11, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp12, err := this.Groups[(tmp11 - 2)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp9 = (tmp12 << 14)\n\t} else {\n\t\ttmp9 = 0\n\t}\n\tvar tmp13 int;\n\ttmp14, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp14 >= 3) {\n\t\ttmp15, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp16, err := this.Groups[(tmp15 - 3)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp13 = (tmp16 << 21)\n\t} else {\n\t\ttmp13 = 0\n\t}\n\tvar tmp17 int;\n\ttmp18, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp18 >= 4) {\n\t\ttmp19, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp20, err := this.Groups[(tmp19 - 4)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp17 = (tmp20 << 28)\n\t} else {\n\t\ttmp17 = 0\n\t}\n\tvar tmp21 int;\n\ttmp22, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp22 >= 5) {\n\t\ttmp23, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp24, err := this.Groups[(tmp23 - 5)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp21 = (tmp24 << 35)\n\t} else {\n\t\ttmp21 = 0\n\t}\n\tvar tmp25 int;\n\ttmp26, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp26 >= 6) {\n\t\ttmp27, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp28, err := this.Groups[(tmp27 - 6)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp25 = (tmp28 << 42)\n\t} else {\n\t\ttmp25 = 0\n\t}\n\tvar tmp29 int;\n\ttmp30, err := this.Last()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif (tmp30 >= 7) {\n\t\ttmp31, err := this.Last()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp32, err := this.Groups[(tmp31 - 7)].Value()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\ttmp29 = (tmp32 << 49)\n\t} else {\n\t\ttmp29 = 0\n\t}\n\tthis.value = int((((((((tmp4 + tmp5) + tmp9) + tmp13) + tmp17) + tmp21) + tmp25) + tmp29))\n\tthis._f_value = true\n\treturn this.value, nil\n}", "func (this *VlqBase128Be_Group) Value() (v int, err error) {\n\tif (this._f_value) {\n\t\treturn this.value, nil\n\t}\n\tthis.value = int((this.B & 127))\n\tthis._f_value = true\n\treturn this.value, nil\n}", "func (d *DataPacket) Priority() byte {\n\treturn d.data[108]\n}", "func (this *RTPPacket) GetSSRC() uint32 {\n\treturn this.header.ssrc\n}", "func (rt *RecvTxOut) Value() int64 {\n\ttx := rt.tx.MsgTx()\n\treturn tx.TxOut[rt.outpoint.Index].Value\n}", "func (q *UnsafeQueue16) Get() (val uint16, ok bool) {\n\tif q.putPos == q.getPos {\n\t\truntime.Gosched()\n\t\treturn 0, false\n\t}\n\tval = q.cache[q.getPos&q.capMod]\n\tq.getPos++\n\treturn val, true\n}", "func (d *DataPacket) Sequence() byte {\n\treturn d.data[111]\n}", "func (l *FixedLimiter) Value() int64 {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\treturn l.value\n}", "func Get() int {\n\tfor i := maxReservedTCPPort; i < maxTCPPort; i++ {\n\t\tp := tcpPortRand.Intn(maxRandTCPPort) + maxReservedTCPPort + 1\n\t\tif IsAvailable(p) {\n\t\t\treturn p\n\t\t}\n\t}\n\treturn -1\n}", "func (p *Packet) GetPacketID() (PacketID [16]byte) {\n}", "func (p *Packet) GetStreamID() (StreamID uint32) {\n}", "func (c *ControlPacket) PacketID() uint16 {\n\tswitch r := c.Content.(type) {\n\tcase *Publish:\n\t\treturn r.PacketID\n\tcase *Puback:\n\t\treturn r.PacketID\n\tcase *Pubrec:\n\t\treturn r.PacketID\n\tcase *Pubrel:\n\t\treturn r.PacketID\n\tcase *Pubcomp:\n\t\treturn r.PacketID\n\tcase *Subscribe:\n\t\treturn r.PacketID\n\tcase *Suback:\n\t\treturn r.PacketID\n\tcase *Unsubscribe:\n\t\treturn r.PacketID\n\tcase *Unsuback:\n\t\treturn r.PacketID\n\tdefault:\n\t\treturn 0\n\t}\n}", "func (q *UnsafeQueue16) Quantity() uint16 {\n\tif q.putPos >= q.getPos {\n\t\treturn q.putPos - q.getPos\n\t}\n\treturn q.capMod + (q.putPos - q.getPos)\n}", "func (w *WrapperClient) Value() int {\n\tw.mux.Lock()\n\tdefer w.mux.Unlock()\n\n\treturn w.streamQuota\n}", "func getPointerValue(bytes []byte) (int, error) {\n\tpointer := -1\n\tif len(bytes) < 2 {\n\t\treturn pointer, errors.New(fmt.Sprint(\"bytes too short to deserialize dnsmessage.Header, expected at least 12 bytes but got\", len(bytes)))\n\t}\n\n\tvar pointerMask byte = 0b11000000\n\tif bytes[0]&pointerMask > 0 {\n\t\tpointerBytes := make([]byte, 2)\n\t\tcopy(pointerBytes, bytes)\n\t\t//Flip masked bites to not include them in pointer val\n\t\tpointerBytes[0] = pointerBytes[0] & (^pointerMask)\n\t\t// unsignes16 to signed int first to preseve the signed bit, then to int.\n\t\tpointer = int(binary.BigEndian.Uint16(pointerBytes))\n\t}\n\n\treturn pointer, nil\n}", "func (p Packet) GsMsgID() byte {\n\treturn p[0]\n}", "func (c *connAttrs) Dfv() int { c.mu.RLock(); defer c.mu.RUnlock(); return c._dfv }", "func (sc *SafeCounter) Value(key string) int {\n\tsc.mux.Lock()\n\t// Lock so only one goroutine at a time can access the map sc.v\n\tdefer sc.mux.Unlock()\n\treturn sc.v[key]\n}", "func (c *Cell) value() byte {\n\tif c.sv != 0 {\n\t\treturn c.sv\n\t}\n\tif !c.resolved() {\n\t\treturn 0\n\t}\n\tvar sv byte\n\tfor i := byte(0); i < GridSize; i++ {\n\t\tif !c.mask[i] {\n\t\t\tif sv != 0 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\tsv = i + 1\n\t\t}\n\t}\n\treturn sv\n}", "func (this *RTPPacket) GetCSRC(num uint8) uint32 {\n\tif num >= this.header.csrccount {\n\t\treturn 0\n\t}\n\n\treturn this.header.csrc[num]\n}", "func (r *RawPacket) DestinationSSRC() []uint32 {\n\treturn []uint32{}\n}", "func (l *RateLimiter) Value() int64 {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\treturn l.value\n}", "func (s *PacketDurationQueue) Dequeue() float32 {\n\ts.lock.Lock()\n\titem := s.items[0]\n\ts.items = s.items[1:len(s.items)]\n\ts.lock.Unlock()\n\treturn item\n}", "func (k *PolicyKey) GetDestPort() uint16 {\n\treturn byteorder.NetworkToHost16(k.DestPortNetwork)\n}", "func (fo FifoOption) Value() int {\n\treturn int(fo)\n}", "func parseDSCP(dscp string) (uint8, bool) {\n\tif s, err := strconv.ParseUint(dscp, 10, 6); err == nil {\n\t\treturn uint8(s), true\n\t}\n\tdscp = strings.ToUpper(dscp)\n\tswitch dscp {\n\tcase \"BE\":\n\t\tfallthrough\n\tcase \"DF\":\n\t\tfallthrough\n\tcase \"CS0\":\n\t\treturn 0x00, true\n\tcase \"CS1\":\n\t\treturn 0x08, true\n\tcase \"AF11\":\n\t\treturn 0x0A, true\n\tcase \"AF12\":\n\t\treturn 0x0C, true\n\tcase \"AF13\":\n\t\treturn 0x0E, true\n\tcase \"CS2\":\n\t\treturn 0x10, true\n\tcase \"AF21\":\n\t\treturn 0x12, true\n\tcase \"AF22\":\n\t\treturn 0x14, true\n\tcase \"AF23\":\n\t\treturn 0x16, true\n\tcase \"CS3\":\n\t\treturn 0x18, true\n\tcase \"AF31\":\n\t\treturn 0x1A, true\n\tcase \"AF32\":\n\t\treturn 0x1C, true\n\tcase \"AF33\":\n\t\treturn 0x1E, true\n\tcase \"CS4\":\n\t\treturn 0x20, true\n\tcase \"AF41\":\n\t\treturn 0x22, true\n\tcase \"AF42\":\n\t\treturn 0x24, true\n\tcase \"AF43\":\n\t\treturn 0x26, true\n\tcase \"CS5\":\n\t\treturn 0x28, true\n\tcase \"EF\":\n\t\treturn 0x2E, true\n\tcase \"CS6\":\n\t\treturn 0x30, true\n\tcase \"LE\":\n\t\treturn 0x01, true\n\tdefault:\n\t\treturn 0, false\n\t}\n}", "func (ip IPv4) Value() string {\n\treturn ip.value\n}", "func (p *Packet) GetDestinationUIP() (DestinationUIP [16]byte) {\n}", "func (st *FixedFIFO) GetCap() int {\n\tst.Lock()\n\tdefer st.Unlock()\n\n\treturn cap(st.queue)\n}", "func (r *ReadStreamSRTCP) GetSSRC() uint32 {\n\treturn r.ssrc\n}", "func (q *UnsafeQueue64) Get() (val uint64, ok bool) {\n\tif q.putPos == q.getPos {\n\t\truntime.Gosched()\n\t\treturn 0, false\n\t}\n\tval = q.cache[q.getPos&q.capMod]\n\tq.getPos++\n\treturn val, true\n}", "func (a *SequenceNumber) GetSQN() (sQN uint8) {}", "func (q *Queue) Peek() int {\n\tif q.start.next != nil {\n\t\t_iteratePeek(q.start)\n\t}\n\treturn q.start.val\n}", "func (this *MyQueue) Peek() int {\n\treturn this.Stack[0]\n}", "func (this *DeployLock) value() int {\n\tthis.mutex.Lock()\n\tdefer this.mutex.Unlock()\n\treturn this.numStarted\n}", "func (this *RTPPacket) GetCSRCCount() uint8 {\n\treturn this.header.csrccount\n}", "func (q *MyQueue) Peek() int {\n\tfront := q.list.Front()\n\tres := front.Value.(int)\n\treturn res\n}", "func bufferValue(index uint16, buffer []byte) (uint8, bool) {\n\ti := int(index)\n\ttotal := uint8(0)\n\tswitch buffer[i] {\n\tcase '0':\n\tcase '1':\n\t\ttotal += 16 * 1\n\tcase '2':\n\t\ttotal += 16 * 2\n\tcase '3':\n\t\ttotal += 16 * 3\n\tcase '4':\n\t\ttotal += 16 * 4\n\tcase '5':\n\t\ttotal += 16 * 5\n\tcase '6':\n\t\ttotal += 16 * 6\n\tcase '7':\n\t\ttotal += 16 * 7\n\tcase '8':\n\t\ttotal += 16 * 8\n\tcase '9':\n\t\ttotal += 16 * 9\n\tcase 'a', 'A':\n\t\ttotal += 16 * 10\n\tcase 'b', 'B':\n\t\ttotal += 16 * 11\n\tcase 'c', 'C':\n\t\ttotal += 16 * 12\n\tcase 'd', 'D':\n\t\ttotal += 16 * 13\n\tcase 'e', 'E':\n\t\ttotal += 16 * 14\n\tcase 'f', 'F':\n\t\ttotal += 16 * 15\n\tdefault:\n\t\tprint(\"!bad character in payload hi byte(number #\", i, \"):\", buffer[i], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\tswitch buffer[i+1] {\n\tcase '0':\n\tcase '1':\n\t\ttotal++\n\tcase '2':\n\t\ttotal += 2\n\tcase '3':\n\t\ttotal += 3\n\tcase '4':\n\t\ttotal += 4\n\tcase '5':\n\t\ttotal += 5\n\tcase '6':\n\t\ttotal += 6\n\tcase '7':\n\t\ttotal += 7\n\tcase '8':\n\t\ttotal += 8\n\tcase '9':\n\t\ttotal += 9\n\tcase 'a', 'A':\n\t\ttotal += 10\n\tcase 'b', 'B':\n\t\ttotal += 11\n\tcase 'c', 'C':\n\t\ttotal += 12\n\tcase 'd', 'D':\n\t\ttotal += 13\n\tcase 'e', 'E':\n\t\ttotal += 14\n\tcase 'f', 'F':\n\t\ttotal += 15\n\tdefault:\n\t\tprint(\"!bad character in payload low byte (number #\", i+1, \"):\", buffer[i+1], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\treturn total, true\n}", "func bufferValue(index uint16, buffer []byte) (uint8, bool) {\n\ti := int(index)\n\ttotal := uint8(0)\n\tswitch buffer[i] {\n\tcase '0':\n\tcase '1':\n\t\ttotal += 16 * 1\n\tcase '2':\n\t\ttotal += 16 * 2\n\tcase '3':\n\t\ttotal += 16 * 3\n\tcase '4':\n\t\ttotal += 16 * 4\n\tcase '5':\n\t\ttotal += 16 * 5\n\tcase '6':\n\t\ttotal += 16 * 6\n\tcase '7':\n\t\ttotal += 16 * 7\n\tcase '8':\n\t\ttotal += 16 * 8\n\tcase '9':\n\t\ttotal += 16 * 9\n\tcase 'a', 'A':\n\t\ttotal += 16 * 10\n\tcase 'b', 'B':\n\t\ttotal += 16 * 11\n\tcase 'c', 'C':\n\t\ttotal += 16 * 12\n\tcase 'd', 'D':\n\t\ttotal += 16 * 13\n\tcase 'e', 'E':\n\t\ttotal += 16 * 14\n\tcase 'f', 'F':\n\t\ttotal += 16 * 15\n\tdefault:\n\t\tprint(\"!bad character in payload hi byte(number #\", i, \"):\", buffer[i], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\tswitch buffer[i+1] {\n\tcase '0':\n\tcase '1':\n\t\ttotal++\n\tcase '2':\n\t\ttotal += 2\n\tcase '3':\n\t\ttotal += 3\n\tcase '4':\n\t\ttotal += 4\n\tcase '5':\n\t\ttotal += 5\n\tcase '6':\n\t\ttotal += 6\n\tcase '7':\n\t\ttotal += 7\n\tcase '8':\n\t\ttotal += 8\n\tcase '9':\n\t\ttotal += 9\n\tcase 'a', 'A':\n\t\ttotal += 10\n\tcase 'b', 'B':\n\t\ttotal += 11\n\tcase 'c', 'C':\n\t\ttotal += 12\n\tcase 'd', 'D':\n\t\ttotal += 13\n\tcase 'e', 'E':\n\t\ttotal += 14\n\tcase 'f', 'F':\n\t\ttotal += 15\n\tdefault:\n\t\tprint(\"!bad character in payload low byte (number #\", i+1, \"):\", buffer[i+1], \"\\n\")\n\t\treturn 0xff, false\n\t}\n\treturn total, true\n}", "func (v *Value) TTL() time.Duration { return dnsutil.MinTTL(v.msg) }", "func (sNode *PowerNode) GetValue() int {\n\treturn sNode.value\n}", "func (cc PipConstraints) Value() string {\n\treturn cc.value\n}", "func (s *Stack) Peek() int {\n\tif s.length == 0 {\n\t\treturn MIN\n\t}\n\treturn s.top.value\n}", "func (r *ReplyTopic) PacketID() uint16 {\n\treturn r.p\n}", "func (cpu *CPU) pull() byte {\n\tcpu.sp++\n\treturn cpu.read(0x100 | uint16(cpu.sp))\n}", "func (this *MyQueue) Peek() int {\n\treturn this.stack.Top()\n}", "func (c *Counter) Value() uint64 {\n\treturn atomic.LoadUint64(c.addr())\n}", "func (cpu *CPU) S_C() int {\r\n\treturn int(cpu.Sr() & 1)\r\n}", "func (fi *FastIntegerHashMap) Get(key uint64) (uint64, bool) {\n\treturn fi.packets.get(key)\n}", "func (this *MyQueue) Peek() int {\n\treturn this.q[len(this.q)-1]\n}", "func (m Message) Value() []byte {\n\tstart, end, size := m.valueOffsets()\n\tif size == -1 {\n\t\treturn nil\n\t}\n\treturn m[start+4 : end]\n}", "func (m match) dist() uint32 {\n\treturn uint32(m.distance - minDistance)\n}", "func (f Fixed8) Value() int64 {\n\treturn int64(f) / int64(decimals)\n}", "func getPortForSentKey(key int) int {\n\tkeyList := getSortedKeyList()\n\tfor _, value := range keyList {\n\t\tkeyListPort := getPortFromKey(uint32(value))\n\t\tif key < value {\n\t\t\treturn keyListPort\n\t\t}\n\t}\n\treturn getPortFromKey(uint32(keyList[0])) // returns first node in chain if wrap around\n}", "func (p *payload) calculatePacketSize() int32 {\n\treturn int32(len(p.packetBody) + 4 + 4 + 2)\n}", "func (s *StringChecksum) Value() string {\n\treturn s.value\n}", "func DetectPacket(src []byte) (int, Type) {\n\t// check for minimum size\n\tif len(src) < 2 {\n\t\treturn 0, 0\n\t}\n\n\t// get type\n\tt := Type(src[0] >> 4)\n\n\t// get remaining length\n\t_rl, n := binary.Uvarint(src[1:])\n\trl := int(_rl)\n\n\tif n <= 0 {\n\t\treturn 0, 0\n\t}\n\n\treturn 1 + n + rl, t\n}", "func (c *chdPoker) get(key uint32) uint16 {\n\n\th := hasherPoker(key) ^ c.r[0]\n\n\tri := c.indices[h%2444]\n\n\tr := c.r[ri]\n\n\tti := (h ^ r) % 4888\n\n\tv := c.values[ti]\n\n\treturn v\n}", "func (m *mechanism) SrcPort() int {\n\tsrcPortStr := m.GetParameters()[SrcPort]\n\tif srcPortStr == \"\" {\n\t\treturn 0\n\t}\n\tsrcPort, err := strconv.ParseInt(srcPortStr, 10, 64)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn int(srcPort)\n}", "func (u *unvisited) d() int {\n\treturn u.dist.get(u.p)\n}", "func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 {\n\tswitch {\n\tcase n < 44:\n\t\treturn uint16(nfcValues[n<<6+uint32(b)])\n\tdefault:\n\t\tn -= 44\n\t\treturn uint16(nfcSparse.lookup(n, b))\n\t}\n}", "func (p *Processor) ValueForNode(k string) (v uint16) {\n\treturn p.Nodes[k].Value(0)\n}", "func (this *Stats) SendBitRate() float32 { return float32(this.ptr.f_send_bitrate) }", "func (s Stash) Value() string {\n\tvals := utils.MapKeys(s.payload)\n\tif len(vals) < 1 {\n\t\treturn \"\"\n\t}\n\n\treturn expand(fmt.Sprintf(\"%v\", vals[0]))\n}", "func (pq *MinPQueue) GetMin() string {\n\tqueue := *pq\n\treturn queue[0].value\n}", "func (s *Slave) Packet() *Packet {\n\treturn s.p\n}", "func (d *distance) get() int {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\treturn d.v\n}", "func (c *SafeCounter) Value() int {\n\tc.mu.Lock()\n\t// Lock so only one goroutine at a time can access the variable\n\tdefer c.mu.Unlock()\n\treturn c.v\n}", "func (q *Queue) dequeue() int {\n\tif q.isEmpty() {\n\t\tfmt.Println(\"Queue empty\")\n\t\treturn -1\n\t}\n\tvalue := q.values[0]\n\tq.values = q.values[1:]\n\treturn value\n}", "func (n *Node) Value(depth int) (v uint16) {\n\tif depth > 100 {\n\t\tfmt.Println(\"Too deep for\", n)\n\t\treturn\n\t}\n\tif n.cacheval != 0 {\n\t\treturn n.cacheval\n\t}\n\t//fmt.Printf(\"(%d) %s\\n\", depth, n)\n\tvar l, r uint16\n\tif n.Lref != \"\" {\n\t\t//fmt.Println(n.Op, \"finding value for l =\", n.Lref)\n\t\tl = n.P.NodeByKey(n.Lref).Value(depth + 1)\n\t} else {\n\t\t//fmt.Println(n.Op, \"using Lval\", n.Lval)\n\t\tl = n.Lval\n\t}\n\n\tif n.Rref != \"\" {\n\t\t//fmt.Println(n.Op, \"finding value for r =\", n.Rref)\n\t\tr = n.P.NodeByKey(n.Rref).Value(depth + 1)\n\t} else {\n\t\t//fmt.Println(n.Op, \"using Rval\", n.Rval)\n\t\tr = n.Rval\n\t}\n\n\tn.cacheval = n.F(l, r)\n\treturn n.cacheval\n}", "func (network *Network) SendFindValuePacket(contact Contact, hash string) {\n\tcreatedPacket := network.CreatePacket(\"find_value\", network.me.Address, network.me.ID.String(), contact.ID.String(), nil, []byte(hash))\n\tnetwork.SendPacket(createdPacket, contact.Address)\n}", "func (q *UnsafeQueue64) Quantity() uint64 {\n\tif q.putPos >= q.getPos {\n\t\treturn q.putPos - q.getPos\n\t}\n\treturn q.capMod + (q.putPos - q.getPos)\n}", "func (id MatchID) Value() (driver.Value, error) {\n\treturn id[:], nil // []byte\n}", "func (a *Sequence) Value() uint64 {\n\ta.m.Lock()\n\tdefer a.m.Unlock()\n\treturn a.n\n}", "func pcValue(tab []byte, target uint64, arch *sys.Arch) int32 {\n\tval := int32(-1)\n\tvar pc uint64\n\tfor step(&tab, &pc, &val, pc == 0, arch) {\n\t\tif target < pc {\n\t\t\treturn val\n\t\t}\n\t}\n\treturn -1\n}", "func (self *MonoTimer) Value() int64 {\n\tcurrentTime := GetMonoTime()\n\n\treturn currentTime - self.startTime\n}", "func (shaper *ByteSequenceShaper) findMatchingPacket(sequence []byte) *SequenceModel {\n\tfor i, model := range shaper.RemoveSequences {\n\t\ttarget := model.Sequence\n\t\tsource := sequence[int(model.Offset) : int(model.Offset)+len(target)]\n\t\tif bytes.Equal(source, target) {\n\t\t\t// Remove matched packet so that it's not matched again\n\t\t\tshaper.RemoveSequences = append(shaper.RemoveSequences[:i], shaper.RemoveSequences[i+1:]...)\n\n\t\t\t// Return matched packet\n\t\t\treturn model\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *safeCounter) Value() int {\n\tc.mux.Lock()\n\tdefer c.mux.Unlock()\n\treturn c.cnt\n}", "func (cmd *MonitorStatus) SetValue(result *Result) error {\n\texpAmount := 4\n\tpayload := result.value[2:]\n\tamount := len(payload)\n\n\tif amount != expAmount {\n\t\treturn fmt.Errorf(\n\t\t\t\"Expected %d bytes of payload, got %d\", expAmount, amount,\n\t\t)\n\t}\n\n\t// 0x80 is the MSB: 0b10000000\n\tcmd.MilActive = (payload[0] & 0x80) == 0x80\n\t// 0x7F everything but the MSB: 0b01111111\n\tcmd.DtcAmount = byte(payload[0] & 0x7F)\n\n\treturn nil\n}", "func (m *DomainDnsSrvRecord) GetPriority()(*int32) {\n val, err := m.GetBackingStore().Get(\"priority\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func (h sendPacketHeap) Min(greaterEqual packet.PacketID, lessEqual packet.PacketID) (*packet.DataPacket, int) {\n\tlen := len(h)\n\tidx := 0\n\twrapped := greaterEqual.Seq > lessEqual.Seq\n\tfor idx < len {\n\t\tpid := h[idx].pkt.Seq\n\t\tvar next int\n\t\tif pid.Seq == greaterEqual.Seq {\n\t\t\treturn h[idx].pkt, idx\n\t\t} else if pid.Seq >= greaterEqual.Seq {\n\t\t\tnext = idx * 2\n\t\t} else {\n\t\t\tnext = idx*2 + 1\n\t\t}\n\t\tif next >= len && h[idx].pkt.Seq.Seq > greaterEqual.Seq && (wrapped || h[idx].pkt.Seq.Seq <= lessEqual.Seq) {\n\t\t\treturn h[idx].pkt, idx\n\t\t}\n\t\tidx = next\n\t}\n\n\t// can't find any packets with greater value, wrap around\n\tif wrapped {\n\t\tidx = 0\n\t\tfor {\n\t\t\tnext := idx * 2\n\t\t\tif next >= len && h[idx].pkt.Seq.Seq <= lessEqual.Seq {\n\t\t\t\treturn h[idx].pkt, idx\n\t\t\t}\n\t\t\tidx = next\n\t\t}\n\t}\n\treturn nil, -1\n}", "func (p *Suback) PacketIdentifier() uint16 {\n\tpid, _ := p.uint16(p.packetIDPos)\n\treturn pid\n}", "func (packet *DemoValuePacket) GetID() int64 {\n\treturn packet.ID\n}", "func (q *Queue) Tail() uint64 { return q.tail }", "func (cmd *DistSinceDTCClear) SetValue(result *Result) error {\n\tpayload, err := result.PayloadAsUInt16()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Value = uint32(payload)\n\n\treturn nil\n}", "func (t *VTIntStr) RedisValue() string {\n\treturn fmt.Sprintf(\"%d %s\", t.Key, t.Value)\n}", "func (t *VTIntDbl) RedisValue() string {\n\treturn fmt.Sprintf(\"%d %v\", t.Key, t.Value)\n}", "func (kcp *KCP) PeekSize() (length int) {\n\tif len(kcp.rcv_queue) == 0 {\n\t\treturn -1\n\t}\n\n\tseg := &kcp.rcv_queue[0]\n\tif seg.frg == 0 {\n\t\treturn seg.data.Len()\n\t}\n\n\tif len(kcp.rcv_queue) < int(seg.frg+1) {\n\t\treturn -1\n\t}\n\n\tfor k := range kcp.rcv_queue {\n\t\tseg := &kcp.rcv_queue[k]\n\t\tlength += seg.data.Len()\n\t\tif seg.frg == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func (shaper *ByteSequenceShaper) findNextPacket(index int8) *SequenceModel {\n\tfor _, sequence := range shaper.AddSequences {\n\t\tif index == sequence.Index {\n\t\t\treturn sequence\n\t\t}\n\t}\n\n\treturn nil\n}", "func (q *TaskQueue) Pop() int {\n\tif q.Count == 0 {\n\t\treturn -1\n\t}\n\tnode := q.Nodes[q.Head]\n\tq.Head = (q.Head + 1) % q.Size\n\tq.Count--\n\treturn node\n}", "func (q *OperationQueue) SuggestValue() (consensus.SlotValue, bool) {\n\tkey, chunk := q.NewChunk(q.Operations())\n\tif chunk == nil {\n\t\t// q.Logf(\"has no suggestion\")\n\t\treturn consensus.SlotValue(\"\"), false\n\t}\n\tq.Logf(\"i=%d, suggests %s = %s\", q.slot, util.Shorten(string(key)), chunk)\n\treturn key, true\n}", "func (p Prometheus) Value() (float64, error) {\n\tresp, err := http.Get(p.URL)\n\tif err != nil {\n\t\treturn -1.0, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn -1.0, err\n\t}\n\tfvalue, err := p.findValue(resp.Body)\n\tif err != nil {\n\t\treturn -1.0, err\n\t}\n\treturn fvalue, nil\n}", "func (q *Queue) Peek() interface{} {\n\treturn q.data.Front().Value\n}", "func (cpu *CPU) Sp() uint16 {\r\n\treturn cpu.regs[1]\r\n}", "func (m *mechanism) DstPort() int {\n\tdstPortStr := m.GetParameters()[DstPort]\n\tif dstPortStr != \"\" {\n\t\treturn 0\n\t}\n\n\tdstPort, err := strconv.ParseInt(dstPortStr, 10, 64)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn int(dstPort)\n}", "func (b *BlockchainIterator) Value() (*msg.Packet, error) {\n\tif b.Err != nil {\n\t\treturn nil, b.Err\n\t}\n\treturn &b.Tip, nil\n}" ]
[ "0.5506935", "0.5470176", "0.53617424", "0.5298042", "0.52958035", "0.5238294", "0.51907325", "0.5134276", "0.49141097", "0.4898104", "0.4896561", "0.4892348", "0.48907828", "0.48768947", "0.4873316", "0.48707613", "0.4837199", "0.4807118", "0.47696432", "0.47665495", "0.47518072", "0.47436073", "0.47417095", "0.47392398", "0.47273389", "0.47019967", "0.46999073", "0.4693401", "0.4683361", "0.46734327", "0.4669734", "0.46499237", "0.46414936", "0.4628151", "0.46213943", "0.4599653", "0.45956963", "0.45810825", "0.4578567", "0.4569302", "0.45672897", "0.4561258", "0.4561258", "0.45587343", "0.45486766", "0.45431954", "0.45396686", "0.4530643", "0.4523055", "0.45179015", "0.45139655", "0.4495002", "0.44910032", "0.4487237", "0.44841716", "0.448297", "0.44822896", "0.448196", "0.44784808", "0.4471623", "0.44607794", "0.44574073", "0.445445", "0.44524166", "0.44522306", "0.44469815", "0.4442737", "0.44399473", "0.44378847", "0.44378784", "0.4436744", "0.44351485", "0.44248882", "0.442016", "0.4416668", "0.4413539", "0.44129473", "0.4406878", "0.4389175", "0.43886083", "0.43811485", "0.43801117", "0.43799675", "0.43779856", "0.4377185", "0.43691897", "0.4366847", "0.436577", "0.43600187", "0.43537658", "0.4352114", "0.4351012", "0.43501586", "0.43481824", "0.4342267", "0.43415406", "0.43412414", "0.4340896", "0.433982", "0.43277496" ]
0.47516108
21
The description information of the traffic scheduling policy.
func (o InterRegionTrafficQosQueueOutput) InterRegionTrafficQosQueueDescription() pulumi.StringPtrOutput { return o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringPtrOutput { return v.InterRegionTrafficQosQueueDescription }).(pulumi.StringPtrOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o OrganizationSecurityPolicyOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *OrganizationSecurityPolicy) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (s *SecurityRule) Description() string {\n\treturn s.Description_\n}", "func (o ServerPolicyOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServerPolicy) pulumi.StringOutput { return v.Description }).(pulumi.StringOutput)\n}", "func (o InstanceMaintenancePolicyOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicy) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenancePolicyOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceMaintenancePolicy) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o ResiliencyPolicyOutput) PolicyDescription() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResiliencyPolicy) pulumi.StringPtrOutput { return v.PolicyDescription }).(pulumi.StringPtrOutput)\n}", "func (o SecurityPolicyRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRule) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o AuthorizationPolicyOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AuthorizationPolicy) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o EndpointAclPolicyOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EndpointAclPolicy) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o FirewallPolicyRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FirewallPolicyRule) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (*TriggeringPolicy) Descriptor() ([]byte, []int) {\n\treturn file_go_chromium_org_luci_scheduler_appengine_messages_config_proto_rawDescGZIP(), []int{3}\n}", "func (r *AutoVLANCfgResource) Description() string {\n\treturn AutoVLANResource\n}", "func (a *CMP) Description() string {\n\treturn \"Configuration for CMP Server to send metrics to.\"\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleResponseOutput) Schedule() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyScheduleResponse) string { return v.Schedule }).(pulumi.StringOutput)\n}", "func (o GetEndpointAclPoliciesPolicyOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointAclPoliciesPolicy) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicySchedule) *string { return v.Schedule }).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyExemptionOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyExemption) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (*ScheduleTimeoutDetails) Descriptor() ([]byte, []int) {\n\treturn file_github_com_dogmatiq_enginekit_enginetest_internal_action_action_proto_rawDescGZIP(), []int{1}\n}", "func (o WorkloadStatusConfigStaticOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v WorkloadStatusConfigStatic) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o SecurityPolicyRuleResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SecurityPolicyRuleResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (m *ManagedAppPolicy) GetDescription()(*string) {\n return m.description\n}", "func (o LookupFirewallPolicyResultOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.Description }).(pulumi.StringOutput)\n}", "func (*RunnableResourcePolicySet_Policy_Rule) Descriptor() ([]byte, []int) {\n\treturn file_cerbos_runtime_v1_runtime_proto_rawDescGZIP(), []int{1, 1, 0}\n}", "func (o RouterNatRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterNatRule) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o FirewallPolicyRuleResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FirewallPolicyRuleResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (*RunnableResourcePolicySet_Policy) Descriptor() ([]byte, []int) {\n\treturn file_cerbos_runtime_v1_runtime_proto_rawDescGZIP(), []int{1, 1}\n}", "func (o TlsInspectionPolicyOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *TlsInspectionPolicy) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o AuthorizationRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AuthorizationRule) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func Description(date string) string {\n\tlayout := \"Monday, January 2, 2006, at 15:04\"\n\treturn fmt.Sprintf(\"You have an appointment on %s.\",\n\t\tSchedule(date).Format(layout))\n}", "func (*RunnablePrincipalPolicySet_Policy) Descriptor() ([]byte, []int) {\n\treturn file_cerbos_runtime_v1_runtime_proto_rawDescGZIP(), []int{4, 1}\n}", "func (o *SSHAuthorizationPolicy) Doc() string {\n\n\treturn `An SSH authorization allows you to define the permissions for the owner\nof a OpenSSH certificate issued by a Microsegmentation certificate authority.\nYou can\ndefine if a user with some claims can connect to an ` + \"`\" + `sshd` + \"`\" + ` server managed by\nan instance of ` + \"`\" + `enforcerd` + \"`\" + ` according to its tags, what permissions he has and\nfor how long delivered certificates are valid.`\n}", "func (*Schedules) Descriptor() ([]byte, []int) {\n\treturn file_src_nap_nap_proto_rawDescGZIP(), []int{10}\n}", "func (o LookupPolicyResultOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o LookupClientTlsPolicyResultOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupClientTlsPolicyResult) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o WorkloadStatusConfigStaticPtrOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *WorkloadStatusConfigStatic) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Description\n\t}).(pulumi.StringPtrOutput)\n}", "func (r WebRestrictions) TimeDescription() string {\n\tintClass := r.getTimeClass()\n\tswitch intClass {\n\tcase 0:\n\t\treturn \"This token has an infinite lifetime!\"\n\tcase 1:\n\t\treturn \"This token is long-lived.\"\n\tcase 2:\n\t\treturn \"This token will expire within 7days.\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func (r *TopicRule) Description() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"description\"])\n}", "func (l *ActivityDumpRuntimeSetting) Description() string {\n\treturn \"Set/get the corresponding field.\"\n}", "func (*Policy) Descriptor() ([]byte, []int) {\n\treturn file_interservice_license_control_license_control_proto_rawDescGZIP(), []int{4}\n}", "func (o RouterNatRuleResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterNatRuleResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o InstanceMaintenancePolicyPtrOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenancePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Description\n\t}).(pulumi.StringPtrOutput)\n}", "func (o InstanceMaintenancePolicyPtrOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceMaintenancePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Description\n\t}).(pulumi.StringPtrOutput)\n}", "func (o TrustConfigOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TrustConfig) pulumi.StringOutput { return v.Description }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicySchedulePtrOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicySchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Schedule\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleResponsePtrOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicyScheduleResponse) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Schedule\n\t}).(pulumi.StringPtrOutput)\n}", "func (o HttpRouteRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HttpRouteRule) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o LookupResponsePolicyResultOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupResponsePolicyResult) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o SecurityGroupRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SecurityGroupRule) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (n *Vspheretpgy) Description() string {\n\treturn \"Read vCenter status information\"\n}", "func (j *ScheduledJob) ScheduleDetails() *jobspb.ScheduleDetails {\n\treturn &j.rec.ScheduleDetails\n}", "func (o UsagePlanOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *UsagePlan) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (p scheduleOnHost) name() policyName {\n\treturn scheduleOnHostAnnotationPolicy\n}", "func (o QuotaLimitOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v QuotaLimit) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (p *policy) String() string {\n\treturn fmt.Sprintf(policyDocument,\n\t\tp.Expiration,\n\t\tp.Bucket,\n\t\tp.Key,\n\t\tp.O.MaxFileSize,\n\t\tp.Credential,\n\t\tp.Date,\n\t)\n}", "func (o ReservationResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ReservationResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o QuotaLimitResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v QuotaLimitResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (s policyRules) String() string {\n\treturn console.Colorize(\"Policy\", s.Resource+\" => \"+s.Allow+\"\")\n}", "func (*PolicyRule) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_skv2_api_multicluster_v1alpha1_cluster_proto_rawDescGZIP(), []int{2}\n}", "func (s *Scope) Description() string {\n\treturn s.description\n}", "func (m *Resource) Description() string {\n\treturn m.description\n}", "func (o TimelineOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Timeline) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (*RunnablePrincipalPolicySet_Policy_ActionRule) Descriptor() ([]byte, []int) {\n\treturn file_cerbos_runtime_v1_runtime_proto_rawDescGZIP(), []int{4, 1, 0}\n}", "func Description(date string) string {\n\tvar t time.Time = Schedule(date)\n\n\treturn fmt.Sprintf(\"You have an appointment on %s, at %2d:%2d.\", t.Format(forms[4]), t.Hour(), t.Minute())\n}", "func (t *Topology) Description() description.Topology {\n\tt.dmtx.Lock()\n\tdefer t.dmtx.Unlock()\n\treturn t.desc\n}", "func (s *SystemdTimings) Description() string {\n\treturn \"Gather systemd boot and unit timing data\"\n}", "func (o RouterAdvertisedIpRangeResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v RouterAdvertisedIpRangeResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (p *Plan) Describe() string {\n\tactions := map[Action]string{\n\t\tActionDelete: color.New(color.BgRed, color.FgBlack).SprintFunc()(\"DELETE\"),\n\t\tActionUpdate: color.New(color.BgCyan, color.FgBlack).SprintFunc()(\"UPDATE\"),\n\t\tActionCreate: color.New(color.BgGreen, color.FgBlack).SprintFunc()(\"CREATE\"),\n\t}\n\n\tbuf := new(bytes.Buffer)\n\ttable := tablewriter.NewWriter(buf)\n\ttable.SetHeader([]string{\"ACTION\", \"OBJECT\", \"REASON\"})\n\n\tfor _, step := range p.Steps {\n\t\ttable.Append([]string{actions[step.Action], step.Object.ToString(), step.Reason})\n\t}\n\n\ttable.Render()\n\n\treturn buf.String()\n}", "func (m *ConditionalAccessPolicy) GetDescription()(*string) {\n val, err := m.GetBackingStore().Get(\"description\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (md *pcpMetricDesc) Description() string {\n\treturn md.shortDescription + \"\\n\" + md.longDescription\n}", "func (o GetPolicyDocumentRuleOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetPolicyDocumentRule) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o StaticRouteOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StaticRoute) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func cmdListPolicySchedules(ccmd *cobra.Command, args []string) {\n\taplSvc := apl.NewClient()\n\n\toutput := runListCommand(&policyScheduleParams, aplSvc.PolicySchedules.List)\n\n\tif output != nil {\n\t\tfields := []string{\"ID\", \"Name\", \"ResourceType\", \"Status\", \"CreatedTime\"}\n\t\tprintTableResultsCustom(output.([]apl.PolicySchedule), fields)\n\t}\n}", "func (o TimeWindowCustomAlertRuleResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TimeWindowCustomAlertRuleResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o PriorityClassOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PriorityClass) pulumi.StringOutput { return v.Description }).(pulumi.StringOutput)\n}", "func (o EciScalingConfigurationOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EciScalingConfiguration) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (*Schedule) Descriptor() ([]byte, []int) {\n\treturn file_proto_common_proto_rawDescGZIP(), []int{3}\n}", "func (o *SSHAuthorizationPolicy) GetDescription() string {\n\n\treturn o.Description\n}", "func (*RunnablePrincipalPolicySet_Policy_ResourceRules) Descriptor() ([]byte, []int) {\n\treturn file_cerbos_runtime_v1_runtime_proto_rawDescGZIP(), []int{4, 1, 1}\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetDescription() string {\n\tif o == nil || o.Description == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Description\n}", "func (t *Treat) Description() {\n\tfmt.Printf(\"Hi, i'm a size %d Pork Treat\\n\", t.size)\n}", "func (o HttpRouteRuleResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HttpRouteRuleResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) GetScheduleInfo()(RequestScheduleable) {\n return m.scheduleInfo\n}", "func (o EcsLaunchTemplateOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EcsLaunchTemplate) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (*Resource) Descriptor() ([]byte, []int) {\n\treturn file_ocis_messages_policies_v0_policies_proto_rawDescGZIP(), []int{1}\n}", "func (mlw Wrapper) Description() string {\n\tvar count int\n\tfor row := range mlw.ml.Results {\n\t\tif mlw.ml.Results[row].SumTimerWait > 0 {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"Mutex Latency (events_waits_summary_global_by_event_name) %d rows\", count)\n}", "func (*Schedule) Descriptor() ([]byte, []int) {\n\treturn file_src_grpc_pipeline_proto_rawDescGZIP(), []int{2}\n}", "func (*CronSchedule) Descriptor() ([]byte, []int) {\n\treturn file_toit_model_job_proto_rawDescGZIP(), []int{19}\n}", "func (o RouterAdvertisedIpRangeOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RouterAdvertisedIpRange) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (*Policy) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_binaryauthorization_v1_resources_proto_rawDescGZIP(), []int{0}\n}", "func (o ScheduledQueryRulesAlertV2Output) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ScheduledQueryRulesAlertV2) pulumi.StringPtrOutput { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (o ReservationTypeOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ReservationType) *string { return v.Description }).(pulumi.StringPtrOutput)\n}", "func (cfg Config) Description() string {\n\treturn cfg.description\n}", "func (o *SparseSSHAuthorizationPolicy) GetDescription() (out string) {\n\n\tif o.Description == nil {\n\t\treturn\n\t}\n\n\treturn *o.Description\n}", "func (o GetRulesRuleOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRule) string { return v.Description }).(pulumi.StringOutput)\n}", "func (o GetRulesRuleOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRule) string { return v.Description }).(pulumi.StringOutput)\n}", "func (*Policies) Descriptor() ([]byte, []int) {\n\treturn file_src_nap_nap_proto_rawDescGZIP(), []int{13}\n}", "func (e E_OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Config_Priority) String() string {\n\treturn ygot.EnumLogString(e, int64(e), \"E_OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Config_Priority\")\n}", "func (*BatchGetEffectiveIamPoliciesResponse_EffectiveIamPolicy_PolicyInfo) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_asset_v1_asset_service_proto_rawDescGZIP(), []int{51, 0, 0}\n}", "func (o SourceInstancePropertiesResponseOutput) Description() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SourceInstancePropertiesResponse) string { return v.Description }).(pulumi.StringOutput)\n}", "func (*AccessPolicySpec) Descriptor() ([]byte, []int) {\n\treturn file_github_com_solo_io_gloo_mesh_api_networking_v1alpha2_access_policy_proto_rawDescGZIP(), []int{0}\n}", "func (o ThingTypePropertiesOutput) Description() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ThingTypeProperties) *string { return v.Description }).(pulumi.StringPtrOutput)\n}" ]
[ "0.6332255", "0.62671643", "0.62489957", "0.62482285", "0.62482285", "0.62149894", "0.6198616", "0.61557883", "0.60916317", "0.60522413", "0.6021759", "0.60082877", "0.5975633", "0.59616953", "0.59614545", "0.59455854", "0.5939765", "0.58849066", "0.58648825", "0.58433276", "0.58350956", "0.58326936", "0.579985", "0.57880795", "0.57819784", "0.5781425", "0.5752712", "0.57180786", "0.5671941", "0.5660891", "0.56425935", "0.56394327", "0.56372416", "0.5630273", "0.5618926", "0.56178993", "0.5617747", "0.5612559", "0.5611213", "0.5609804", "0.5603612", "0.5603612", "0.56035197", "0.55883175", "0.55844903", "0.5582098", "0.5567678", "0.5559577", "0.5550608", "0.55403674", "0.5535016", "0.5530042", "0.55291104", "0.5523232", "0.55142325", "0.5511532", "0.5510261", "0.550578", "0.5502256", "0.55020773", "0.54990554", "0.54975086", "0.5488599", "0.5486586", "0.54819703", "0.54784364", "0.5443325", "0.54406047", "0.5433953", "0.5426923", "0.54247457", "0.5420198", "0.5418648", "0.5407091", "0.5404824", "0.539091", "0.53906417", "0.5390131", "0.53888863", "0.5380101", "0.5376778", "0.5375537", "0.53720516", "0.53667134", "0.5362079", "0.5359695", "0.5351974", "0.5349533", "0.5345853", "0.5344312", "0.5342611", "0.5328217", "0.53212893", "0.53211075", "0.53211075", "0.53199685", "0.5317307", "0.5311947", "0.5305705", "0.5304933", "0.530455" ]
0.0
-1
The name of the traffic scheduling policy.
func (o InterRegionTrafficQosQueueOutput) InterRegionTrafficQosQueueName() pulumi.StringPtrOutput { return o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringPtrOutput { return v.InterRegionTrafficQosQueueName }).(pulumi.StringPtrOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p scheduleOnHost) name() policyName {\n\treturn scheduleOnHostAnnotationPolicy\n}", "func (p scheduleWithOverProvisioningAwareness) name() policyName {\n\treturn overProvisioningPolicy\n}", "func (p preferScheduleOnHost) name() policyName {\n\treturn preferScheduleOnHostAnnotationPolicy\n}", "func (o ResiliencyPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResiliencyPolicy) pulumi.StringOutput { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (o ConfigurationBackupOutput) PolicyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConfigurationBackup) *string { return v.PolicyName }).(pulumi.StringPtrOutput)\n}", "func (p antiAffinityLabel) name() policyName {\n\treturn antiAffinityLabelPolicy\n}", "func (o MrScalarTaskScalingUpPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingUpPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (p *Policy) Name() string {\n\treturn p.InternalName\n}", "func (o MrScalarTaskScalingDownPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarTaskScalingDownPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (o ElastigroupScalingTargetPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingTargetPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (o GroupPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *GroupPolicy) pulumi.StringOutput { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (policy *PolicySvc) Name() string {\n\treturn \"policy\"\n}", "func getPolicyName(downstream, upstream service.K8sServiceAccount) string {\n\treturn fmt.Sprintf(\"%s to %s\", downstream, upstream)\n}", "func (o *ExportPolicyCreateRequest) PolicyName() ExportPolicyNameType {\n\tvar r ExportPolicyNameType\n\tif o.PolicyNamePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyNamePtr\n\treturn r\n}", "func (o ElastigroupScalingDownPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingDownPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (o *ExportPolicyCreateRequest) PolicyName() ExportPolicyNameType {\n\tr := *o.PolicyNamePtr\n\treturn r\n}", "func (o MrScalarCoreScalingDownPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingDownPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (p preferAntiAffinityLabel) name() policyName {\n\treturn preferAntiAffinityLabelPolicy\n}", "func (o MrScalarCoreScalingUpPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MrScalarCoreScalingUpPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (o ValidatingAdmissionPolicyBindingSpecOutput) PolicyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyBindingSpec) *string { return v.PolicyName }).(pulumi.StringPtrOutput)\n}", "func (o ElastigroupScalingUpPolicyOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupScalingUpPolicy) string { return v.PolicyName }).(pulumi.StringOutput)\n}", "func (o ValidatingAdmissionPolicyBindingSpecPatchOutput) PolicyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyBindingSpecPatch) *string { return v.PolicyName }).(pulumi.StringPtrOutput)\n}", "func (o ConfigurationBackupPtrOutput) PolicyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationBackup) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PolicyName\n\t}).(pulumi.StringPtrOutput)\n}", "func (r *AwsAPIGatewayMethodSettingsThrottlingRule) Name() string {\n\treturn \"aws_apigateway_stage_throttling_rule\"\n}", "func (o AuthorizationPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AuthorizationPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o *ExportPolicyDestroyRequest) PolicyName() ExportPolicyNameType {\n\tvar r ExportPolicyNameType\n\tif o.PolicyNamePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyNamePtr\n\treturn r\n}", "func (r *Policy) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (o NetworkSimPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkSimPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o ServerPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServerPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o RolePolicyAttachmentOutput) PolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RolePolicyAttachment) pulumi.StringOutput { return v.PolicyName }).(pulumi.StringOutput)\n}", "func GeneratePolicyName(namespace, name, gvk string) string {\n\thash := fnv.New32a()\n\thashutil.DeepHashObject(hash, namespace+gvk)\n\n\t// The name of resources, like 'Role'/'ClusterRole'/'RoleBinding'/'ClusterRoleBinding',\n\t// may contain symbols(like ':') that are not allowed by CRD resources which require the\n\t// name can be used as a DNS subdomain name. So, we need to replace it.\n\t// These resources may also allow for other characters(like '&','$') that are not allowed\n\t// by CRD resources, we only handle the most common ones now for performance concerns.\n\t// For more information about the DNS subdomain name, please refer to\n\t// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names.\n\tif strings.Contains(name, \":\") {\n\t\tname = strings.ReplaceAll(name, \":\", \".\")\n\t}\n\treturn strings.ToLower(fmt.Sprintf(\"%s-%s\", name, rand.SafeEncodeString(fmt.Sprint(hash.Sum32()))))\n}", "func (r *AwsCloudwatchLogGroupLambdaRetentionRule) Name() string {\n\treturn \"aws_cloudwatch_log_group_lambda_retention\"\n}", "func (o SharedAccessPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SharedAccessPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o AlertPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AlertPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o AutoSnapshotPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AutoSnapshotPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (c *IAM) getPolicyName() (string, error) {\n\tclusterName, err := c.cfg.AccessPoint.GetClusterName()\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\n\tprefix := clusterName.GetClusterName()\n\n\t// If the length of the policy name is over the limit, trim the cluster\n\t// name from right and keep the policyNameSuffix intact.\n\tmaxPrefixLength := maxPolicyNameLength - len(policyNameSuffix)\n\tif len(prefix) > maxPrefixLength {\n\t\tprefix = prefix[:maxPrefixLength]\n\t}\n\n\treturn prefix + policyNameSuffix, nil\n}", "func (o ValidatingAdmissionPolicyBindingSpecPtrOutput) PolicyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ValidatingAdmissionPolicyBindingSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PolicyName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ValidatingAdmissionPolicyBindingSpecPatchPtrOutput) PolicyName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ValidatingAdmissionPolicyBindingSpecPatch) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PolicyName\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *SSHAuthorizationPolicy) GetName() string {\n\n\treturn o.Name\n}", "func (o GetSecurityPoliciesPolicyOutput) SecurityPolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecurityPoliciesPolicy) string { return v.SecurityPolicyName }).(pulumi.StringOutput)\n}", "func (pl *RepeatPriority) Name() string {\n\treturn Name\n}", "func ModuleName(p *policyv1.Policy) string {\n\tswitch pt := p.PolicyType.(type) {\n\tcase *policyv1.Policy_ResourcePolicy:\n\t\treturn ResourcePolicyModuleName(pt.ResourcePolicy.Resource, pt.ResourcePolicy.Version)\n\tcase *policyv1.Policy_PrincipalPolicy:\n\t\treturn PrincipalPolicyModuleName(pt.PrincipalPolicy.Principal, pt.PrincipalPolicy.Version)\n\tcase *policyv1.Policy_DerivedRoles:\n\t\treturn DerivedRolesModuleName(pt.DerivedRoles.Name)\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown policy type %T\", pt))\n\t}\n}", "func (o JobIamPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *JobIamPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o UserPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *UserPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (t *TestSpec) NetworkPolicyName() string {\n\treturn fmt.Sprintf(\"%s_policy.json\", t.Prefix)\n}", "func (o ConfigurationBackupSchedulePolicyOutput) SchedulePolicyType() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConfigurationBackupSchedulePolicy) *string { return v.SchedulePolicyType }).(pulumi.StringPtrOutput)\n}", "func (km KeyValueMap) Policy() string {\n\treturn km[kmPolicy]\n}", "func ResourcePolicyModuleName(resource, version string) string {\n\treturn fmt.Sprintf(\"%s.%s.v%s\", ResourcePoliciesPrefix, Sanitize(resource), Sanitize(version))\n}", "func (o *StorageNetAppSnapshotPolicySchedule) GetScheduleName() string {\n\tif o == nil || o.ScheduleName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ScheduleName\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicySchedule) *string { return v.Schedule }).(pulumi.StringPtrOutput)\n}", "func (o SecurityProfileBehaviorOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SecurityProfileBehavior) string { return v.Name }).(pulumi.StringOutput)\n}", "func (h *HPA) Name() string {\n\treturn \"horizontalpodautoscaler\"\n}", "func (o ResourcePolicyExemptionOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyExemption) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func ControllerName(kind string) string {\n\treturn \"claimscheduling/\" + strings.ToLower(kind)\n}", "func (o *SnapmirrorCreateRequest) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}", "func (mgr *LocalHashMapDBMgr) Policy() string {\n\treturn mgr.policy\n}", "func (pl *AvailabilityNodePriority) Name() string {\n\treturn Name\n}", "func (r *ComputeFirewallRuleResource) Name() string {\n\treturn r.f.Name\n}", "func (l *ActivityDumpRuntimeSetting) Name() string {\n\treturn l.ConfigKey\n}", "func (pl *NoMaxResourceCount) Name() string {\n\treturn Name\n}", "func (h *RateLimit) GetName() string {\n\treturn \"rate_limit\"\n}", "func (o FirewallPolicyAssociationOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FirewallPolicyAssociation) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (ScrapeHostResourceUtilization) Name() string {\n\treturn hostResourceUtilization\n}", "func getStrategyPolicy(policy ParentAbstractionServiceRetryPolicy) string {\n\tswitch policy {\n\tcase ParentAbstractionServiceRetryPolicyConsistentHash:\n\t\treturn `consistent_hash`\n\tcase ParentAbstractionServiceRetryPolicyRoundRobinIP:\n\t\treturn `rr_ip`\n\tcase ParentAbstractionServiceRetryPolicyRoundRobinStrict:\n\t\treturn `rr_strict`\n\tcase ParentAbstractionServiceRetryPolicyFirst:\n\t\treturn `first_live`\n\tcase ParentAbstractionServiceRetryPolicyLatched:\n\t\treturn `latched`\n\tdefault:\n\t\treturn getStrategyPolicy(DefaultParentAbstractionServiceRetryPolicy)\n\t}\n}", "func (o *SparseSSHAuthorizationPolicy) GetName() (out string) {\n\n\tif o.Name == nil {\n\t\treturn\n\t}\n\n\treturn *o.Name\n}", "func (o ConfigurationBackupOutput) SchedulePolicy() ConfigurationBackupSchedulePolicyPtrOutput {\n\treturn o.ApplyT(func(v ConfigurationBackup) *ConfigurationBackupSchedulePolicy { return v.SchedulePolicy }).(ConfigurationBackupSchedulePolicyPtrOutput)\n}", "func (r *LoadBalancerCookieStickinessPolicy) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (w *NotificationPolicy) TableName() string {\n\treturn NotificationPolicyTable\n}", "func (o CloudConfigurationRuleOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CloudConfigurationRule) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (o *GuardianPolicyDataData) GetPolicyName() string {\n\tif o == nil || o.PolicyName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PolicyName\n}", "func (o ConfigurationBackupSchedulePolicyPtrOutput) SchedulePolicyType() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationBackupSchedulePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SchedulePolicyType\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *PolicyRule) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o TlsCipherPolicyOutput) TlsCipherPolicyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TlsCipherPolicy) pulumi.StringOutput { return v.TlsCipherPolicyName }).(pulumi.StringOutput)\n}", "func (o SecurityPolicyAssociationOutput) Name() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v SecurityPolicyAssociation) *string { return v.Name }).(pulumi.StringPtrOutput)\n}", "func (action *scheduleRoutineAction) Name() string {\n\treturn \"schedule-routine\"\n}", "func (action *scheduleRoutineAction) Name() string {\n\treturn \"schedule-routine\"\n}", "func (s *Schema) TableName() string {\n\treturn \"p2p_preheat_policy\"\n}", "func (o SharedAccessPolicyOutput) ResourceGroupName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SharedAccessPolicy) pulumi.StringOutput { return v.ResourceGroupName }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleResponseOutput) Schedule() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyScheduleResponse) string { return v.Schedule }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyInstanceSchedulePolicySchedulePtrOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicySchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Schedule\n\t}).(pulumi.StringPtrOutput)\n}", "func (o PriorityClassOutput) PreemptionPolicy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *PriorityClass) pulumi.StringOutput { return v.PreemptionPolicy }).(pulumi.StringOutput)\n}", "func (a *ALBIngress) Name() string {\n\treturn fmt.Sprintf(\"%s-%s\", a.namespace, a.ingressName)\n}", "func (o QuotaRateLimitOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *QuotaRateLimit) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (r *Bucket) Policy() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"policy\"])\n}", "func (rl *RateLimit) Name() string {\n\treturn \"ratelimit\"\n}", "func (o TlsInspectionPolicyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TlsInspectionPolicy) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (*bgpCollector) Name() string {\n\treturn \"BGP\"\n}", "func (a *Approval) Name() string {\n\treturn a.name\n}", "func (r DeliveryResource) Name() string {\n\treturn r.Spec.Moniker.String()\n}", "func (p *policy) String() string {\n\treturn fmt.Sprintf(policyDocument,\n\t\tp.Expiration,\n\t\tp.Bucket,\n\t\tp.Key,\n\t\tp.O.MaxFileSize,\n\t\tp.Credential,\n\t\tp.Date,\n\t)\n}", "func (r *Policy) PolicyType() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"policyType\"])\n}", "func (o EndpointAclPolicyOutput) ModuleName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *EndpointAclPolicy) pulumi.StringPtrOutput { return v.ModuleName }).(pulumi.StringPtrOutput)\n}", "func (o *VolumeExportAttributesType) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}", "func (o ApplicationSpecRolloutplanCanarymetricOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationSpecRolloutplanCanarymetric) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o OrganizationSecurityPolicyOutput) PolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OrganizationSecurityPolicy) pulumi.StringOutput { return v.PolicyId }).(pulumi.StringOutput)\n}", "func (e E_OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Config_Priority) String() string {\n\treturn ygot.EnumLogString(e, int64(e), \"E_OpenconfigQos_Qos_SchedulerPolicies_SchedulerPolicy_Schedulers_Scheduler_Config_Priority\")\n}", "func (t *Task) Name() string { t.mutex.RLock(); defer t.mutex.RUnlock(); return t.name }", "func (o *WafPolicyGroup) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (o ReplicaExternalKeyOutput) Policy() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReplicaExternalKey) pulumi.StringOutput { return v.Policy }).(pulumi.StringOutput)\n}", "func (o LookupPolicyResultOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o ClientTlsPolicyIamBindingOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClientTlsPolicyIamBinding) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}" ]
[ "0.74736947", "0.72675604", "0.7266452", "0.67986524", "0.6659939", "0.6645844", "0.66170263", "0.661601", "0.6613454", "0.65992755", "0.65884906", "0.65819204", "0.65560925", "0.6417246", "0.6395096", "0.638605", "0.6384816", "0.638258", "0.6348977", "0.63074774", "0.6294279", "0.627122", "0.6268355", "0.62654656", "0.6197496", "0.6149078", "0.6089095", "0.6063415", "0.60451865", "0.6022557", "0.6004818", "0.5912896", "0.58913004", "0.58911294", "0.5884592", "0.5880826", "0.5868977", "0.58623326", "0.5844748", "0.57944", "0.5707748", "0.569402", "0.56853753", "0.56478167", "0.5642347", "0.56244624", "0.5620505", "0.56152886", "0.5592608", "0.5579429", "0.5561152", "0.55424094", "0.55316365", "0.5524647", "0.5523312", "0.5495756", "0.54749066", "0.5460355", "0.54390544", "0.54187566", "0.5382141", "0.53771675", "0.5370972", "0.53588265", "0.53513265", "0.53497005", "0.53409415", "0.5337465", "0.5334052", "0.5325651", "0.5313234", "0.5297507", "0.52875304", "0.52858853", "0.5276462", "0.5276462", "0.5274577", "0.5270607", "0.5269301", "0.52611893", "0.525569", "0.5250709", "0.5247766", "0.5246536", "0.52424794", "0.5230492", "0.5227394", "0.52236164", "0.5220501", "0.5212747", "0.52110845", "0.5210339", "0.51922613", "0.51815444", "0.5177802", "0.517079", "0.5167861", "0.5159758", "0.5151221", "0.5149168", "0.51463944" ]
0.0
-1
The percentage of crossregion bandwidth that the current queue can use.
func (o InterRegionTrafficQosQueueOutput) RemainBandwidthPercent() pulumi.IntOutput { return o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.IntOutput { return v.RemainBandwidthPercent }).(pulumi.IntOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (br *BandwidthMeter) Bandwidth() (bytesPerSec float64) {\n deltaSecs := br.lastRead.Sub(br.start).Seconds()\n bytesPerSec = float64(br.bytesRead) / deltaSecs\n return\n}", "func percentAvailable(statfs *syscall.Statfs_t) uint8 {\n\tif statfs.Blocks == 0 {\n\t\treturn uint8(0)\n\t}\n\treturn uint8(float32(statfs.Bavail) / float32(statfs.Blocks) * 100.0)\n}", "func (d *Download) Percent() float32 {\r\n\treturn float32(d.current) / float32(d.max)\r\n}", "func (t *Track) Bandwidth() int {\n\treturn t.bandwidth\n}", "func forceUperBandwidth(bw int64) int64 {\n\n\tif bw > maxBwPerBroker {\n\t\treturn maxBwPerBroker\n\t}\n\treturn bw\n}", "func (t *Track) computeBandwidth() {\n\tif t.bandwidth > 0 {\n\t\treturn\n\t}\n\ttotalDuration := int64(0)\n\ttotalSize := int64(0)\n\t/* Accumulate duration and size for all chunks */\n\tfor _, duration := range t.chunksDuration {\n\t\ttotalDuration += duration\n\t}\n\tfor _, size := range t.chunksSize {\n\t\ttotalSize += int64(size)\n\t}\n\t/* Rescale duration to seconds */\n\ttotalDuration /= int64(t.globalTimescale)\n\tif totalDuration > 0 {\n\t\t/* Return bandwidth */\n\t\tt.bandwidth = int(totalSize / totalDuration)\n\t} else {\n\t\tt.bandwidth = 0\n\t}\n}", "func MBUsed() float64 {\n var m runtime.MemStats\n runtime.ReadMemStats(&m)\n return float64(m.TotalAlloc) / BytesPerMBF \n}", "func calculateCPUPercent(currentCPU, previousCPU, now, previousSystem uint64) float64 {\n\tvar (\n\t\tcpuPercent = 0.0\n\t\tcpuDelta = float64(currentCPU - previousCPU)\n\t\tsystemDelta = float64(now - previousSystem)\n\t)\n\tif systemDelta > 0.0 && cpuDelta > 0.0 {\n\t\t// gets a ratio of container cpu usage total, and multiplies that by 100 to get a percentage\n\t\tcpuPercent = (cpuDelta / systemDelta) * 100\n\t}\n\treturn cpuPercent\n}", "func rate(read int64, t time.Duration) float64 {\n\treturn float64(read) / (1024 * 1024) / t.Seconds()\n}", "func (ms mainnetSchedule) ConsensusRatio() float64 {\n\treturn mainnetConsensusRatio\n}", "func (l *channelLink) getBandwidth() lnwire.MilliSatoshi {\n\treturn l.channel.LocalAvailableBalance() - l.overflowQueue.pendingAmount()\n}", "func (bucket *Bucket) Rate() float64 {\n\treturn 1e9 / float64(bucket.fillInterval)\n}", "func (cp *ConstantPacer) Rate(elapsed time.Duration) float64 {\n\treturn cp.hitsPerNs() * 1e9\n}", "func (t *transfer) Percentage() int {\n\t// catch zero values\n\tif t.progress == 0 || t.size == 0 {\n\t\treturn 0\n\t}\n\t// calculate\n\treturn int(100.0 * (float32(t.progress) / float32(t.size)))\n}", "func getMemPercent(usage uint64, memLimit uint64) float64 {\n\tif memLimit == 0 {\n\t\treturn 0\n\t}\n\n\treturn float64(usage) / float64(memLimit) * 100\n}", "func (o DiskReplicaPairOutput) Bandwidth() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DiskReplicaPair) pulumi.StringOutput { return v.Bandwidth }).(pulumi.StringOutput)\n}", "func (s *syncRatio) getRatio() *float32 {\n\t// Prevent number of syncs from growing indefinitely.\n\tif s.syncEvents > s.syncsBeforeTruncate {\n\t\ts.truncateSyncs()\n\t}\n\tif s.syncEvents <= 0 {\n\t\treturn nil\n\t}\n\tratio := float32(s.syncEvents-s.failedSyncs) / float32(s.syncEvents)\n\tlog.Debugf(\"[status] Successful syncs to total syncs ratio: %v\", ratio)\n\treturn &ratio\n}", "func (l *channelLink) Bandwidth() lnwire.MilliSatoshi {\n\tcommand := &getBandwidthCmd{\n\t\tresp: make(chan lnwire.MilliSatoshi, 1),\n\t}\n\n\tselect {\n\tcase l.linkControl <- command:\n\t\treturn <-command.resp\n\tcase <-l.quit:\n\t\treturn 0\n\t}\n}", "func CPUPercent() ([]float64, error) {\n\tused, err := cpu.Percent(0, true)\n\treturn used, err\n}", "func (scheduler *SchedulerFair) UpdateQuota() {\r\n\tscheduler.queuesMu.Lock()\r\n\tdefer scheduler.queuesMu.Unlock()\r\n\tscheduler.queuesQuotaMu.Lock()\r\n\tdefer scheduler.queuesQuotaMu.Unlock()\r\n\t//log.Info(\"Updating queues quota~\")\r\n\r\n\t/* phase 1: DRF */\r\n\tusingGPU := 0\r\n\tusingCPU := 0\r\n\tusingMemory := 0\r\n\tallocatedGPU := 0\r\n\tallocatedCPU := 0\r\n\tallocatedMemory := 0\r\n\tscheduler.resourceAllocationsMu.Lock()\r\n\tfor _, quota := range scheduler.resourceAllocations {\r\n\t\tusingGPU += quota.NumberGPU\r\n\t\tusingCPU += quota.CPU\r\n\t\tusingMemory += quota.Memory\r\n\t}\r\n\tscheduler.resourceAllocationsMu.Unlock()\r\n\r\n\tfor _, quota := range scheduler.queuesQuota {\r\n\t\tallocatedGPU += quota.NumberGPU\r\n\t\tallocatedCPU += quota.CPU\r\n\t\tallocatedMemory += quota.Memory\r\n\t}\r\n\r\n\tpool := InstanceOfResourcePool()\r\n\r\n\tavailableGPU := pool.TotalGPU*1000 - usingGPU*1000 - allocatedGPU\r\n\tavailableCPU := pool.TotalCPU*1000 - usingCPU*1000 - allocatedCPU\r\n\t//availableMemory := pool.TotalMemory - usingMemory - allocatedMemory\r\n\t/* <0 means some nodes exited */\r\n\t//log.Info(availableGPU)\r\n\tif availableGPU <= 0 {\r\n\t\treturn\r\n\t}\r\n\r\n\tvar candidates []string\r\n\trequests := map[string]ResourceCount{}\r\n\tweights := 0\r\n\r\n\tfor queue, jobs := range scheduler.queues {\r\n\t\tif len(jobs) == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tweights += InstanceOfGroupManager().groups[queue].Weight\r\n\t\trequest := ResourceCount{}\r\n\t\tfor i, job := range jobs {\r\n\t\t\tGPU := 0\r\n\t\t\tCPU := 0\r\n\t\t\tMemory := 0\r\n\t\t\tfor _, task := range job.Tasks {\r\n\t\t\t\tGPU += task.NumberGPU\r\n\t\t\t\tCPU += task.NumberCPU\r\n\t\t\t\tMemory += task.Memory\r\n\t\t\t}\r\n\t\t\trequest.NumberGPU += GPU\r\n\t\t\trequest.CPU += CPU\r\n\t\t\trequest.Memory += Memory\r\n\t\t\t/* increase priority at most 10 jobs, to avoid small jobs always goes first in a batch */\r\n\t\t\tif job.Priority == jobs[0].Priority && i < 10 {\r\n\t\t\t\tscheduler.queues[queue][i].BasePriority += 1.0\r\n\t\t\t}\r\n\t\t}\r\n\t\tsort.Sort(sort.Reverse(scheduler.queues[queue]))\r\n\r\n\t\t/* minimum is 1, to avoid divide by zero error following */\r\n\t\tif request.NumberGPU == 0 {\r\n\t\t\trequest.NumberGPU = 1\r\n\t\t}\r\n\t\tif quota, ok := scheduler.queuesQuota[queue]; ok && quota.NumberGPU >= request.NumberGPU*1000 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\trequests[queue] = request\r\n\t\tcandidates = append(candidates, queue)\r\n\t}\r\n\r\n\tif len(candidates) == 0 {\r\n\t\treturn\r\n\t}\r\n\tlog.Debug(\"Can allocate \", availableGPU)\r\n\tlog.Debug(\"Before \")\r\n\tfor queue, quota := range scheduler.queuesQuota {\r\n\t\tlog.Debug(\"Queue<->\", queue)\r\n\t\tlog.Debug(\"GPU:\", quota.NumberGPU)\r\n\t\tlog.Debug(\"CPU:\", quota.CPU)\r\n\t\tlog.Debug(\"Memory:\", quota.Memory)\r\n\t}\r\n\r\n\tper := availableGPU / weights\r\n\tfor _, queue := range candidates {\r\n\t\tif _, ok := scheduler.queuesQuota[queue]; !ok {\r\n\t\t\tscheduler.queuesQuota[queue] = &ResourceCount{}\r\n\t\t}\r\n\t\tweight := InstanceOfGroupManager().groups[queue].Weight\r\n\t\tquota := scheduler.queuesQuota[queue]\r\n\r\n\t\t/* if allocate is more than request, reduce weight */\r\n\t\tlog.Info(quota.NumberGPU, per, weight, requests[queue].NumberGPU)\r\n\t\tbase := per * weight\r\n\t\tif quota.NumberGPU+base > requests[queue].NumberGPU*1000 {\r\n\t\t\tbase = requests[queue].NumberGPU*1000 - quota.NumberGPU\r\n\t\t}\r\n\r\n\t\tquota.NumberGPU += base\r\n\t\tavailableGPU -= base\r\n\r\n\t\tquota.CPU += (requests[queue].CPU * base) / requests[queue].NumberGPU\r\n\t\tavailableCPU -= (requests[queue].CPU * base) / requests[queue].NumberGPU\r\n\t\tquota.Memory += ((requests[queue].Memory * base) / requests[queue].NumberGPU) / 1000\r\n\t}\r\n\t/* avoid resource leak, and reserve full */\r\n\tavailableGPU = availableGPU % 1000\r\n\tif availableGPU > 0 {\r\n\t\tfor _, queue := range candidates {\r\n\t\t\tquota := scheduler.queuesQuota[queue]\r\n\t\t\tquota.NumberGPU += availableGPU\r\n\t\t\tquota.CPU += (requests[queue].CPU * availableGPU) / requests[queue].NumberGPU\r\n\t\t\tquota.Memory += ((requests[queue].Memory * availableGPU) / requests[queue].NumberGPU) / 1000\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tlog.Debug(\"After \")\r\n\tfor queue, quota := range scheduler.queuesQuota {\r\n\t\tlog.Debug(\"Queue<->\", queue)\r\n\t\tlog.Debug(\"GPU:\", quota.NumberGPU)\r\n\t\tlog.Debug(\"CPU:\", quota.CPU)\r\n\t\tlog.Debug(\"Memory:\", quota.Memory)\r\n\t}\r\n\r\n\t/* Phase 2: clear IOUs */\r\n\tfor queue, IOUs := range scheduler.IOUs {\r\n\t\t/* no IOU, skip */\r\n\t\tif t, ok := scheduler.IOUs[queue]; !ok || len(t) == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\t/* nothing to pay */\r\n\t\tif tmp, ok := scheduler.queuesQuota[queue]; !ok || tmp.NumberGPU == 0 {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tminIOU := 0\r\n\t\ttotalIOU := 0\r\n\t\tfor _, IOU := range IOUs {\r\n\t\t\tif IOU.NumberGPU > minIOU && IOU.NumberGPU != 0 {\r\n\t\t\t\tminIOU = IOU.NumberGPU\r\n\t\t\t\ttotalIOU += IOU.NumberGPU\r\n\t\t\t}\r\n\t\t}\r\n\t\tquota := scheduler.queuesQuota[queue]\r\n\t\tif quota.NumberGPU >= totalIOU {\r\n\t\t\t/* can clear all */\r\n\t\t\tminIOU = totalIOU\r\n\t\t}\r\n\t\tif quota.NumberGPU < minIOU*len(IOUs) {\r\n\t\t\tminIOU = quota.NumberGPU / len(IOUs)\r\n\t\t}\r\n\r\n\t\tfor q, IOU := range IOUs {\r\n\t\t\tif IOU.NumberGPU <= minIOU {\r\n\t\t\t\tquota.NumberGPU -= IOU.NumberGPU\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += IOU.NumberGPU\r\n\t\t\t\tIOU.NumberGPU = 0\r\n\t\t\t} else {\r\n\t\t\t\tquota.NumberGPU -= minIOU\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += minIOU\r\n\t\t\t\tIOU.NumberGPU -= minIOU\r\n\t\t\t}\r\n\t\t\tlog.Info(queue, \" pay IOU to \", q, \" now \", IOU.NumberGPU)\r\n\t\t\t/* clear */\r\n\t\t\tif IOU.NumberGPU == 0 {\r\n\t\t\t\tdelete(scheduler.IOUs[queue], q)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif minIOU == 0 {\r\n\t\t\tfor q, IOU := range IOUs {\r\n\t\t\t\tquota.NumberGPU -= 1\r\n\t\t\t\tscheduler.queuesQuota[q].NumberGPU += 1\r\n\t\t\t\tIOU.NumberGPU -= 1\r\n\t\t\t\tlog.Info(queue, \" pay IOU to \", q, \" now \", IOU.NumberGPU)\r\n\t\t\t\t/* clear */\r\n\t\t\t\tif IOU.NumberGPU == 0 {\r\n\t\t\t\t\tdelete(scheduler.IOUs[queue], q)\r\n\t\t\t\t}\r\n\t\t\t\tif quota.NumberGPU == 0 {\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "func blockSize(rate int) int {\n\tconst playbackBufferedTimeUs = 5000\n\treturn rate * playbackBufferedTimeUs / 1000000\n}", "func (t Tap) BandwidthStats() (float64, float64) {\n\tif len(t.stats) < 2 {\n\t\treturn 0, 0\n\t}\n\n\tvar rxRate, txRate float64\n\n\tfor i := range t.stats {\n\t\tif i+1 < len(t.stats) {\n\t\t\trx := float64(t.stats[i+1].RxBytes - t.stats[i].RxBytes)\n\t\t\ttx := float64(t.stats[i+1].TxBytes - t.stats[i].TxBytes)\n\t\t\td := float64(t.stats[i+1].t.Sub(t.stats[i].t).Seconds())\n\n\t\t\t// convert raw byte count to MB/s\n\t\t\trxRate += rx / float64(1<<20) / d\n\t\t\ttxRate += tx / float64(1<<20) / d\n\t\t}\n\t}\n\n\t// compute average\n\trxRate /= float64(len(t.stats) - 1)\n\ttxRate /= float64(len(t.stats) - 1)\n\n\treturn rxRate, txRate\n}", "func CalculatePqBatchCopyRate(timestamps []time.Time) float64 {\n\tvar total int64\n\n\tunixstamps := make([]int64, len(timestamps))\n\tfor i, ts := range timestamps {\n\t\tunixstamps[i] = ts.UnixNano()\n\t}\n\tsort.Sort(Int64Slice(unixstamps))\n\n\tt0 := unixstamps[0]\n\tfor _, t1 := range unixstamps[1:] {\n\t\ttotal += t0 - t1\n\t\tt0 = t1\n\t}\n\treturn (float64(len(timestamps)) / float64(total)) * math.Pow10(9) // ns -> s\n}", "func (ncs NvmeControllers) PercentUsage() string {\n\treturn common.PercentageString(ncs.Total()-ncs.Free(), ncs.Total())\n}", "func Percent(current uint64, all uint64) float64 {\n\tpercent := (float64(current) * float64(100)) / float64(all)\n\treturn percent\n}", "func (b Bridges) BandwidthStats() (float64, float64) {\n\tbridgeLock.Lock()\n\tdefer bridgeLock.Unlock()\n\n\tvar rxRate, txRate float64\n\n\tfor _, br := range b.bridges {\n\t\tfor _, tap := range br.taps {\n\t\t\tif !tap.Defunct {\n\t\t\t\trx, tx := tap.BandwidthStats()\n\n\t\t\t\trxRate += rx\n\t\t\t\ttxRate += tx\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rxRate, txRate\n}", "func GetBandWidth() float64 {\n\turl := \"http://169.231.235.221/sedgtomayhem.txt\"\n\tlines := \"10\"\n\t//fmt.Printf(\"Tailing http endpoint : %s\\n\", url)\n\n\tcmd := \"curl \" + url + \" | tail -\" + lines\n\tout, err := exec.Command(\"bash\", \"-c\", cmd).Output()\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\treturn 0\n\t}\n\t// Use reverse scanner to capture the last nonzero bandwidth\n\tscanner := reverse.NewScanner(strings.NewReader(string(out)))\n\tvar (\n\t\tlastLine string\n\t\tbandWidth float64\n\t)\n\tfor scanner.Scan() {\n\t\tlastLine = scanner.Text()\n\t\tfields := strings.Fields(lastLine)\n\t\tbandWidth, err = strconv.ParseFloat(fields[0], 64)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\tif bandWidth > 0.0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif bandWidth <= 0.0 {\n\t\tfmt.Println(\"The bandwidth zeroed out! Simulate on average 70.7916 !\")\n\t\tbandWidth = 70.7916\n\t}\n\treturn bandWidth\n}", "func (c *Connection) outstandingQueuedBytes() (n int) {\n\tfor _, s := range c.streams {\n\t\tn += s.outstandingQueuedBytes()\n\t}\n\n\treturn\n}", "func (manager *Manager) PercentageComplete() float32 {\n\tswitch manager.state {\n\tcase notRunningState:\n\tcase runningState:\n\t\treturn manager.percentageComplete\n\tdefault:\n\t}\n\n\treturn 1.0\n}", "func (c *gcControllerState) effectiveGrowthRatio() float64 {\n\tif !c.test {\n\t\tassertWorldStoppedOrLockHeld(&mheap_.lock)\n\t}\n\n\tegogc := float64(atomic.Load64(&c.heapGoal)-c.heapMarked) / float64(c.heapMarked)\n\tif egogc < 0 {\n\t\t// Shouldn't happen, but just in case.\n\t\tegogc = 0\n\t}\n\treturn egogc\n}", "func (this *Stats) SendBitRate() float32 { return float32(this.ptr.f_send_bitrate) }", "func (o AnycastEipAddressOutput) Bandwidth() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *AnycastEipAddress) pulumi.IntOutput { return v.Bandwidth }).(pulumi.IntOutput)\n}", "func (o *SpaceInformationType) ObjectStoreReferencedCapacityPercent() int {\n\tvar r int\n\tif o.ObjectStoreReferencedCapacityPercentPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.ObjectStoreReferencedCapacityPercentPtr\n\treturn r\n}", "func (rl *limiter) GetRate() int64 {\n\trl.lock.RLock()\n\tqps := rl.qps\n\trl.lock.RUnlock()\n\n\treturn qps\n}", "func (o HttpFaultAbortOutput) Percentage() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v HttpFaultAbort) *float64 { return v.Percentage }).(pulumi.Float64PtrOutput)\n}", "func (d *state) BlockSize() int { return d.rate }", "func GetCPUPercentage() float64 {\n\tvar ru syscall.Rusage\n\tsyscall.Getrusage(syscall.RUSAGE_SELF, &ru)\n\tusageTime := ru.Utime.Nano() + ru.Stime.Nano()\n\tnowTime := time.Now().UnixNano()\n\tperc := float64(usageTime-lastCPUUsageTime) / float64(nowTime-lastInspectUnixNano) * 100.0\n\tlastInspectUnixNano = nowTime\n\tlastCPUUsageTime = usageTime\n\treturn perc\n}", "func getPixelDiffPercent(numDiffPixels, totalPixels int) float32 {\n\treturn (float32(numDiffPixels) * 100) / float32(totalPixels)\n}", "func (p *pvc) Cost() float64 {\n\tif p == nil || p.Volume == nil {\n\t\treturn 0.0\n\t}\n\n\tgib := p.Bytes / 1024 / 1024 / 1024\n\thrs := p.minutes() / 60.0\n\n\treturn p.Volume.CostPerGiBHour * gib * hrs\n}", "func (this *CirCleQueue)Size() int{\n return (this.tail + this.maxSize- this.head) % this.maxSize\n}", "func (m *DeliveryOptimizationBandwidthBusinessHoursLimit) GetBandwidthPercentageDuringBusinessHours()(*int32) {\n val, err := m.GetBackingStore().Get(\"bandwidthPercentageDuringBusinessHours\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*int32)\n }\n return nil\n}", "func usePercent(total, free uint64) uint64 {\n\tused := (total - free)\n\n\tif total != 0 {\n\t\tu100 := used * 100\n\t\tpct := float64(u100) / float64(total)\n\n\t\treturn uint64(roundFloat(pct, 0))\n\t}\n\n\treturn 0\n}", "func (o AppIngressTrafficWeightOutput) Percentage() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AppIngressTrafficWeight) int { return v.Percentage }).(pulumi.IntOutput)\n}", "func computeCPUPercent(timeSpentA, timeSpentB time.Duration, sampleTimeA, sampleTimeB time.Time) float64 {\n\t// divide change in time spent in CPU over time between samples.\n\t// result is out of 100.\n\t//\n\t// don't worry about overflowing int64. it's like, 30 years.\n\treturn float64((timeSpentB-timeSpentA)*100) / float64(sampleTimeB.UnixNano()-sampleTimeA.UnixNano())\n}", "func (o GetAppIngressTrafficWeightOutput) Percentage() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetAppIngressTrafficWeight) int { return v.Percentage }).(pulumi.IntOutput)\n}", "func (p *Prometheus) CPUBusyPercentage() (float64, error) {\n\tq := fmt.Sprintf(QueryAllCPUBusyPercentage, \"2m\")\n\tval, warns, err := p.API.Query(context.Background(), q, time.Now())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tp.printWarns(warns)\n\tif !p.validateNotEmptyVec(q, val) {\n\t\treturn 0, nil\n\t}\n\tscalarVal := val.(model.Vector)[0].Value\n\treturn float64(scalarVal), nil\n}", "func (r Virtual_Guest) GetBandwidthAllocation() (resp datatypes.Float64, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getBandwidthAllocation\", nil, &r.Options, &resp)\n\treturn\n}", "func (o HttpFaultDelayOutput) Percentage() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v HttpFaultDelay) *float64 { return v.Percentage }).(pulumi.Float64PtrOutput)\n}", "func GetRWBytesPerSecond(partition string) (uint64, uint64) {\n // IOCountersStat\n first_ret, err := disk.IOCounters(partition)\n dealwithErr(err)\n\n var firstReadBytes, firstWriteBytes uint64\n for _, io := range first_ret {\n firstReadBytes = io.ReadBytes\n firstWriteBytes = io.WriteBytes\n } // end of for\n\ttime.Sleep(time.Second)\t\n\n // IOCountersStat\n second_ret, err := disk.IOCounters(partition)\n dealwithErr(err)\n\n var secondReadBytes, secondWriteBytes uint64\n for _, io := range second_ret {\n secondReadBytes = io.ReadBytes\n secondWriteBytes = io.WriteBytes\n } // end of for\n time.Sleep(time.Second)\n\n return secondReadBytes-firstReadBytes, secondWriteBytes-firstWriteBytes\n }", "func (covList *CoverageList) Ratio() float32 {\n\tcovList.summarize()\n\treturn covList.Coverage.Ratio()\n}", "func (r Result) RecvRate() float64 {\n\treturn float64(r.RecvBytes) / float64(r.RWInterval.Len()) * float64(time.Second)\n}", "func (o HttpFaultAbortResponseOutput) Percentage() pulumi.Float64Output {\n\treturn o.ApplyT(func(v HttpFaultAbortResponse) float64 { return v.Percentage }).(pulumi.Float64Output)\n}", "func PercentOf(part int, total int) float64 {\n\treturn (float64(part) * float64(100.00)) / float64(total)\n}", "func (t *SBF) Capacity() uint64 {\n return atomic.LoadUint64(&t.capacity)\n}", "func BaseWorkload(publishingRate float64, currentPerf float64) (numRep int32) {\n\treturn int32(math.Ceil(publishingRate / currentPerf))\n}", "func (o EipAddressOutput) Bandwidth() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EipAddress) pulumi.StringOutput { return v.Bandwidth }).(pulumi.StringOutput)\n}", "func (h *HashTable) getLoadFactor() float64 {\n\treturn float64(*h.size) / float64(len(h.table.buckets))\n}", "func GetCpuCount() float64 {\n return float64(procStatCpuCount)\n}", "func (o LinkOutput) Bandwidth() LinkBandwidthOutput {\n\treturn o.ApplyT(func(v *Link) LinkBandwidthOutput { return v.Bandwidth }).(LinkBandwidthOutput)\n}", "func (o HttpFaultAbortPtrOutput) Percentage() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *HttpFaultAbort) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Percentage\n\t}).(pulumi.Float64PtrOutput)\n}", "func (b *redisBackend) Latency() time.Duration { return time.Duration(atomic.LoadInt64(&b.latency)) }", "func Coverage() float64", "func CalcReplicas(elasticity *v1.Elasticity, publishingRate float64, currentReplicas float64) (newNumRep int32, bufferSize int32) {\n\n\t// minimum capacity -------\n\tif publishingRate < float64(elasticity.Spec.Deployment.Capacity) {\n\t\tminReplicas := int32(1)\n\t\tif elasticity.Spec.Deployment.MinReplicas != nil {\n\t\t\tminReplicas = *elasticity.Spec.Deployment.MinReplicas\n\t\t}\n\t\treturn minReplicas + elasticity.Spec.Buffer.Initial, elasticity.Spec.Buffer.Initial\n\t}\n\n\tvar bufferForCalc float64\n\tif elasticity.Status.BufferedReplicas == 0 {\n\t\tbufferForCalc = float64(elasticity.Spec.Buffer.Initial)\n\t} else {\n\t\tbufferForCalc = float64(elasticity.Status.BufferedReplicas)\n\t}\n\n\t// current capacity ---\n\tbaseWorkload := BaseWorkload(publishingRate, float64(elasticity.Spec.Deployment.Capacity))\n\t// adjust anticipation ---\n\tbufferSize = AdjustBufferAmount(publishingRate, float64(currentReplicas), bufferForCalc, float64(elasticity.Spec.Deployment.Capacity), float64(elasticity.Spec.Buffer.Threshold), elasticity.Spec.Buffer.Initial)\n\ttotalReplicas := baseWorkload + bufferSize\n\n\t// maximum capacity ---\n\tif totalReplicas > elasticity.Spec.Deployment.MaxReplicas {\n\t\ttotalReplicas = elasticity.Spec.Deployment.MaxReplicas\n\t\tbufferSize = elasticity.Spec.Buffer.Initial\n\t}\n\n\treturn totalReplicas, bufferSize\n\n}", "func (o DeliveryPipelineSerialPipelineStageStrategyCanaryCustomCanaryDeploymentPhaseConfigOutput) Percentage() pulumi.IntOutput {\n\treturn o.ApplyT(func(v DeliveryPipelineSerialPipelineStageStrategyCanaryCustomCanaryDeploymentPhaseConfig) int {\n\t\treturn v.Percentage\n\t}).(pulumi.IntOutput)\n}", "func (o StageCanarySettingsOutput) PercentTraffic() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v StageCanarySettings) *float64 { return v.PercentTraffic }).(pulumi.Float64PtrOutput)\n}", "func (nc *NvmeController) Capacity() (tb uint64) {\n\tif nc == nil {\n\t\treturn 0\n\t}\n\tfor _, n := range nc.Namespaces {\n\t\ttb += n.Size\n\t}\n\treturn\n}", "func (ncs NvmeControllers) Capacity() (tb uint64) {\n\tfor _, c := range ncs {\n\t\ttb += (*NvmeController)(c).Capacity()\n\t}\n\treturn\n}", "func getStorageBytes(capRange *csi.CapacityRange) (int64, error) {\n\tif capRange == nil {\n\t\treturn defaultVolumeSizeInBytes, nil\n\t}\n\n\tcapacity := capRange.GetRequiredBytes()\n\treturn capacity, nil\n}", "func getStorageBytes(capRange *csi.CapacityRange) (int64, error) {\n\tif capRange == nil {\n\t\treturn defaultVolumeSizeInBytes, nil\n\t}\n\n\tcapacity := capRange.GetRequiredBytes()\n\treturn capacity, nil\n}", "func gpuCapacity(self *core_v1.ResourceList) *resource.Quantity {\n\tif val, ok := (*self)[ResourceGPU]; ok {\n\t\treturn &val\n\t}\n\treturn &resource.Quantity{Format: resource.DecimalSI}\n}", "func (c *Cuckoo) GetLoadFactor() float64 {\n\treturn float64(c.Elements) / float64(c.Size)\n}", "func rateLogBytes(selRange time.Duration) func(samples []promql.Point) float64 {\n\treturn func(samples []promql.Point) float64 {\n\t\treturn sumOverTime(samples) / selRange.Seconds()\n\t}\n}", "func MilliCPUToShares(milliCPU int64) int64 {\n\treturn 0\n}", "func (c *gcControllerState) setGCPercent(in int32) int32 {\n\tif !c.test {\n\t\tassertWorldStoppedOrLockHeld(&mheap_.lock)\n\t}\n\n\tout := c.gcPercent.Load()\n\tif in < 0 {\n\t\tin = -1\n\t}\n\tc.heapMinimum = defaultHeapMinimum * uint64(in) / 100\n\tc.gcPercent.Store(in)\n\t// Update pacing in response to gcPercent change.\n\tc.commit(c.triggerRatio)\n\n\treturn out\n}", "func (o AgentPoolOutput) BandwidthLimit() BandwidthLimitResponseOutput {\n\treturn o.ApplyT(func(v *AgentPool) BandwidthLimitResponseOutput { return v.BandwidthLimit }).(BandwidthLimitResponseOutput)\n}", "func ctr(syncLvl, srvCnt int) int {\n\tc := srvCnt * syncLvl / 100\n\tif c == 0 && srvCnt > 0 {\n\t\treturn 1\n\t}\n\treturn c\n}", "func (cp *ConstantPacer) hitsPerNs() float64 {\n\treturn float64(cp.Freq) / nano\n}", "func (o HttpFaultDelayResponseOutput) Percentage() pulumi.Float64Output {\n\treturn o.ApplyT(func(v HttpFaultDelayResponse) float64 { return v.Percentage }).(pulumi.Float64Output)\n}", "func (lbs *LoadBasedAlg) getCurrentPercentsSpread(totalWorkers int) int {\n\tif len(lbs.jobClasses) < 2 {\n\t\treturn 0\n\t}\n\tminPct := 0\n\tmaxPct := 0\n\tfor _, className := range lbs.classByDescLoadPct {\n\t\tjc := lbs.jobClasses[className]\n\t\tcurrPct := int(math.Floor(float64(jc.origNumRunningTasks) * 100.0 / float64(totalWorkers)))\n\t\tpctDiff := jc.origTargetLoadPct - currPct\n\t\tif pctDiff < 0 || jc.numWaitingTasks > 0 { // only consider classes using loaned workers, or with waiting tasks\n\t\t\tminPct = min(minPct, pctDiff)\n\t\t\tmaxPct = max(maxPct, pctDiff)\n\t\t}\n\t}\n\n\treturn maxPct - minPct\n}", "func (o *SpaceInformationType) PercentSnapshotSpace() int {\n\tvar r int\n\tif o.PercentSnapshotSpacePtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PercentSnapshotSpacePtr\n\treturn r\n}", "func (o HttpFaultDelayPtrOutput) Percentage() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *HttpFaultDelay) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Percentage\n\t}).(pulumi.Float64PtrOutput)\n}", "func (scs *StorageContractSet) RetrieveRateLimit() (readBPS, writeBPS int64, packetSize uint64) {\n\treturn scs.rl.RetrieveRateLimit()\n}", "func (n *Networker) Capacity() uint64 {\n\treturn uint64(n.subnetPool.Capacity())\n}", "func calculatePercent(count int, totalRows int) (percent float64) {\n\treturn math.Round(float64(count) / float64(totalRows) * 100)\n}", "func (rm resourceMetric) percentFunction() (f func(r resource.Quantity) string) {\n\tf = func(r resource.Quantity) string {\n\t\treturn fmt.Sprintf(\"%v%%\", int64(float64(r.MilliValue())/float64(rm.allocatable.MilliValue())*100))\n\t}\n\treturn f\n}", "func (br *BandwidthMeter) BytesRead() (bytes uint64) {\n bytes = br.bytesRead\n return\n}", "func (c *core) Q() *big.Int {\n\treturn c.Curve.Params().N\n}", "func TestGetCPUPercent(t *testing.T) {\n\t// setup the faking of `cpu.Percent()`\n\toldcpuPercent := cpuPercent\n\tcpuPercent = func(interval time.Duration, percpu bool) ([]float64, error) {\n\t\tret := []float64{100}\n\t\treturn ret, nil\n\t}\n\n\t// test\n\texpected := 100\n\tactual, err := getCPUPercent()\n\n\tassert.NoError(t, err, \"`getCPUPercent()` should not have returned an error\")\n\tassert.Equal(t, expected, actual, \"`getCPUPercent` should be equal to --> 100\")\n\n\t// teardown\n\tcpuPercent = oldcpuPercent\n}", "func (p Pool) BondedRatio() types.Dec {\n\tsupply := p.TokenSupply()\n\tif supply.GT(types.ZeroDec()) {\n\t\treturn p.BondedTokens.Quo(supply)\n\t}\n\treturn types.ZeroDec()\n}", "func (o *PerCPU) Usage() float64 {\n\tu := o.User.ComputeRate()\n\tn := o.UserLowPrio.ComputeRate()\n\ts := o.System.ComputeRate()\n\tt := o.Total.ComputeRate()\n\n\tif u != math.NaN() && n != math.NaN() && s != math.NaN() &&\n\t\tt != math.NaN() && t > 0 {\n\t\treturn (u + s + n) / t\n\t}\n\treturn math.NaN()\n}", "func (o LookupAgentPoolResultOutput) BandwidthLimit() BandwidthLimitResponseOutput {\n\treturn o.ApplyT(func(v LookupAgentPoolResult) BandwidthLimitResponse { return v.BandwidthLimit }).(BandwidthLimitResponseOutput)\n}", "func (j *jobDownloadSnapshot) callExpectedBandwidth() (ul, dl uint64) {\n\t// Estimate 50kb in overhead for upload and download, and then 4 MiB\n\t// necessary to send the actual full sector payload.\n\treturn 50e3 + 1<<22, 50e3\n}", "func (o HttpFaultAbortResponsePtrOutput) Percentage() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *HttpFaultAbortResponse) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Percentage\n\t}).(pulumi.Float64PtrOutput)\n}", "func (sch *Scheduler) CalResourceRate(podUsed *[PHYNUM][DIMENSION]float64) {\n\tfor i := 0; i < PHYNUM; i++ {\n\t\tfmt.Printf(\"%s\", \"node\"+strconv.Itoa(i)+\": \")\n\t\tfor j := 0; j < DIMENSION; j++ {\n\t\t\tfmt.Printf(\"%.3f \", podUsed[i][j]/sch.reTotal[j])\n\t\t}\n\t\tfmt.Println()\n\t}\n}", "func (api *PrivateLightServerAPI) TotalCapacity() hexutil.Uint64 {\n\treturn hexutil.Uint64(api.server.priorityClientPool.totalCapacity())\n}", "func (s *frameStats) frozenFramesPercentage() float64 {\n\treturn percentage(s.FrozenFrames, s.TotalFrames)\n}", "func (br *BandwidthMeter) Duration() (duration time.Duration) {\n duration = br.lastRead.Sub(br.start)\n return\n}", "func (r Virtual_Guest) GetBandwidthTotal(startDateTime *datatypes.Time, endDateTime *datatypes.Time, direction *string, side *string) (resp uint, err error) {\n\tparams := []interface{}{\n\t\tstartDateTime,\n\t\tendDateTime,\n\t\tdirection,\n\t\tside,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getBandwidthTotal\", params, &r.Options, &resp)\n\treturn\n}", "func CalculateUploadRatio(t *torrent.Torrent, c *ClientDB) string {\n\tif c.TotalUploadedBytes > 0 && t.BytesCompleted() > 0 { //If we have actually started uploading and downloading stuff start calculating our ratio\n\t\tuploadRatio := fmt.Sprintf(\"%.2f\", float64(c.TotalUploadedBytes)/float64(t.BytesCompleted()))\n\t\treturn uploadRatio\n\t}\n\tuploadRatio := \"0.00\" //we haven't uploaded anything so no upload ratio just pass a string directly\n\treturn uploadRatio\n}", "func (o StageCanarySettingsPtrOutput) PercentTraffic() pulumi.Float64PtrOutput {\n\treturn o.ApplyT(func(v *StageCanarySettings) *float64 {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.PercentTraffic\n\t}).(pulumi.Float64PtrOutput)\n}" ]
[ "0.64463323", "0.56960267", "0.5637167", "0.5596584", "0.5571499", "0.5541268", "0.5538112", "0.54866683", "0.5401307", "0.5400026", "0.5393798", "0.53594464", "0.5357982", "0.53403497", "0.5308735", "0.5300413", "0.5234758", "0.52156454", "0.51747286", "0.5167365", "0.5117468", "0.5087347", "0.5061056", "0.50501853", "0.5034301", "0.5032535", "0.5023604", "0.50215524", "0.50096047", "0.4989015", "0.4981143", "0.49733356", "0.49604815", "0.49529305", "0.495192", "0.49515542", "0.4945447", "0.49396294", "0.49283555", "0.4915588", "0.49102145", "0.49059254", "0.4901829", "0.48986495", "0.48800713", "0.48736185", "0.48715872", "0.48500648", "0.48495585", "0.48370945", "0.48279026", "0.4822915", "0.4819138", "0.48148128", "0.48073506", "0.48067406", "0.48030052", "0.47952306", "0.4793643", "0.47839442", "0.47750586", "0.47745287", "0.47745016", "0.47738796", "0.47730622", "0.47663462", "0.47638437", "0.47635853", "0.47635853", "0.47605696", "0.47538075", "0.47515303", "0.47514457", "0.47484308", "0.4732195", "0.47299495", "0.4729718", "0.47207114", "0.4716884", "0.4716088", "0.47157645", "0.47059855", "0.47059143", "0.47039333", "0.4702954", "0.47018588", "0.4691032", "0.4690902", "0.4687879", "0.46835232", "0.4678832", "0.46705648", "0.46700704", "0.4669244", "0.46690542", "0.46595505", "0.46585503", "0.46582326", "0.46555388", "0.46519023" ]
0.633253
1
The status of the traffic scheduling policy. Creating: The function is being created.Active: available.Modifying: is being modified.Deleting: Deleted.Deleted: Deleted.
func (o InterRegionTrafficQosQueueOutput) Status() pulumi.StringOutput { return o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (o GetSecurityPoliciesPolicyOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecurityPoliciesPolicy) string { return v.Status }).(pulumi.StringOutput)\n}", "func (o ServerPolicyOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ServerPolicy) pulumi.StringPtrOutput { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o AutoSnapshotPolicyOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AutoSnapshotPolicy) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (o TlsCipherPolicyOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *TlsCipherPolicy) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (j *Job) Status() string {\n\tswitch {\n\tcase j.ActiveRuns != nil:\n\t\treturn \"Running\"\n\tcase len(j.Schedules) == 0:\n\t\treturn \"Unscheduled\"\n\tdefault:\n\t\treturn \"Scheduled\"\n\t}\n}", "func (policy *StorageAccountsManagementPolicy) GetStatus() genruntime.ConvertibleStatus {\n\treturn &policy.Status\n}", "func (policy *StorageAccountsManagementPolicy) GetStatus() genruntime.ConvertibleStatus {\n\treturn &policy.Status\n}", "func (j *ScheduledJob) ScheduleStatus() string {\n\treturn j.rec.ScheduleState.Status\n}", "func (o BucketIntelligentTieringConfigurationOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketIntelligentTieringConfiguration) pulumi.StringPtrOutput { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (policy *ServersConnectionPolicy) GetStatus() genruntime.ConvertibleStatus {\n\treturn &policy.Status\n}", "func (p *Pool) Status() string {\n\tswitch {\n\tcase p.status == NotStarted:\n\t\treturn \"not started\"\n\tcase p.status == Started:\n\t\treturn \"started\"\n\tcase p.status == Stopped:\n\t\treturn \"stopped\"\n\t}\n\n\treturn \"unknown\"\n}", "func Status(c *SQLConnection) (err error) {\n\trecords, err := migrate.GetMigrationRecords(c.db, c.dialect)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfmt.Println(\"Applied At Migration\")\n\tfmt.Println(strings.Repeat(\"=\", 80))\n\n\tfor _, migration := range records {\n\t\tappliedAt := convert.TimeToString(migration.AppliedAt, convert.ISO8601)\n\t\tfmt.Printf(\"%s - %s\\n\", appliedAt, migration.Id)\n\t}\n\n\tnewRecords, _, err := migrate.PlanMigration(c.db, c.dialect, c.source, migrate.Up, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, migration := range newRecords {\n\t\tfmt.Printf(\"Pending - %s\\n\", migration.Id)\n\t}\n\n\treturn\n}", "func (r *Distribution) Status() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"status\"])\n}", "func (m *ThreatAssessmentRequest) GetStatus()(*ThreatAssessmentStatus) {\n return m.status\n}", "func (o RegionAutoscalerOutput) ScalingScheduleStatus() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v *RegionAutoscaler) pulumi.StringMapOutput { return v.ScalingScheduleStatus }).(pulumi.StringMapOutput)\n}", "func (throttler *Throttler) Status() *ThrottlerStatus {\n\treturn &ThrottlerStatus{\n\t\tKeyspace: throttler.keyspace,\n\t\tShard: throttler.shard,\n\n\t\tIsLeader: throttler.isLeader.Load(),\n\t\tIsOpen: throttler.isOpen.Load(),\n\t\tIsEnabled: throttler.isEnabled.Load(),\n\t\tIsDormant: throttler.isDormant(),\n\n\t\tQuery: throttler.GetMetricsQuery(),\n\t\tThreshold: throttler.GetMetricsThreshold(),\n\n\t\tAggregatedMetrics: throttler.aggregatedMetricsSnapshot(),\n\t\tMetricsHealth: throttler.metricsHealthSnapshot(),\n\t}\n}", "func (o InstanceFromTemplateOutput) DesiredStatus() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *InstanceFromTemplate) pulumi.StringOutput { return v.DesiredStatus }).(pulumi.StringOutput)\n}", "func (r *Random) GetStatus() interface{} {\n\treturn SourceStatusRunning\n}", "func (s *AccessPolicy) GetStatus() resv1.Status {\n\treturn &s.Status\n}", "func (o PodSchedulingOutput) Status() PodSchedulingStatusPtrOutput {\n\treturn o.ApplyT(func(v *PodScheduling) PodSchedulingStatusPtrOutput { return v.Status }).(PodSchedulingStatusPtrOutput)\n}", "func (o HorizontalPodAutoscalerConditionPatchOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerConditionPatch) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o HorizontalPodAutoscalerConditionPatchOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerConditionPatch) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o WorkloadStatusConfigStaticOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v WorkloadStatusConfigStatic) string { return v.Status }).(pulumi.StringOutput)\n}", "func (o ReservedInstanceOutput) AllocationStatus() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.AllocationStatus }).(pulumi.StringOutput)\n}", "func (b *Base) GetStatus() string {\n\treturn `\n\tGoCryptoTrader Service: Online\n\tService Started: ` + ServiceStarted.String()\n}", "func (o HorizontalPodAutoscalerConditionOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerCondition) string { return v.Status }).(pulumi.StringOutput)\n}", "func (o HorizontalPodAutoscalerConditionOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerCondition) string { return v.Status }).(pulumi.StringOutput)\n}", "func (t *Task) Status() TaskStatusType {\n\treturn t.status\n}", "func (tj *TensorFlowJob) GetStatus() (status string) {\n\tstatus = \"PENDING\"\n\tif tj.tfjob.Name == \"\" {\n\t\treturn status\n\t}\n\n\tt := checkStatus(tj.tfjob.Status)\n\tif t == commonv1.JobCreated || t == commonv1.JobRestarting {\n\t\tstatus = \"PENDING\"\n\t} else {\n\t\tstatus = strings.ToUpper(string(t))\n\t}\n\n\treturn status\n}", "func (me TAssignmentStatus) IsApproved() bool { return me.String() == \"Approved\" }", "func (o BucketReplicationConfigRuleDestinationReplicationTimeOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleDestinationReplicationTime) string { return v.Status }).(pulumi.StringOutput)\n}", "func (l *qpsLimiter) Status() (max, cur int, interval time.Duration) {\n\tmax = int(atomic.LoadInt32(&l.limit))\n\tcur = int(atomic.LoadInt32(&l.tokens))\n\tinterval = l.interval\n\treturn\n}", "func (o JobConditionOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v JobCondition) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func PrintStatus() {\n\threpo := sqlite.NewHeadsRepo()\n\ttrepo := sqlite.NewTaskRepo()\n\n\tvar pr *domain.Project\n\tvar t *domain.Task\n\tvar err error\n\n\tif t, pr, err = hrepo.GetCurrentTask(); err != nil {\n\t\tfmt.Printf(\"Error :%v\\n\", err)\n\t\treturn\n\t}\n\n\ttaskName := \"No definida\"\n\ttid := 0\n\n\tif t != nil {\n\t\ttaskName = t.Name\n\t\ttid = int(t.ID)\n\t}\n\n\tprojectName := \"No definido\"\n\tpid := 0\n\n\tif pr != nil {\n\t\tprojectName = pr.Name\n\t\tpid = int(pr.ID)\n\t}\n\n\ttoday, week, month, total, _ := trepo.GetAggregates(tid)\n\n\tst := status{\n\t\tCurrentProjectName: projectName,\n\t\tCurrentTaskName: taskName,\n\t\tPID: pid,\n\t\tTID: tid,\n\t\tTimeToday: minHours(today),\n\t\tTimeThisWeek: minHours(week),\n\t\tTimeThisMonth: minHours(month),\n\t\tTimeTotal: minHours(total),\n\t}\n\n\treport, err := template.New(\"report\").Parse(statusTemplate)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error %v\", err)\n\t\treturn\n\t}\n\n\terr = report.Execute(os.Stdout, st)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Error %v\", err)\n\t}\n}", "func (o ValidatingAdmissionPolicyTypeOutput) Status() ValidatingAdmissionPolicyStatusPtrOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyType) *ValidatingAdmissionPolicyStatus { return v.Status }).(ValidatingAdmissionPolicyStatusPtrOutput)\n}", "func (o BucketReplicationConfigurationRuleDestinationReplicationTimeOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigurationRuleDestinationReplicationTime) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\n\tif seq < px.Min() {\n\t\treturn Forgotten, nil\n\t}\n\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\n\tif val, ok := px.decidedVals[seq]; ok {\n\t\treturn Decided, val\n\t}\n\treturn Pending, nil\n}", "func (o StorageNodeStatusConditionsOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageNodeStatusConditions) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o WorkloadStatusConfigStaticPtrOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *WorkloadStatusConfigStatic) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Status\n\t}).(pulumi.StringPtrOutput)\n}", "func (at *Attacker) Status(uuid string) (string, error) {\n\tat.lock.RLock()\n\tdefer at.lock.RUnlock()\n\tentry, ok := at.scheduler[uuid]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"attack reference %s not found\", uuid)\n\t}\n\treturn entry.Status(), nil\n}", "func (dateService) Status(ctx context.Context) (string, error) {\n\treturn \"ok\", nil\n}", "func (o CapacityReservationOutput) Status() CapacityReservationStatusOutput {\n\treturn o.ApplyT(func(v *CapacityReservation) CapacityReservationStatusOutput { return v.Status }).(CapacityReservationStatusOutput)\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\t// Your code here.\n\tif seq < px.min {\n\t\treturn Forgotten, nil\n\t}\n\n\tinstance, ok := px.getInstance(seq)\n\tif !ok {\n\t\treturn Unknown, nil\n\t}\n\treturn instance.status, instance.aValue\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\t// Your code here.\n\t// check if seq number is less than min, return forgotten if it is\n\t// check map for struct for given seq, if agreed value is nil, return pending with agreed value\n\t// otherwise return decided and agreed value for seq\n\n\tmin := px.Min()\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\tif seq < min {\n\t\treturn Forgotten, nil\n\t} else if px.instances[seq] != nil {\n\t\tif px.instances[seq].decided {\n\t\t\treturn Decided, px.instances[seq].va\n\t\t}\n\t}\n\treturn Pending, nil\n}", "func (tp *ThreadPool) Status() string {\n\tvar status string\n\n\ttp.workerMapLock.Lock()\n\tworkerCount := len(tp.workerMap)\n\tworkerKill := tp.workerKill\n\ttp.workerMapLock.Unlock()\n\n\tif workerCount > 0 {\n\t\tif workerKill == -1 {\n\t\t\tstatus = StatusStopping\n\t\t} else {\n\t\t\tstatus = StatusRunning\n\t\t}\n\t} else {\n\t\tstatus = StatusStopped\n\t}\n\n\treturn status\n}", "func (ls ListSchema) Status() string {\n\treturn ls.rawResponse.Status\n}", "func (o GetRulesRuleOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRule) string { return v.Status }).(pulumi.StringOutput)\n}", "func (o GetRulesRuleOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRule) string { return v.Status }).(pulumi.StringOutput)\n}", "func (a *Agent) Status() string {\n\ta.mutex.RLock()\n\tdefer a.mutex.RUnlock()\n\n\treturn a.status\n}", "func (px *Paxos) Status(seq int) (bool, interface{}) {\n\t// Your code here.\n\treturn px.Lslots[seq].Decided, px.Lslots[seq].V\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\tfate := Pending\n\tvar retValue interface{}\n\tpx.mu.Lock()\n\tif seq < px.minSeq {\n\t\tfate = Forgotten\n\t} else if px.isDecided(seq) {\n\t\tfate = Decided\n\t\tretValue = px.getDecidedValue(seq)\n\t}\n\tpx.mu.Unlock()\n\treturn fate, retValue\n}", "func (o StorageClusterStatusConditionsOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterStatusConditions) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o OrganizationJobTriggerOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OrganizationJobTrigger) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (o GetConfigurationRecordersRecorderOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetConfigurationRecordersRecorder) string { return v.Status }).(pulumi.StringOutput)\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n \n if seq < px.Min() {\n return Forgotten, nil\n }\n\n instance := px.getInstance(seq)\n return instance.Fate, instance.Va\n}", "func (m *SecurityActionState) GetStatus()(*OperationStatus) {\n val, err := m.GetBackingStore().Get(\"status\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*OperationStatus)\n }\n return nil\n}", "func (o ReservedInstanceOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ReservedInstance) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (o ApplicationStatusConditionsOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationStatusConditions) string { return v.Status }).(pulumi.StringOutput)\n}", "func statusOf(transaction transaction) string {\n\treturn networkaccountpurchase.OPEN\n}", "func (sss StorageServiceStats) Status() string {\n\treturn sss.rawResponse.Status\n}", "func (csapr ContainersSetAccessPolicyResponse) Status() string {\n\treturn csapr.rawResponse.Status\n}", "func (s *Service) Status() (string, time.Time) {\n\tif m := s.mgr; m != nil {\n\t\tm.lock()\n\t\tdefer m.unlock()\n\t}\n\treturn s.reason, s.stamp\n}", "func (b *Build) Status(c *router.Control) {\n\tqueue, current, reassign := b.state.GetTasks()\n\n\tresponse := struct {\n\t\tReassign []string `json:\"reassign\"`\n\t\tQueue []string `json:\"queue\"`\n\t\tInProgress []string `json:\"inProgress\"`\n\t}{\n\t\tReassign: reassign,\n\t\tQueue: queue,\n\t\tInProgress: current,\n\t}\n\n\tc.Code(http.StatusOK).Body(response)\n}", "func (m *AccessPackageAssignment) GetStatus()(*string) {\n return m.status\n}", "func (o EmailIdentityDkimSigningAttributesOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v EmailIdentityDkimSigningAttributes) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (m *ThreatAssessmentRequest) GetStatus()(*ThreatAssessmentStatus) {\n val, err := m.GetBackingStore().Get(\"status\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*ThreatAssessmentStatus)\n }\n return nil\n}", "func (m *ScheduleItem) GetStatus()(*FreeBusyStatus) {\n val, err := m.GetBackingStore().Get(\"status\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*FreeBusyStatus)\n }\n return nil\n}", "func (r *runtime) Status() *Status {\n\thealth := r.getError().Error()\n\n\treturn &Status{\n\t\tHealth: health,\n\t\tState: r.getState(),\n\t\tError: r.getError().Error(),\n\t\tStatus: r.httpStat.Status(),\n\t\tTopN: r.topN.Status(),\n\t}\n}", "func (ssp StorageServiceProperties) Status() string {\n\treturn ssp.rawResponse.Status\n}", "func (ae *attackEntry) Status() string {\n\treturn ae.status\n}", "func (c *Collection) Status(w http.ResponseWriter, req *http.Request) {\n\t// responds with current status of the analysis\n\t// checks systemtap is running, this is probably done via global variable?\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\t// Your code here.\n\tif seq < px.Min() {\n\t\treturn Forgotten, nil\n\t}\n\n\tnode, ok := px.prepareStatus.Find(seq)\n\tif ok && node.State.Done {\n\t\treturn Decided, node.State.VA\n\t}\n\treturn Pending, nil\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\t// Your code here\n\n\t//log.Printf(\"judge status of %d\\n\", seq)\n\tif seq < px.Min() {\n\t\t//\tlog.Printf(\"forgotten\\n\")\n\t\treturn Forgotten, nil\n\t}\n\t//log.Printf(\"no forgotten\\n\")\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\n\t_, exist := px.acceptor[seq]\n\n\tif exist {\n\t\treturn px.acceptor[seq].state, px.acceptor[seq].decided.Value\n\t}\n\treturn Pending, nil\n}", "func (self *client) GetStatus() {\n\n}", "func (twrkr *twerk) status() Status {\n\tlive := twrkr.liveWorkersNum.Get()\n\tworking := twrkr.currentlyWorkingNum.Get()\n\tinQueue := len(twrkr.jobListener)\n\n\treturn Status{\n\t\tlive: live,\n\t\tworking: working,\n\t\tjobsInQueue: inQueue,\n\t}\n}", "func (px *Paxos) Status(seq int) (bool, interface{}) {\n\t// Your code here.\n\tcurMin := px.Min()\n\tpx.mu.Lock()\n\tdefer px.mu.Unlock()\n\n\ttargetIns := px.instances[seq]\n\tif seq < curMin || targetIns == nil {\n\t\treturn false, nil\n\t} else {\n\t\t//debug\n\t\t// fmt.Printf(\"Status: isDecided=%t, va=%v, me=%d, seq %d\\n\", targetIns.isDecided, targetIns.vDecided, px.me, seq)\n\t\treturn targetIns.isDecided, targetIns.vDecided\n\t}\n}", "func (rule *NamespacesEventhubsAuthorizationRule) GetStatus() genruntime.ConvertibleStatus {\n\treturn &rule.Status\n}", "func (px *Paxos) Status(seq int) (Fate, interface{}) {\n\t// Your code here.\n\tpx.RLock()\n\tdefer px.RUnlock()\n\tif seq < px.minSeq {\n\t\treturn Forgotten, nil\n\t}\n\tsi := px.seqInstanceBySeq(seq)\n\treturn si.Status(), si.Value()\n}", "func (control *Control) Status(waived string) (status string) {\n\tstatus = ResultStatusPassed\n\tfor _, result := range control.Results {\n\t\tif result.Status == ResultStatusFailed {\n\t\t\tstatus = ResultStatusFailed\n\t\t\tbreak\n\t\t} else if result.Status == ResultStatusSkipped {\n\t\t\tstatus = ResultStatusSkipped\n\t\t}\n\t}\n\tif waived == ControlWaivedStrYesRun || waived == ControlWaivedStrYes {\n\t\tstatus = ResultStatusWaived\n\t}\n\treturn status\n}", "func (o *SSHAuthorizationPolicy) GetActiveSchedule() string {\n\n\treturn o.ActiveSchedule\n}", "func (p *DirectBuy) Status() error {\n\tdefer p.statusLock.RUnlock()\n\tp.statusLock.RLock()\n\treturn p.status\n}", "func (o MachineInstanceStatusConditionsOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v MachineInstanceStatusConditions) string { return v.Status }).(pulumi.StringOutput)\n}", "func (f Future) Status() string {\n\tif f.pt == nil {\n\t\treturn \"\"\n\t}\n\treturn f.pt.pollingStatus()\n}", "func (o ApplicationStatusResourcesOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusResources) *string { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (f *FaasController) Status() *supervisor.Status {\n\treturn &supervisor.Status{}\n}", "func GetStatus(cfg *Config) Status {\n\tnow := time.Now().Unix()\n\n\ts := Status{\n\t\tPID: os.Getpid(),\n\t\tService: \"list-service\",\n\t}\n\n\ts.Status = \"ok\"\n\ts.Version = Version()\n\ts.CPUs = runtime.NumCPU()\n\ts.GoVers = runtime.Version()\n\ts.TimeStamp = now\n\ts.UpTime = now - InstanceStartTime\n\ts.LogLevel = log.GetLevel()\n\n\tif host, err := os.Hostname(); err == nil {\n\t\ts.Hostname = host\n\t}\n\n\treturn s\n}", "func (o ApplicationStatusOutput) Policy() ApplicationStatusPolicyArrayOutput {\n\treturn o.ApplyT(func(v ApplicationStatus) []ApplicationStatusPolicy { return v.Policy }).(ApplicationStatusPolicyArrayOutput)\n}", "func PolicyTypeStatus_Values() []string {\n\treturn []string{\n\t\tPolicyTypeStatusEnabled,\n\t\tPolicyTypeStatusPendingEnable,\n\t\tPolicyTypeStatusPendingDisable,\n\t}\n}", "func (o RuleMfaOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RuleMfa) pulumi.StringPtrOutput { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o GetVpdsVpdOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpdsVpd) string { return v.Status }).(pulumi.StringOutput)\n}", "func (o BgpIpOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BgpIp) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (o RegionAutoscalerOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegionAutoscaler) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (o LaunchOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Launch) pulumi.StringOutput { return v.Status }).(pulumi.StringOutput)\n}", "func (o BucketReplicationConfigurationRuleDestinationReplicationTimePtrOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigurationRuleDestinationReplicationTime) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Status\n\t}).(pulumi.StringPtrOutput)\n}", "func (s Status) String() string {\n\tswitch s {\n\tcase Created:\n\t\treturn \"created\"\n\tcase Creating:\n\t\treturn \"creating\"\n\tcase Paused:\n\t\treturn \"paused\"\n\tcase Running:\n\t\treturn \"running\"\n\tcase Stopped:\n\t\treturn \"stopped\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n\n}", "func (o BucketReplicationConfigRuleDestinationReplicationTimePtrOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigRuleDestinationReplicationTime) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Status\n\t}).(pulumi.StringPtrOutput)\n}", "func (b *Backup) Status() BackupStatus {\n\treturn BackupStatus{int(C.sqlite3_backup_remaining(b.sb)), int(C.sqlite3_backup_pagecount(b.sb))}\n}", "func (o ValidatingAdmissionPolicyPatchTypeOutput) Status() ValidatingAdmissionPolicyStatusPatchPtrOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyPatchType) *ValidatingAdmissionPolicyStatusPatch { return v.Status }).(ValidatingAdmissionPolicyStatusPatchPtrOutput)\n}", "func (o SignonOutput) Status() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Signon) pulumi.StringPtrOutput { return v.Status }).(pulumi.StringPtrOutput)\n}", "func (o BucketReplicationConfigRuleOutput) Status() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRule) string { return v.Status }).(pulumi.StringOutput)\n}" ]
[ "0.637768", "0.61041886", "0.60253423", "0.6005666", "0.58875674", "0.58757114", "0.58757114", "0.5827052", "0.5817711", "0.5783979", "0.57203084", "0.5682372", "0.56083393", "0.5584729", "0.5578477", "0.55780166", "0.55646974", "0.55562615", "0.5540438", "0.5537126", "0.55078566", "0.55078566", "0.5505557", "0.5487373", "0.5482925", "0.5481117", "0.5481117", "0.5447543", "0.54445773", "0.54212254", "0.5421202", "0.54045993", "0.5399316", "0.5388969", "0.53846407", "0.5380093", "0.53687626", "0.53641576", "0.53640926", "0.5361072", "0.5357738", "0.5353608", "0.53520495", "0.5349911", "0.53452706", "0.5341994", "0.5339086", "0.5339086", "0.53356206", "0.5335035", "0.5329558", "0.532928", "0.532503", "0.53191864", "0.5315343", "0.5313089", "0.5291083", "0.52886957", "0.5286358", "0.52814907", "0.5276741", "0.52762747", "0.5272135", "0.5262115", "0.5261909", "0.5254178", "0.5250153", "0.5250002", "0.5248617", "0.52478236", "0.5236198", "0.52322537", "0.5224016", "0.5220033", "0.52140987", "0.52114373", "0.52106947", "0.5209537", "0.5209066", "0.5208754", "0.5200035", "0.51892245", "0.5180099", "0.5178304", "0.5173509", "0.51731855", "0.51673174", "0.51649916", "0.51638454", "0.51627976", "0.51624453", "0.51619065", "0.51606005", "0.5160014", "0.5157087", "0.5155433", "0.51539075", "0.5147879", "0.5147794", "0.514114" ]
0.564104
12
The ID of the traffic scheduling policy.
func (o InterRegionTrafficQosQueueOutput) TrafficQosPolicyId() pulumi.StringOutput { return o.ApplyT(func(v *InterRegionTrafficQosQueue) pulumi.StringOutput { return v.TrafficQosPolicyId }).(pulumi.StringOutput) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Policy) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o OrganizationSecurityPolicyOutput) PolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OrganizationSecurityPolicy) pulumi.StringOutput { return v.PolicyId }).(pulumi.StringOutput)\n}", "func (v *AddDecisionTaskRequest) GetScheduleID() (o int64) {\n\tif v != nil && v.ScheduleID != nil {\n\t\treturn *v.ScheduleID\n\t}\n\treturn\n}", "func (j *ScheduledJob) ScheduleID() int64 {\n\treturn j.rec.ScheduleID\n}", "func (o InfraAlertConditionOutput) PolicyId() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *InfraAlertCondition) pulumi.IntOutput { return v.PolicyId }).(pulumi.IntOutput)\n}", "func (o GetSecurityPoliciesPolicyOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecurityPoliciesPolicy) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ListenerOutput) SecurityPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Listener) pulumi.StringOutput { return v.SecurityPolicyId }).(pulumi.StringOutput)\n}", "func (o ControlPolicyAttachmentOutput) PolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ControlPolicyAttachment) pulumi.StringOutput { return v.PolicyId }).(pulumi.StringOutput)\n}", "func (v *AddActivityTaskRequest) GetScheduleID() (o int64) {\n\tif v != nil && v.ScheduleID != nil {\n\t\treturn *v.ScheduleID\n\t}\n\treturn\n}", "func (p *DefaultPolicy) GetID() string {\n\treturn p.ID\n}", "func (o SplitTunnelOutput) PolicyId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *SplitTunnel) pulumi.StringPtrOutput { return v.PolicyId }).(pulumi.StringPtrOutput)\n}", "func (o *VRSRedeploymentpolicy) Identifier() string {\n\n\treturn o.ID\n}", "func (o FirewallPolicyAssociationResponseOutput) FirewallPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FirewallPolicyAssociationResponse) string { return v.FirewallPolicyId }).(pulumi.StringOutput)\n}", "func (o *GuardianPolicyDataData) GetPolicyId() string {\n\tif o == nil || o.PolicyId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.PolicyId\n}", "func (o RefreshScheduleMapOutput) ScheduleId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RefreshScheduleMap) *string { return v.ScheduleId }).(pulumi.StringPtrOutput)\n}", "func (agg *Planner) ID() PlannerID { return agg.id }", "func (o GetListenersListenerOutput) SecurityPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetListenersListener) string { return v.SecurityPolicyId }).(pulumi.StringOutput)\n}", "func (o RefreshScheduleMapPtrOutput) ScheduleId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *RefreshScheduleMap) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ScheduleId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *MicrosoftGraphWindows10CompliancePolicy) GetId() string {\n\tif o == nil || o.Id == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (o GetEndpointAclPoliciesPolicyOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointAclPoliciesPolicy) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ResourcePolicyExemptionOutput) PolicyAssignmentId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyExemption) pulumi.StringOutput { return v.PolicyAssignmentId }).(pulumi.StringOutput)\n}", "func (o SecurityPolicyAssociationResponseOutput) SecurityPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SecurityPolicyAssociationResponse) string { return v.SecurityPolicyId }).(pulumi.StringOutput)\n}", "func (c *localComponent) ID() dependency.Instance {\n\treturn dependency.PolicyBackend\n}", "func (transaction *ScheduleSignTransaction) GetScheduleID() ScheduleID {\n\tif transaction.scheduleID == nil {\n\t\treturn ScheduleID{}\n\t}\n\n\treturn *transaction.scheduleID\n}", "func (r *LoadBalancerBackendServerPolicy) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o GetTrafficPolicyDocumentRuleOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentRule) string { return v.Id }).(pulumi.StringOutput)\n}", "func (cfg *Static) GetID() string {\n\treturn cfg.JobName\n}", "func (p scheduleWithOverProvisioningAwareness) name() policyName {\n\treturn overProvisioningPolicy\n}", "func (p scheduleOnHost) name() policyName {\n\treturn scheduleOnHostAnnotationPolicy\n}", "func (t *Task) ID() uint64 { t.mutex.RLock(); defer t.mutex.RUnlock(); return t.id }", "func (e *Policy) GetID() *identity.ID {\n\treturn e.ID\n}", "func (r *Policy) ResourceId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"resourceId\"])\n}", "func (r *LaunchConfiguration) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o *SSHAuthorizationPolicy) Identifier() string {\n\n\treturn o.ID\n}", "func (id WorkflowId) ID() string {\n\tfmtString := \"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Logic/workflows/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.WorkflowName)\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicySchedule) *string { return v.Schedule }).(pulumi.StringPtrOutput)\n}", "func (o *RequestsDeploymentScheduledBackup) GetBackupPolicyId() string {\n\tif o == nil || o.BackupPolicyId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.BackupPolicyId\n}", "func (o *ModelsBackupSchedule) GetId() string {\n\tif o == nil || o.Id == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) GetPrincipalId()(*string) {\n return m.principalId\n}", "func (p *ResourcePool) ID() string {\n\treturn fmt.Sprintf(\"resourcepool(%s)\", p.manager.Name())\n}", "func (m *PrivilegedAccessGroupEligibilitySchedule) GetPrincipalId()(*string) {\n val, err := m.GetBackingStore().Get(\"principalId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o SqlPoolVulnerabilityAssessmentOutput) SqlPoolSecurityAlertPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SqlPoolVulnerabilityAssessment) pulumi.StringOutput { return v.SqlPoolSecurityAlertPolicyId }).(pulumi.StringOutput)\n}", "func (o ConfigurationBackupOutput) SchedulePolicy() ConfigurationBackupSchedulePolicyPtrOutput {\n\treturn o.ApplyT(func(v ConfigurationBackup) *ConfigurationBackupSchedulePolicy { return v.SchedulePolicy }).(ConfigurationBackupSchedulePolicyPtrOutput)\n}", "func ResourcePolicyModuleID(resource, version string) ModuleID {\n\treturn GenModuleIDFromName(ResourcePolicyModuleName(resource, version))\n}", "func (o *WafPolicyGroup) GetId() string {\n\tif o == nil || o.Id == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (id PacketCoreControlPlaneId) ID() string {\n\tfmtString := \"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.MobileNetwork/packetCoreControlPlanes/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroupName, id.PacketCoreControlPlaneName)\n}", "func (r *LoadBalancerCookieStickinessPolicy) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (id GlobalRulestackId) ID() string {\n\tfmtString := \"/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks/%s\"\n\treturn fmt.Sprintf(fmtString, id.GlobalRulestackName)\n}", "func (b *rateWindowBehavior) ID() string {\n\treturn b.id\n}", "func (o *StorageNetAppSnapshotPolicySchedule) GetClassId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ClassId\n}", "func (o ResourcePolicyInstanceSchedulePolicySchedulePtrOutput) Schedule() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ResourcePolicyInstanceSchedulePolicySchedule) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Schedule\n\t}).(pulumi.StringPtrOutput)\n}", "func (r *ScheduledAction) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (r Resource) ID() string {\n\treturn r.id\n}", "func (m *BookingBusiness) GetSchedulingPolicy()(BookingSchedulingPolicyable) {\n val, err := m.GetBackingStore().Get(\"schedulingPolicy\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(BookingSchedulingPolicyable)\n }\n return nil\n}", "func PolicyDefinitionID(input string) (*PolicyDefinitionId, error) {\n\t// in general, the id of a definition should be (for custom policy definition):\n\t// {scope}/providers/Microsoft.Authorization/policyDefinitions/{name}\n\t// and for built-in policy-definition:\n\t// /providers/Microsoft.Authorization/policyDefinitions/{name}\n\tregex := regexp.MustCompile(`/providers/[Mm]icrosoft\\.[Aa]uthorization/policy[Dd]efinitions/`)\n\tif !regex.MatchString(input) {\n\t\treturn nil, fmt.Errorf(\"unable to parse Policy Definition ID %q\", input)\n\t}\n\n\tsegments := regex.Split(input, -1)\n\n\tif len(segments) != 2 {\n\t\treturn nil, fmt.Errorf(\"unable to parse Policy Definition ID %q: Expected 2 segments after split\", input)\n\t}\n\n\tscope := segments[0]\n\tname := segments[1]\n\tif name == \"\" {\n\t\treturn nil, fmt.Errorf(\"unable to parse Policy Definition ID %q: definition name is empty\", input)\n\t}\n\n\tif scope == \"\" {\n\t\treturn &PolicyDefinitionId{\n\t\t\tName: name,\n\t\t\tId: input,\n\t\t}, nil\n\t}\n\n\tscopeId, err := PolicyScopeID(scope)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse Policy Definition ID %q: %+v\", input, err)\n\t}\n\n\treturn &PolicyDefinitionId{\n\t\tName: name,\n\t\tId: input,\n\t\tPolicyScopeId: scopeId,\n\t}, nil\n}", "func (o VolumeGroupSapHanaVolumeDataProtectionSnapshotPolicyOutput) SnapshotPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v VolumeGroupSapHanaVolumeDataProtectionSnapshotPolicy) string { return v.SnapshotPolicyId }).(pulumi.StringOutput)\n}", "func (p preferScheduleOnHost) name() policyName {\n\treturn preferScheduleOnHostAnnotationPolicy\n}", "func (sc *ConditionsScraper) ID() string {\n\treturn \"sc-pt-ml-freqs\"\n}", "func (o ConfigurationBackupSchedulePolicyOutput) SchedulePolicyType() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ConfigurationBackupSchedulePolicy) *string { return v.SchedulePolicyType }).(pulumi.StringPtrOutput)\n}", "func (r *Rule) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (pk PublicKey) ID() string {\n\treturn stringEntry(pk[IDProperty])\n}", "func (o *SnapmirrorCreateRequest) Policy() string {\n\tvar r string\n\tif o.PolicyPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.PolicyPtr\n\treturn r\n}", "func (mgr *LocalHashMapDBMgr) Policy() string {\n\treturn mgr.policy\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) GetTargetScheduleId()(*string) {\n return m.targetScheduleId\n}", "func (mt *MTraffic) Id() []byte {\n\treturn []byte(mt.Time.Format(time.RFC3339))\n}", "func (id OfferPlanId) ID() string {\n\tfmtString := \"/subscriptions/%s/providers/Microsoft.MarketplaceOrdering/offerTypes/virtualMachine/publishers/%s/offers/%s/plans/%s\"\n\treturn fmt.Sprintf(fmtString, id.SubscriptionId, id.PublisherId, id.OfferId, id.PlanId)\n}", "func (w *AuthWorker) ID() int {\n\treturn w.id\n}", "func (rr *RecordingRule) ID() uint64 {\n\treturn rr.RuleID\n}", "func (p antiAffinityLabel) name() policyName {\n\treturn antiAffinityLabelPolicy\n}", "func (t Task) ID() int {\n\treturn t.id\n}", "func (m *AdapTuning) GetID() uint32 {\n\treturn 11010\n}", "func (o LookupFirewallPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (n *resPool) ID() string {\n\treturn n.id\n}", "func workflowID(smName, suffix string) string {\n\tif suffix == \"\" {\n\t\tsuffix = shortUUID()\n\t}\n\tid := fmt.Sprintf(\"%s--%s\", smName, suffix)\n\n\t// ensure the generated ID is within the 80 character limit\n\tif len(id) > 80 {\n\t\treturn id[:80]\n\t}\n\treturn id\n}", "func (o ConfigurationBackupPtrOutput) SchedulePolicy() ConfigurationBackupSchedulePolicyPtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationBackup) *ConfigurationBackupSchedulePolicy {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SchedulePolicy\n\t}).(ConfigurationBackupSchedulePolicyPtrOutput)\n}", "func (s *SchedulePolicyServer) Delete(\n\tctx context.Context,\n\treq *api.SdkSchedulePolicyDeleteRequest,\n) (*api.SdkSchedulePolicyDeleteResponse, error) {\n\tif s.cluster() == nil {\n\t\treturn nil, status.Error(codes.Unavailable, \"Resource has not been initialized\")\n\t}\n\n\tif len(req.GetName()) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Must supply Schedule name\")\n\t}\n\n\terr := s.cluster().SchedPolicyDelete(req.GetName())\n\tif err != nil && err != kvdb.ErrNotFound {\n\t\treturn nil, status.Errorf(\n\t\t\tcodes.Internal,\n\t\t\t\"Failed to delete schedule policy: %v\",\n\t\t\terr.Error())\n\t}\n\n\treturn &api.SdkSchedulePolicyDeleteResponse{}, nil\n}", "func (a *Agent) ID() string {\n\ta.mutex.RLock()\n\tdefer a.mutex.RUnlock()\n\n\treturn a.id\n}", "func (o GetTrafficPolicyDocumentEndpointOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentEndpoint) string { return v.Id }).(pulumi.StringOutput)\n}", "func (t *Task) ID() string {\n\treturn t.id\n}", "func (pkt *SubAddRequest) ID() int {\n\treturn PacketSubAddRequest\n}", "func (o NetworkOutput) QosPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Network) pulumi.StringOutput { return v.QosPolicyId }).(pulumi.StringOutput)\n}", "func GetPlanID(userCount int) string {\n\tswitch {\n\tcase userCount == 0:\n\t\treturn GetPlan(Free).ID\n\tcase userCount == 1:\n\t\treturn GetPlan(Solo).ID\n\tdefault:\n\t\treturn GetPlan(General).ID\n\t}\n}", "func (o *SparseSSHAuthorizationPolicy) Identifier() string {\n\n\tif o.ID == nil {\n\t\treturn \"\"\n\t}\n\treturn *o.ID\n}", "func (r *Distribution) WebAclId() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"webAclId\"])\n}", "func (pkt *SubModRequest) ID() int {\n\treturn PacketSubModRequest\n}", "func (r *Request) ID() string { return string(r.id) }", "func (r *Request) ID() string { return string(r.id) }", "func (o GetVolumeGroupSapHanaVolumeDataProtectionSnapshotPolicyOutput) SnapshotPolicyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVolumeGroupSapHanaVolumeDataProtectionSnapshotPolicy) string { return v.SnapshotPolicyId }).(pulumi.StringOutput)\n}", "func (b *ApprovalWorkflowProviderPolicyTemplatesCollectionRequestBuilder) ID(id string) *GovernancePolicyTemplateRequestBuilder {\n\tbb := &GovernancePolicyTemplateRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}\n\tbb.baseURL += \"/\" + id\n\treturn bb\n}", "func (o *CreateReservationTimeSliceModel) GetRatePlanId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.RatePlanId\n}", "func (pkt *SubDelRequest) ID() int {\n\treturn PacketSubDelRequest\n}", "func (r *TopicRule) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o ResourcePolicyInstanceSchedulePolicyScheduleResponseOutput) Schedule() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResourcePolicyInstanceSchedulePolicyScheduleResponse) string { return v.Schedule }).(pulumi.StringOutput)\n}", "func (o ConfigurationBackupSchedulePolicyPtrOutput) SchedulePolicyType() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ConfigurationBackupSchedulePolicy) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SchedulePolicyType\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *VNFThresholdPolicy) Identifier() string {\n\n\treturn o.ID\n}", "func (c *controller) CreatePolicy(ctx context.Context, schema *policyModels.Schema) (id int64, err error) {\n\tif schema == nil {\n\t\treturn 0, errors.New(\"nil policy schema provided\")\n\t}\n\n\t// Update timestamps\n\tnow := time.Now()\n\tschema.CreatedAt = now\n\tschema.UpdatedTime = now\n\n\t// Get full model of policy schema\n\terr = schema.Decode()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// valid policy schema\n\terr = schema.ValidatePreheatPolicy()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tid, err = c.pManager.Create(ctx, schema)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tschema.ID = id\n\n\tif schema.Trigger != nil &&\n\t\tschema.Trigger.Type == policyModels.TriggerTypeScheduled &&\n\t\tlen(schema.Trigger.Settings.Cron) > 0 {\n\t\t// schedule and update policy\n\t\textras := make(map[string]interface{})\n\t\tif _, err = c.scheduler.Schedule(ctx, job.P2PPreheatVendorType, id, \"\", schema.Trigger.Settings.Cron,\n\t\t\tSchedulerCallback, TriggerParam{PolicyID: id}, extras); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif err = schema.Encode(); err == nil {\n\t\t\terr = c.pManager.Update(ctx, schema, \"trigger\")\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif e := c.scheduler.UnScheduleByVendor(ctx, job.P2PPreheatVendorType, id); e != nil {\n\t\t\t\treturn 0, errors.Wrap(e, err.Error())\n\t\t\t}\n\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\treturn\n}", "func (m *UnifiedRoleAssignmentScheduleRequest) GetAppScopeId()(*string) {\n return m.appScopeId\n}", "func (a *Pipeline) ID() PipelineID {\n\treturn PipelineID(a.Service.ID())\n}", "func (w *W) ID() string {\n\treturn w.Config.URL\n}", "func (v *Validator) ID() uint32 {\n\tif v.id == 0 {\n\t\tv.id = keys.PublicKeyID(&v.Key.PublicKey)\n\t}\n\treturn v.id\n}" ]
[ "0.6260987", "0.6210173", "0.61886704", "0.6113732", "0.6055413", "0.60344696", "0.59402114", "0.58527046", "0.5847763", "0.58081985", "0.5807119", "0.5807077", "0.57898337", "0.5768478", "0.5742225", "0.56864387", "0.5664078", "0.5663449", "0.565793", "0.5621334", "0.5612016", "0.55971307", "0.5595503", "0.5589208", "0.55702984", "0.5562903", "0.55578244", "0.55235726", "0.5495308", "0.54780567", "0.5460475", "0.54373217", "0.542105", "0.54107195", "0.5379831", "0.53593457", "0.53553176", "0.53420156", "0.5341681", "0.534019", "0.53278226", "0.5318843", "0.53123206", "0.5295756", "0.5277963", "0.52765316", "0.5267", "0.5241755", "0.5241307", "0.52362895", "0.5209775", "0.5201771", "0.52005965", "0.51984537", "0.5198263", "0.51981324", "0.5172609", "0.51724315", "0.5172206", "0.51708615", "0.51703197", "0.51629233", "0.5162666", "0.5152718", "0.51456606", "0.5140271", "0.51391524", "0.5131218", "0.5130155", "0.51136035", "0.5113538", "0.5113449", "0.510812", "0.5104233", "0.5103731", "0.5079037", "0.5066863", "0.50652903", "0.5058342", "0.50558233", "0.503747", "0.5036796", "0.5026747", "0.5025981", "0.5023775", "0.50181097", "0.50181097", "0.5014928", "0.50138223", "0.50106853", "0.50035036", "0.5000956", "0.49957493", "0.49947205", "0.4994563", "0.49774927", "0.4971275", "0.49683613", "0.4967823", "0.4965496" ]
0.56604415
18
getHTTPRecoder creates a new httpClient that records all HTTP requests in a cassette. This cassette is then replayed whenever tests are executed again. This means that once the requests are recorded in the cassette, no more real HTTP request must be made to run the tests. It is important to call add a `defer cleanup()` so the given cassette files are correctly closed and saved after the requests.
func getHTTPRecoder(t *testing.T, update bool) (client *http.Client, cleanup func(), err error) { recorderMode := recorder.ModeReplaying if update { recorderMode = recorder.ModeRecording } // Setup recorder and scw client r, err := recorder.NewAsMode(getTestFilePath(t, ".cassette"), recorderMode, &SocketPassthroughTransport{}) if err != nil { return nil, nil, err } // Add a filter which removes Authorization headers from all requests: r.AddFilter(cassetteRequestFilter) // Remove secrets from response r.AddSaveFilter(cassetteResponseFilter) r.SetMatcher(cassetteMatcher) return &http.Client{Transport: &retryableHTTPTransport{transport: r}}, func() { assert.NoError(t, r.Stop()) // Make sure recorder is stopped once done with it }, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetHTTPClient() *http.Client { return httpClientPool.Get().(*http.Client) }", "func TracedHTTPClient(timeout time.Duration) *http.Client {\n\tot := project.DefaultHTTPTransport()\n\treturn &http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: &withInjectedDataRoundTripper{ot},\n\t}\n}", "func httpGet(ctx context.Context, path, trustedCAFile string, headers map[string]string) (io.ReadCloser, error) {\n\tclient := &http.Client{}\n\n\tif trustedCAFile != \"\" {\n\t\trootCAs, err := x509.SystemCertPool()\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"failed to retrieve system cert pool\")\n\t\t}\n\t\tif rootCAs == nil {\n\t\t\trootCAs = x509.NewCertPool()\n\t\t}\n\n\t\tcerts, err := ioutil.ReadFile(trustedCAFile)\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Errorf(\"failed to read trusted CA file: %s\", trustedCAFile)\n\t\t}\n\n\t\tif ok := rootCAs.AppendCertsFromPEM(certs); !ok {\n\t\t\tlogger.Errorf(\"failed to append %s to RootCAs, using system certs only\", trustedCAFile)\n\t\t}\n\n\t\tappendCerts(rootCAs)\n\n\t\tclient = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tRootCAs: rootCAs,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching asset: %s\", err)\n\t}\n\treq = req.WithContext(ctx)\n\n\tfor k, v := range headers {\n\t\tvalues := strings.Split(v, \",\")\n\t\tfor _, value := range values {\n\t\t\treq.Header.Add(k, strings.TrimSpace(value))\n\t\t}\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error fetching asset: %s\", err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"error fetching asset: Response Code %d\", resp.StatusCode)\n\t}\n\n\treturn resp.Body, nil\n}", "func (t *cassetteTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\tfilename := t.directory + \"/\" + t.cassette\n\tif _, e := os.Stat(filename + \".resp\"); e == nil {\n\t\tcontent, _ := ioutil.ReadFile(filename + \".resp\")\n\t\tvar resp http.Response\n\t\tjson.Unmarshal(content, &resp)\n\n\t\t// and the body\n\t\tresp.Body, _ = os.Open(filename + \".body\")\n\n\t\t// check for the error too\n\t\tvar err error = nil\n\t\tif _, e = os.Stat(filename + \".err\"); err == nil {\n\t\t\tcontent, _ := ioutil.ReadFile(filename + \".err\")\n\n\t\t\tjson.Unmarshal(content, &err)\n\t\t}\n\n\t\treturn &resp, err\n\t}\n\n\t// need to fetch the data from the web, so use the default transport\n\tresp, err := http.DefaultClient.Do(req)\n\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\t// save the cassette to disk\n\tj, _ := json.Marshal(resp)\n\tioutil.WriteFile(filename+\".resp\", j, 0644)\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tioutil.WriteFile(filename+\".body\", body, 0644)\n\tresp.Body, _ = os.Open(filename + \".body\")\n\n\tif err != nil {\n\t\tj, _ = json.Marshal(err)\n\t\tioutil.WriteFile(filename+\".err\", j, 0644)\n\t}\n\n\treturn resp, err\n}", "func InitHTTPClient(tracer opentracing.Tracer) {\n\thttpClient = http.NewRequests(tracer)\n}", "func NewHTTPClient(tc *trace.Client, orig *http.Client) *HTTPClient {\n\tif orig == nil {\n\t\torig = http.DefaultClient\n\t}\n\trt := orig.Transport\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\tclient := http.Client{\n\t\tTransport: &tracerTransport{base: rt},\n\t\tCheckRedirect: orig.CheckRedirect,\n\t\tJar: orig.Jar,\n\t\tTimeout: orig.Timeout,\n\t}\n\treturn &HTTPClient{\n\t\tClient: client,\n\t\ttc: tc,\n\t}\n}", "func testHttpClient() *http.Client {\n\treturn &http.Client{\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n}", "func CreateMockHTTPClient(b []byte, statusCode int) *mock.HTTPClient {\n\tr := ioutil.NopCloser(bytes.NewReader([]byte(b)))\n\tmockHTTPClient := &mock.HTTPClient{}\n\tmockHTTPClient.DoFn = func(*http.Request) (*http.Response, error) {\n\t\treturn &http.Response{\n\t\t\tStatusCode: statusCode,\n\t\t\tBody: r,\n\t\t}, nil\n\t}\n\treturn mockHTTPClient\n}", "func testHTTPClient() *http.Client {\n\treturn &http.Client{\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n}", "func GetHTTPClient() *http.Client {\r\n tlsConfig := &tls.Config {\r\n InsecureSkipVerify: true, //for this test, ignore ssl certificate\r\n }\r\n\r\n tr := &http.Transport{TLSClientConfig: tlsConfig}\r\n client := &http.Client{Transport: tr}\r\n\r\n return client\r\n}", "func CreateHTTPClient(handler http.Handler) (*http.Client, func()) {\n\ts := httptest.NewServer(handler)\n\n\tcli := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: func(_ context.Context, network, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(network, s.Listener.Addr().String())\n\t\t\t},\n\t\t},\n\t}\n\n\treturn cli, s.Close\n}", "func GetHTTPClient() *http.Client {\n tlsConfig := &tls.Config {\n InsecureSkipVerify: true, //for this test, ignore ssl certificate\n }\n\n tr := &http.Transport{TLSClientConfig: tlsConfig}\n client := &http.Client{Transport: tr}\n\n return client\n}", "func getHttpClient(f *File, timeout int) *http.Client {\n\tproxyUrl := http.ProxyFromEnvironment\n\tif f.Proxy != \"\" {\n\t\tproxy, _ := url.Parse(f.Proxy)\n\t\tproxyUrl = http.ProxyURL(proxy)\n\t}\n\ttr := &http.Transport{\n\t\tProxy: proxyUrl,\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: f.SkipVerify},\n\t}\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t}\n\treturn client\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 15,\n\t\t},\n\t\tTimeout: time.Duration(10) * time.Second,\n\t}\n\n\treturn client\n}", "func CreateHTTPSClient(handler http.Handler) (*http.Client, string, func()) {\n\n\tserver := httptest.NewTLSServer(handler)\n\n\tcert, err := x509.ParseCertificate(server.TLS.Certificates[0].Certificate[0])\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Could not parse certificate\")\n\t}\n\n\tcertpool := x509.NewCertPool()\n\tcertpool.AddCert(cert)\n\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: func(_ context.Context, network, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(network, server.Listener.Addr().String())\n\t\t\t},\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tRootCAs: certpool,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn client, server.URL, server.Close\n}", "func CtxHttpClient(src *Source) *http.Client {\n\tval := src.Context().Value(HttpClientContextKey)\n\tif val == nil {\n\t\treturn nil\n\t}\n\treturn val.(*http.Client)\n}", "func NewHTTPClient() *HTTPClient {\n\treturn &HTTPClient{\n\t\tClient: http.DefaultClient,\n\t\tCacheDir: viper.GetString(\"http_cache_dir\"),\n\t}\n}", "func HTTPClient() *http.Client {\n\tif httpClient == nil {\n\t\ttransport := &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\n\t\thttpClient = &http.Client{Transport: transport}\n\t}\n\treturn httpClient\n}", "func NewHTTPClient() *http.Client {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true, //nolint:gosec // Needs to be enabled in suites. Not used in production.\n\t\t},\n\t}\n\n\treturn &http.Client{\n\t\tTransport: tr,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n}", "func FetchFileCABundleCertHTTP() types.Test {\n\tname := \"tls.fetchfile.http.cabundle\"\n\tin := types.GetBaseDisk()\n\tout := types.GetBaseDisk()\n\tconfig := fmt.Sprintf(`{\n\t\t\"ignition\": {\n\t\t\t\"version\": \"$version\",\n\t\t\t\"security\": {\n\t\t\t\t\"tls\": {\n\t\t\t\t\t\"certificateAuthorities\": [{\n\t\t\t\t\t\t\"source\": \"http://127.0.0.1:8080/certificates\"\n\t\t\t\t\t}]\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"storage\": {\n\t\t\t\"files\": [{\n\t\t\t\t\"path\": \"/foo/bar\",\n\t\t\t\t\"contents\": {\n\t\t\t\t\t\"source\": %q\n\t\t\t\t}\n\t\t\t},{\n\t\t\t\t\"path\": \"/foo/bar2\",\n\t\t\t\t\"contents\": {\n\t\t\t\t\t\"source\": %q\n\t\t\t\t}\n\t\t\t}]\n\t\t}\n\t}`, customCAServer.URL, customCAServer2.URL)\n\tconfigMinVersion := \"3.0.0\"\n\n\treturn types.Test{\n\t\tName: name,\n\t\tIn: in,\n\t\tOut: out,\n\t\tConfig: config,\n\t\tConfigMinVersion: configMinVersion,\n\t}\n}", "func NewResourceManager(g func(ctx context.Context) (*grpc.ClientConn, error)) *ResourceManager {\n\treturn &ResourceManager{g}\n}", "func New(CABundleFile, CABundleDir string, httpTimeout time.Duration) (*http.Client, error) {\n\treturn _new(CABundleFile, CABundleDir, httpTimeout, \"\")\n}", "func NewHTTP(config HTTPConfig, defaultWP WriteParams) (*httpClient, error) {\n\t// validate required parameters:\n\tif len(config.URL) == 0 {\n\t\treturn nil, fmt.Errorf(\"config.URL is required to create an HTTP client\")\n\t}\n\tif len(defaultWP.Database) == 0 {\n\t\treturn nil, fmt.Errorf(\"A default database is required to create an HTTP client\")\n\t}\n\n\t// set defaults:\n\tif config.Timeout == 0 {\n\t\tconfig.Timeout = defaultRequestTimeout\n\t}\n\tif config.MaxIdleConnsPerHost == 0 {\n\t\tconfig.MaxIdleConnsPerHost = defaultMaxIdleConnsPerHost\n\t}\n\t// parse URL:\n\tu, err := url.Parse(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing config.URL: %s\", err)\n\t}\n\tif u.Scheme != \"http\" && u.Scheme != \"https\" {\n\t\treturn nil, fmt.Errorf(\"config.URL scheme must be http(s), got %s\", u.Scheme)\n\t}\n\n\tvar transport http.Transport\n\tif len(config.HTTPProxy) > 0 {\n\t\tproxyURL, err := url.Parse(config.HTTPProxy)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing config.HTTPProxy: %s\", err)\n\t\t}\n\n\t\ttransport = http.Transport{\n\t\t\tProxy: http.ProxyURL(proxyURL),\n\t\t\tMaxIdleConnsPerHost: config.MaxIdleConnsPerHost,\n\t\t}\n\t} else {\n\t\ttransport = http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tMaxIdleConnsPerHost: config.MaxIdleConnsPerHost,\n\t\t}\n\t}\n\n\treturn &httpClient{\n\t\twriteURL: writeURL(u, defaultWP),\n\t\tconfig: config,\n\t\turl: u,\n\t\tclient: &http.Client{\n\t\t\tTimeout: config.Timeout,\n\t\t\tTransport: &transport,\n\t\t},\n\t}, nil\n}", "func createHTTPClient() *http.Client {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConnsPerHost: 1,\n\t\tDisableKeepAlives: true,\n\t}\n\n\treturn &http.Client{\n\t\tTransport: tr,\n\t\tTimeout: time.Second * 60,\n\t}\n}", "func setup() (client *Client, mux *http.ServeMux, serverURL string, destructor func()) {\n\n\tmux = http.NewServeMux()\n\n\tapiHandler := http.NewServeMux()\n\tapiHandler.Handle(baseURLPath + \"/\", http.StripPrefix(baseURLPath, mux))\n\tapiHandler.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tfmt.Println(\"FAIL: Client.BaseURL path prefix is not in the request URL:\")\n\t\tfmt.Println(req.URL.String())\n\t\tfmt.Println(\"Use a relative endpoint URL\")\n\t\thttp.Error(w, \"BaseURL path prefix: \" + baseURLPath + \" not in request URL\", http.StatusInternalServerError)\n\t})\n\n\t// Test HTTP server used to provide mock API responses\n\tmockServer := httptest.NewServer(apiHandler)\n\n\t// Jira client being tested against the mock server\n\tclient, _ = NewClient(nil, mockServer.URL)\n\tmockServerURL, _ := url.Parse(mockServer.URL + baseURLPath + \"/\")\n\tclient.BaseURL = mockServerURL\n\n\treturn client, mux, mockServer.URL, mockServer.Close\n}", "func NewHTTPFetcher(requestTimeout time.Duration, requestMaxRetry int) *HTTPFetcher {\n\tif requestTimeout == 0 {\n\t\trequestTimeout = 5 * time.Second\n\t}\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\ttransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\treturn &HTTPFetcher{\n\t\tclient: &http.Client{\n\t\t\tTimeout: requestTimeout,\n\t\t},\n\t\tinsecureClient: &http.Client{\n\t\t\tTimeout: requestTimeout,\n\t\t\tTransport: transport,\n\t\t},\n\t\tinitialBackoff: time.Millisecond * 500,\n\t\trequestMaxRetry: requestMaxRetry,\n\t}\n}", "func NewHTTPClient(skipVerify bool, certPath string) (*http.Client, error) {\n\ttlsConfig := &tls.Config{\n\t\tInsecureSkipVerify: skipVerify,\n\t}\n\n\tif !skipVerify && certPath != \"\" {\n\t\tcert, err := os.ReadFile(certPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcertPool, err := x509.SystemCertPool()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"WARN: unable to get system cert pool: %v\\n\", err)\n\t\t\tcertPool = x509.NewCertPool()\n\t\t}\n\t\tcertPool.AppendCertsFromPEM(cert)\n\t\ttlsConfig.RootCAs = certPool\n\t}\n\n\treturn &http.Client{\n\t\tTimeout: 2 * time.Minute,\n\t\tTransport: &http.Transport{\n\t\t\tIdleConnTimeout: 2 * time.Minute,\n\t\t\tResponseHeaderTimeout: 2 * time.Minute,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}}, nil\n}", "func CreateHTTPClient(roundTripper func(*http.Request) (*http.Response, error)) *http.Client {\n\treturn &http.Client{\n\t\tTransport: roundTripperFunc(roundTripper),\n\t}\n}", "func httpClient() *http.Client {\n\tclient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\tr.URL.Opaque = r.URL.Path\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn &client\n}", "func HTTPClient() *http.Client {\n\treturn &http.Client{Timeout: 5 * time.Second}\n}", "func LoadFromHttp(source string) ([]byte, error) {\n\tvar resp *http.Response\n\n\tif !(strings.HasPrefix(source, \"http://\") || strings.HasPrefix(source, \"https://\")) {\n\t\treturn nil, WrongFormatError\n\t}\n\n\t// Create custom http transport\n\t// From: https://www.loginradius.com/blog/async/tune-the-go-http-client-for-high-performance/\n\thttpTransport := http.DefaultTransport.(*http.Transport).Clone()\n\thttpTransport.MaxIdleConns = 10\n\thttpTransport.MaxConnsPerHost = 10\n\thttpTransport.IdleConnTimeout = 60 * time.Second\n\thttpTransport.MaxIdleConnsPerHost = 10\n\thttpTransport.ResponseHeaderTimeout = httpResponseHeadersTimeout\n\n\t// Prepare request\n\tclient := http.Client{\n\t\tTransport: httpTransport,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", source, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Execute request\n\tctx, ctxCancel := context.WithTimeout(context.Background(), httpRequestTimeout)\n\tdefer ctxCancel()\n\tresp, err = client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check if the request succeeded\n\tif resp.StatusCode != 200 {\n\t\t_ = resp.Body.Close()\n\n\t\treturn nil, fmt.Errorf(\"unexpected HTTP status code [http-status=%v]\", resp.Status)\n\t}\n\n\t// Read response body\n\tvar responseBody []byte\n\tresponseBody, err = ioutil.ReadAll(resp.Body)\n\t_ = resp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Done\n\treturn responseBody, nil\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: MaxIdleConnections,\n\t\t},\n\t\tTimeout: time.Duration(RequestTimeout) * time.Second,\n\t}\n\n\treturn client\n}", "func newTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func newTestClient(fn roundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func NewHTTPClient(source Source) (*http.Client, error) {\n\tcerts, err := x509.SystemCertPool()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(source.CACerts) > 0 {\n\t\tfor i := range source.CACerts {\n\t\t\tcerts.AddCert(source.CACerts[i])\n\t\t}\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\tRootCAs: certs,\n\t\t\t},\n\t\t\tProxy: func(req *http.Request) (*url.URL, error) {\n\t\t\t\tif strings.TrimSpace(source.HTTPProxy) != \"\" {\n\t\t\t\t\tos.Setenv(\"HTTP_PROXY\", source.HTTPProxy)\n\t\t\t\t}\n\n\t\t\t\tif strings.TrimSpace(source.HTTPSProxy) != \"\" {\n\t\t\t\t\tos.Setenv(\"HTTPS_PROXY\", source.HTTPSProxy)\n\t\t\t\t}\n\n\t\t\t\tif strings.TrimSpace(source.NoProxy) != \"\" {\n\t\t\t\t\tos.Setenv(\"NO_PROXY\", source.NoProxy)\n\t\t\t\t}\n\n\t\t\t\treturn http.ProxyFromEnvironment(req)\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func NewHTTP() *HTTP {\n\treturn HTTPPool.Get().(*HTTP)\n}", "func RequestCapturingMockHttpClient(f RequestToResponse) (*http.Client, *http.Request) {\n\tvar capture http.Request\n\treturn &http.Client{\n\t\tTransport: RequestToResponse(func(req *http.Request) (*http.Response, error) {\n\t\t\tcapture = *req.Clone(req.Context())\n\t\t\treturn f(req)\n\t\t}),\n\t}, &capture\n}", "func NewInstrumentedHTTPClient(n string) *http.Client {\n\tc := http.Client{}\n\tInstrumentHTTPClient(&c, n)\n\treturn &c\n}", "func (o *CopyRecipeToMyRecipesWithChangesParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func GetHTTPClient() *http.Client {\n\t// Lazy initialize the HTTP client\n\tif httpClient == nil {\n\t\t// Initialize the default transport\n\t\tinitDefaultTransport()\n\n\t\toptions := &cookiejar.Options{\n\t\t\tPublicSuffixList: publicsuffix.List,\n\t\t}\n\n\t\tjar, err := cookiejar.New(options)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error creating new cookie jar: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\thttpClient = &http.Client{\n\t\t\tJar: jar,\n\t\t}\n\t}\n\n\treturn httpClient\n}", "func CreateMockHTTPClient(res ...http.Response) MockHTTPClient {\n\treturn MockHTTPClient{\n\t\tresponses: &res,\n\t}\n}", "func makeHTTPTestServer(t testing.TB, fnmc func(mc *config.MayaConfig)) *TestServer {\n\treturn makeHTTPTestServerWithWriter(t, nil, fnmc)\n}", "func MockHTTP() (*http.Client, *httpmock.MockTransport) {\n\tt := httpmock.NewMockTransport()\n\treturn &http.Client{Transport: t}, t\n}", "func testHTTPResponse(t *testing.T, r *httprouter.Router, req *nethttp.Request) *httptest.ResponseRecorder {\n\n\t// Create a response recorder\n\tw := httptest.NewRecorder()\n\n\t// Create the service and process the above request.\n\tr.ServeHTTP(w, req)\n\n\treturn w\n}", "func newHTTPReader(cli *http.Client) (*httpReader, error) {\n\tif cli == nil {\n\t\treturn nil, errInvalidClient\n\t}\n\treturn &httpReader{cli}, nil\n}", "func withCassette(cassetteName string, f func(*recorder.Recorder)) {\n\tr, err := recorder.New(cassetteName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer r.Stop()\n\n\tf(r)\n}", "func newHTTPClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: timeout,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\n\t\t\tTLSHandshakeTimeout: timeout,\n\t\t\tResponseHeaderTimeout: timeout,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\tMaxIdleConns: 5,\n\t\t\tIdleConnTimeout: 90 * time.Second,\n\t\t},\n\t}\n}", "func InstrumentHTTPClient(hc *http.Client, n string) {\n\tl := prometheus.Labels{\"controller\": n}\n\n\trt := reqTotal.MustCurryWith(l)\n\trif := reqInFlight.With(l)\n\trl := reqLatency.MustCurryWith(l)\n\trbl := reqEventsLatency.MustCurryWith(l)\n\n\ttrace := &promhttp.InstrumentTrace{\n\t\tDNSStart: func(t float64) {\n\t\t\trbl.WithLabelValues(\"dns_start\").Observe(t)\n\t\t},\n\t\tDNSDone: func(t float64) {\n\t\t\trbl.WithLabelValues(\"dns_end\").Observe(t)\n\t\t},\n\t\tConnectStart: func(t float64) {\n\t\t\trbl.WithLabelValues(\"connect_start\").Observe(t)\n\t\t},\n\t\tConnectDone: func(t float64) {\n\t\t\trbl.WithLabelValues(\"connect_end\").Observe(t)\n\t\t},\n\t\tTLSHandshakeStart: func(t float64) {\n\t\t\trbl.WithLabelValues(\"tls_start\").Observe(t)\n\t\t},\n\t\tTLSHandshakeDone: func(t float64) {\n\t\t\trbl.WithLabelValues(\"tls_end\").Observe(t)\n\t\t},\n\t\tGotFirstResponseByte: func(t float64) {\n\t\t\trbl.WithLabelValues(\"ttfb\").Observe(t)\n\t\t},\n\t}\n\n\thc.Transport = promhttp.InstrumentRoundTripperInFlight(rif,\n\t\tpromhttp.InstrumentRoundTripperCounter(rt,\n\t\t\tpromhttp.InstrumentRoundTripperTrace(trace,\n\t\t\t\tpromhttp.InstrumentRoundTripperDuration(rl, http.DefaultTransport),\n\t\t\t),\n\t\t),\n\t)\n}", "func NewHTTPClient(slog slog.Logger, filer sio.Filer) (clt Client, err error) {\n\thttpClt := &HTTPClient{logger: slog}\n\thttpClt.client = httpClt\n\thttpClt.filer = filer\n\treturn httpClt.client, nil\n}", "func GetHTTPClient() *http.Client {\n\tonce.Do(func() {\n\t\thttpClient = http.DefaultClient\n\t})\n\n\treturn httpClient\n}", "func TestHTTPResponse(t *testing.T, method, urlStr string, payload io.Reader) *httptest.ResponseRecorder {\n\treq, err := http.NewRequest(method, urlStr, payload)\n\tif err != nil {\n\t\tt.Fatalf(\"Unsuccessful %s on %q: %v\\n\", method, urlStr, err)\n\t}\n\tresp := httptest.NewRecorder()\n\tServeSingleHTTP(resp, req)\n\treturn resp\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\tv := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).DialContext,\n\t\tMaxIdleConns: 100,\n\t\tIdleConnTimeout: 90 * time.Second,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n\tv.RegisterProtocol(\"http\", transportFunc(doer))\n\treturn &http.Client{\n\t\tTransport: http.RoundTripper(v),\n\t}\n}", "func (f *fetcher) downloadHTTP(url, label string, out writeSyncer, etag string) (*cacheData, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toptions := make(http.Header)\n\t// Send credentials only over secure channel\n\tif req.URL.Scheme == \"https\" {\n\t\tif hostOpts, ok := f.headers[req.URL.Host]; ok {\n\t\t\toptions = hostOpts.Header()\n\t\t}\n\t}\n\tfor k, v := range options {\n\t\tfor _, e := range v {\n\t\t\treq.Header.Add(k, e)\n\t\t}\n\t}\n\ttransport := http.DefaultTransport\n\tif f.insecureSkipVerify {\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t}\n\t}\n\tif etag != \"\" {\n\t\treq.Header.Add(\"If-None-Match\", etag)\n\t}\n\treq.Header.Add(\"User-Agent\", fmt.Sprintf(\"rkt/%s\", version.Version))\n\n\tclient := &http.Client{Transport: transport}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tcd := &cacheData{}\n\t// TODO(jonboulle): handle http more robustly (redirects?)\n\tswitch res.StatusCode {\n\tcase http.StatusAccepted:\n\t\t// If the server returns Status Accepted (HTTP 202), we should retry\n\t\t// downloading the signature later.\n\t\treturn nil, errStatusAccepted\n\tcase http.StatusOK:\n\t\tfallthrough\n\tcase http.StatusNotModified:\n\t\tcd.etag = res.Header.Get(\"ETag\")\n\t\tcd.maxAge = getMaxAge(res.Header.Get(\"Cache-Control\"))\n\t\tcd.useCached = (res.StatusCode == http.StatusNotModified)\n\t\tif cd.useCached {\n\t\t\treturn cd, nil\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"bad HTTP status code: %d\", res.StatusCode)\n\t}\n\n\tprefix := \"Downloading \" + label\n\tfmtBytesSize := 18\n\tbarSize := int64(80 - len(prefix) - fmtBytesSize)\n\tbar := ioprogress.DrawTextFormatBar(barSize)\n\tfmtfunc := func(progress, total int64) string {\n\t\t// Content-Length is set to -1 when unknown.\n\t\tif total == -1 {\n\t\t\treturn fmt.Sprintf(\n\t\t\t\t\"%s: %v of an unknown total size\",\n\t\t\t\tprefix,\n\t\t\t\tioprogress.ByteUnitStr(progress),\n\t\t\t)\n\t\t}\n\t\treturn fmt.Sprintf(\n\t\t\t\"%s: %s %s\",\n\t\t\tprefix,\n\t\t\tbar(progress, total),\n\t\t\tioprogress.DrawTextFormatBytes(progress, total),\n\t\t)\n\t}\n\n\treader := &ioprogress.Reader{\n\t\tReader: res.Body,\n\t\tSize: res.ContentLength,\n\t\tDrawFunc: ioprogress.DrawTerminalf(os.Stdout, fmtfunc),\n\t\tDrawInterval: time.Second,\n\t}\n\n\tif _, err := io.Copy(out, reader); err != nil {\n\t\treturn nil, fmt.Errorf(\"error copying %s: %v\", label, err)\n\t}\n\n\tif err := out.Sync(); err != nil {\n\t\treturn nil, fmt.Errorf(\"error writing %s: %v\", label, err)\n\t}\n\n\treturn cd, nil\n}", "func newHTTPClient(count int) *client {\n\treturn &client{\n\t\tcli: &http.Client{\n\t\t\tTimeout: time.Second * 5,\n\t\t},\n\t\tworkers: count,\n\t\t//can be different size\n\t\terrChan: make(chan error, count),\n\t\tseen: make(map[int]struct{}),\n\t\tpath: \"http://host.docker.internal:9010/objects/\",\n\t}\n}", "func CreateHTTPClient(requestURL string) (*Client, error) {\n\t_, err := url.ParseRequestURI(requestURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: time.Duration(requestTimeout) * time.Second,\n\t\t},\n\t\tbaseURL: requestURL,\n\t}, nil\n}", "func getCABundleTransport() *http.Transport {\n\treturn &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: 30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t}\n}", "func (s *server) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\t// Get request and response from the pool.\n\n\treq := s.requestPool.Get().(*Request)\n\tres := s.responsePool.Get().(*Response)\n\n\t// Tie the request body and the standard request body together.\n\n\tr.Body = &requestBody{\n\t\tr: req,\n\t\thr: r,\n\t\trc: r.Body,\n\t}\n\n\t// Reset the request.\n\n\treq.Air = s.a\n\treq.SetHTTPRequest(r)\n\treq.res = res\n\treq.params = req.params[:0]\n\treq.routeParamNames = nil\n\treq.routeParamValues = nil\n\treq.parseRouteParamsOnce = &sync.Once{}\n\treq.parseOtherParamsOnce = &sync.Once{}\n\tfor key := range req.values {\n\t\tdelete(req.values, key)\n\t}\n\n\treq.localizedString = nil\n\n\t// Reset the response.\n\n\tres.Air = s.a\n\tres.SetHTTPResponseWriter(&responseWriter{\n\t\tr: res,\n\t\trw: rw,\n\t})\n\tres.Status = http.StatusOK\n\tres.ContentLength = -1\n\tres.Written = false\n\tres.Minified = false\n\tres.Gzipped = false\n\tres.req = req\n\tres.ohrw = rw\n\tres.servingContent = false\n\tres.serveContentError = nil\n\tres.reverseProxying = false\n\tres.deferredFuncs = res.deferredFuncs[:0]\n\n\t// Chain the gases stack.\n\n\th := func(req *Request, res *Response) error {\n\t\th := s.a.router.route(req)\n\t\tfor i := len(s.a.Gases) - 1; i >= 0; i-- {\n\t\t\th = s.a.Gases[i](h)\n\t\t}\n\n\t\treturn h(req, res)\n\t}\n\n\t// Chain the pregases stack.\n\n\tfor i := len(s.a.Pregases) - 1; i >= 0; i-- {\n\t\th = s.a.Pregases[i](h)\n\t}\n\n\t// Execute the chain.\n\n\tif err := h(req, res); err != nil {\n\t\tif !res.Written && res.Status < http.StatusBadRequest {\n\t\t\tres.Status = http.StatusInternalServerError\n\t\t}\n\n\t\ts.a.ErrorHandler(err, req, res)\n\t}\n\n\t// Execute the deferred functions.\n\n\tfor i := len(res.deferredFuncs) - 1; i >= 0; i-- {\n\t\tres.deferredFuncs[i]()\n\t}\n\n\t// Put the route param values back to the pool.\n\n\tif req.routeParamValues != nil {\n\t\ts.a.router.routeParamValuesPool.Put(req.routeParamValues)\n\t}\n\n\t// Put the request and response back to the pool.\n\n\ts.requestPool.Put(req)\n\ts.responsePool.Put(res)\n}", "func NewHTTPClient(options ...Opt) *HTTP {\n\tc := &HTTP{\n\t\tHTTPClient: &http.Client{},\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tif c.latestManifestURLFmt == \"\" {\n\t\tc.latestManifestURLFmt = defaultLatestManifestURLFmt\n\t}\n\n\tif c.manifestURLFmt == \"\" {\n\t\tc.manifestURLFmt = defaultManifestURLFmt\n\t}\n\n\treturn c\n}", "func (o *GetDeploymentByIDV3UsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func newHTTPClient(\n\tapiKey string,\n\tdebug bool,\n\tomitRetry bool,\n\ttimeout time.Duration,\n\ttransport http.RoundTripper,\n) httpC {\n\tif transport == nil {\n\t\ttransport = http.DefaultTransport\n\t}\n\treturn &gcmHTTP{\n\t\tGCMURL: httpAddress,\n\t\tapiKey: apiKey,\n\t\thttpClient: &http.Client{\n\t\t\tTransport: transport,\n\t\t\tTimeout: timeout,\n\t\t},\n\t\tdebug: debug,\n\t\tomitRetry: omitRetry,\n\t}\n}", "func (c *Client) httpClient() *http.Client { return http.DefaultClient }", "func (lm LinksManager) HTTPClient() *http.Client {\n\treturn lm.Client\n}", "func SetHTTPClient(newClient *http.Client) {\n\thttpClient = newClient\n}", "func (backend *Backend) HTTPClient() *http.Client {\n\treturn backend.httpClient\n}", "func (di *Dispatcher) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tvar response definition.Response\n\tmRequest := di.Translator.BuildRequestDefinitionFromHTTP(req)\n\n\tif mRequest.Path == \"/favicon.ico\" {\n\t\treturn\n\t}\n\n\tlogging.Printf(\"New request: %s %s\\n\", req.Method, req.URL.String())\n\tresult := definition.Result{}\n\tmock, errs := di.Router.Route(&mRequest)\n\tif errs == nil {\n\t\tresult.Found = true\n\t} else {\n\t\tresult.Found = false\n\t\tresult.Errors = errs\n\t}\n\n\tlogging.Printf(\"Mock match found: %s. Name : %s\\n\", strconv.FormatBool(result.Found), mock.Name)\n\n\tif result.Found {\n\t\tif len(mock.Control.ProxyBaseURL) > 0 {\n\t\t\tpr := proxy.Proxy{URL: mock.Control.ProxyBaseURL}\n\t\t\tresponse = pr.MakeRequest(mock.Request)\n\t\t} else {\n\n\t\t\tdi.VarsProcessor.Eval(&mRequest, mock)\n\n\t\t\tif !reflect.DeepEqual(definition.Notify{}, mock.Notify) {\n\t\t\t\tgo di.Notifier.Notify(mock)\n\t\t\t}\n\n\t\t\tif mock.Control.Crazy {\n\t\t\t\tlogging.Printf(\"Running crazy mode\")\n\t\t\t\tmock.Response.StatusCode = di.randomStatusCode(mock.Response.StatusCode)\n\t\t\t}\n\t\t\tif mock.Control.Delay > 0 {\n\t\t\t\tlogging.Printf(\"Adding a delay\")\n\t\t\t\ttime.Sleep(time.Duration(mock.Control.Delay) * time.Second)\n\t\t\t}\n\t\t\tresponse = mock.Response\n\t\t}\n\n\t} else {\n\t\tresponse = mock.Response\n\t}\n\n\t//translate request\n\tdi.Translator.WriteHTTPResponseFromDefinition(&response, w)\n\n\t//log to console\n\tm := definition.Match{Request: mRequest, Response: response, Result: result, Persist: mock.Persist}\n\tgo di.recordMatchData(m)\n}", "func getHTTPClient(options RegistryOptions) *http.Client {\n\n\toverriddenTimeout := httpRequestResponseTimeout\n\ttimeout := options.HTTPTimeout\n\t//if value is invalid or unspecified, the default will be used\n\tif timeout != nil && *timeout > 0 {\n\t\t//convert timeout to seconds\n\t\toverriddenTimeout = time.Duration(*timeout) * time.Second\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tResponseHeaderTimeout: overriddenTimeout,\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: options.SkipTLSVerify},\n\t\t},\n\t\tTimeout: overriddenTimeout,\n\t}\n}", "func NewFetchHTTP(tr http.RoundTripper) esitag.ResourceHandler {\n\tf := &fetchHTTP{\n\t\tclient: &http.Client{\n\t\t\tTransport: tr,\n\t\t\tTimeout: esitag.DefaultTimeOut,\n\t\t},\n\t}\n\treturn f\n}", "func getHttp(url url.URL) (io.ReadCloser, error) {\n\tresp, err := http.Get(url.String())\n\tif err != nil {\n\t\tlog.Printf(\"HTTP failed to GET url=%s. error=%s\\n\", url.String(), err)\n\t\treturn nil, err\n\t}\n\n\treturn resp.Body, nil\n}", "func NewHTTP(port uint16, pachClientFactory func(ctx context.Context) *client.APIClient) *HTTP {\n\tmux := http.NewServeMux()\n\thandler := &Server{\n\t\tpachClientFactory: pachClientFactory,\n\t}\n\tmux.Handle(\"/archive/\", CSRFWrapper(handler))\n\tmux.Handle(\"/healthz\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"healthy\\n\")) //nolint:errcheck\n\t}))\n\treturn &HTTP{\n\t\tmux: mux,\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\t\tHandler: mux,\n\t\t},\n\t}\n}", "func NewHTTPFetcher(ctx context.Context, logger *logr.Logger, reqTimeout time.Duration) Fetcher {\n\treturn &httpFetcher{\n\t\tctx,\n\t\tlogger,\n\t\t&http.Client{Timeout: reqTimeout},\n\t}\n}", "func HTTPGet(ctx context.Context, config HTTPGetConfig) (out HTTPGetResult) {\n\taddresses := strings.Join(config.Addresses, \" \")\n\tif addresses == \"\" {\n\t\t// TODO(bassosimone): what to do in this case? We clearly\n\t\t// cannot fill the DNS cache...\n\t\treturn\n\t}\n\ttarget := config.TargetURL.String()\n\tconfig.Session.Logger().Infof(\"GET %s...\", target)\n\tdomain := config.TargetURL.Hostname()\n\tresult, err := urlgetter.Getter{\n\t\tConfig: urlgetter.Config{\n\t\t\tDNSCache: fmt.Sprintf(\"%s %s\", domain, addresses),\n\t\t},\n\t\tSession: config.Session,\n\t\tTarget: target,\n\t}.Get(ctx)\n\tconfig.Session.Logger().Infof(\"GET %s... %+v\", target, err)\n\tout.Failure = result.Failure\n\tout.TestKeys = result\n\treturn\n}", "func makeHTTPRequest(requestURL string, t *testing.T) *http.Request {\n\tdummyReader, _ := io.Pipe()\n\tr, err := http.NewRequest(\"GET\", requestURL, dummyReader)\n\tassert.Nil(t, err)\n\treturn r\n}", "func NewhttpClientMock(valid bool) *HTTPClientMock {\n\treturn &HTTPClientMock{\n\t\tapiKeyPublic: \"apiKeyPublic\",\n\t\tapiKeyPrivate: \"apiKeyPrivate\",\n\t\tclient: http.DefaultClient,\n\t\tvalidCreds: valid,\n\t\tfx: fixtures.New(),\n\t\tCallFunc: func() (int, int, error) {\n\t\t\tif valid == true {\n\t\t\t\treturn 1, 1, nil\n\t\t\t}\n\t\t\treturn 0, 0, errors.New(\"Unexpected error: Unexpected server response code: 401: EOF\")\n\t\t},\n\t\tSendMailV31Func: func(req *http.Request) (*http.Response, error) {\n\t\t\treturn nil, errors.New(\"mock send mail function not implemented yet\")\n\t\t},\n\t}\n}", "func SetHTTPClient(client *http.Client) {\n\thttpClient = client\n}", "func getHTTP(uri string, sslVerify bool, timeout time.Duration) (io.ReadCloser, error) {\n\ttr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: !sslVerify}}\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t\tTransport: tr,\n\t\tCheckRedirect: redirectPolicyFunc,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", uri, nil)\n\treq.Header.Add(\"Authorization\", \"Basic \"+globalBasicAuthString)\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !(resp.StatusCode >= 200 && resp.StatusCode < 300) {\n\t\tresp.Body.Close()\n\t\treturn nil, fmt.Errorf(\"HTTP status %d\", resp.StatusCode)\n\t}\n\treturn resp.Body, nil\n}", "func NewHTTPClient() *http.Client {\n\n\ttr := &http.Transport{\n\t\t//TLSClientConfig: &tls.Config{\n\t\t//\tInsecureSkipVerify: conf.InsecureSkipVerify,\n\t\t//},\n\t\tMaxIdleConnsPerHost: DefaultMaxIdleConnsPerHost,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: DefaultTimeout,\n\t\t\tKeepAlive: DefaultKeepAlive,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: DefaultTimeout,\n\t}\n\n\treturn &http.Client{\n\t\tTimeout: DefaultTimeout,\n\t\tTransport: tr,\n\t}\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{}\n\tif insecure {\n\t\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\treturn client\n}", "func DoHttpRequest(method string, requrl string, contentType string, body io.Reader, token string, subjecttoken string) (data []byte, statusCode int, header http.Header, err error) {\n\n\treq, err := http.NewRequest(method, requrl, body)\n\tif err != nil {\n\t\treturn nil, 500, nil, err\n\t}\n\n\treq.Header.Set(\"Content-Type\", contentType)\n\n\trequestURL, err := url.Parse(requrl)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestHost := requestURL.Host\n\n\tvar httpClient *http.Client\n\tc, ok := GetConnection(requrl)\n\tif ok { // The connection existing in cache\n\t\thttpClient = c\n\t} else { //Have to create a new connection\n\t\thttpClient, err = NewConnection(requestURL.Scheme + \"://\" + requestHost)\n\t\tif err != nil {\n\t\t\treturn nil, 500, nil, err\n\t\t}\n\t}\n\n\tresp, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\thttpClient, err = NewConnection(requestURL.Scheme + \"://\" + requestHost)\n\t\tif err != nil { //Try to refresh the cache and try again in case the error caused by the cache incorrect\n\t\t\treturn nil, 500, nil, err\n\t\t}\n\t\tresp, err = httpClient.Do(req)\n\t\tif err != nil { //Try to refresh the cache and try again in case the error caused by the cache incorrect\n\t\t\treturn nil, 500, nil, err\n\t\t}\n\t}\n\n\tdata, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, 500, nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\treturn data, resp.StatusCode, resp.Header, nil\n}", "func (o *PostReconciliationParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func (o *AutoscaleStopInstancesByCrnParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func NewClient(httpClient *http.Client) *Client {\n\tif httpClient == nil {\n\t\thttpClient = http.DefaultClient\n\t}\n\tbaseURL, _ := url.Parse(baseURL)\n\n\tc := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}\n\tc.common.client = c\n\tc.RRSet = (*RRSetService)(&c.common)\n\tc.RData = (*RDataService)(&c.common)\n\n\treturn c\n}", "func initClient() *http.Client {\n\treturn &http.Client{\n\t\tTimeout: time.Duration(timeout) * time.Second,\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConns: 10,\n\t\t\tMaxIdleConnsPerHost: 10,\n\t\t\tMaxConnsPerHost: 10,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t},\n\t}\n}", "func (c *Client) HTTPClient() HTTPInterface {\n\treturn c.httpClient\n}", "func (c *Client) GetHTTPClient() *http.Client {\n\tif c.hc == nil {\n\t\tc.hc = &http.Client{\n\t\t\tTimeout: time.Second * 5,\n\t\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\t\tc.SetToken(req)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t}\n\t}\n\treturn c.hc\n}", "func HTTP(addr string) CacheFunc {\n\treturn func(in chan *Request) chan *Request {\n\n\t\tout := make(chan *Request)\n\n\t\tgo func() {\n\t\t\tfor req := range in {\n\t\t\t\tfname := addr + \"/\" + req.key() + FileExtension\n\n\t\t\t\tresponse, err := http.Get(fname)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// If we don't get a response from the server, return an error.\n\t\t\t\t\treq.errs = append(req.errs, fmt.Errorf(response.Status))\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif response.StatusCode != 200 { // Check if the status is 'ok'.\n\t\t\t\t\tif response.StatusCode == 404 {\n\t\t\t\t\t\t// If we get a \"not found\" error, pass the request on.\n\t\t\t\t\t\tout <- req\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If we get a different status, return an error.\n\t\t\t\t\t\treq.errs = append(req.errs, fmt.Errorf(response.Status))\n\t\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tb, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// We can't read the file.\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := req.resultPayload.UnmarshalBinary(b); err != nil {\n\t\t\t\t\t// There is some problem with the file.\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := response.Body.Close(); err != nil {\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Successfully retrieved the result. Now return it to the requester.\n\t\t\t\treq.returnChan <- req\n\t\t\t}\n\t\t}()\n\t\treturn out\n\t}\n}", "func NewHTTPGetLoader(client *http.Client) HTTPGetLoader {\n\treturn HTTPGetLoader{\n\t\tclient: client,\n\t}\n}", "func CenHttpRoute() (router *httprouter.Router) {\n\trouter = httprouter.New()\n\n\trouter.GET(\"/injured\", cenHandler.GetInjured)\n\n\treturn\n}", "func HTTPGet(url string, headers map[string]string, timeout ...time.Duration) ([]byte, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// custom headers\n\tif len(headers) != 0 {\n\t\tfor k, v := range headers {\n\t\t\treq.Header.Set(k, v)\n\t\t}\n\t}\n\n\t// custom timeout\n\tif len(timeout) > 0 {\n\t\thttpClient.Timeout = timeout[0]\n\t}\n\n\tresp, err := httpClient.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tio.Copy(ioutil.Discard, resp.Body)\n\n\t\treturn nil, fmt.Errorf(\"error http code: %d\", resp.StatusCode)\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}", "func (c *Client) doHTTP(path string, method string, reader io.Reader) (resp *http.Response, err error) {\n\treturn nil, nil\n}", "func (o *GetContentSourceUsingGETParams) SetHTTPClient(client *http.Client) {\n\to.HTTPClient = client\n}", "func NewHTTPClient(retries int) HTTPClient {\n\tif retries <= 0 {\n\t\tpanic(\"retries should be greater than 0\")\n\t}\n\treturn &httpClient{\n\t\tretries: retries,\n\t}\n}", "func GetHttpClient(sdkConfig *SdkConfig) *http.Client {\n\n\tif sdkConfig.SkipVerify {\n\t\tlog.Println(\"[WARNING] Using SkipVerify for ignoring SSL certificate issues!\")\n\t\treturn &http.Client{Transport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ignore expired SSL certificates\n\t\t}}\n\t}\n\treturn http.DefaultClient\n}", "func GetCreateHttpHandler() http.HandlerFunc {\n\treturn allowCORS(\n\t\tvalidateReCaptcha(\n\t\t\tmiddleware.InputCreateCheck(\n\t\t\t\thttp.HandlerFunc(createHandler)),\n\t\t),\n\t\t\"*\")\n\n}", "func NewHTTPTester(addr, path string) *HTTPTester {\n\treturn &HTTPTester{\n\t\tclient: http.Client{},\n\t\turl: fmt.Sprintf(\"http://%s%s\", addr, path),\n\t}\n}", "func (am *authManager) GetHTTPClient(client kubernetes.Interface) *http.Client {\n\tclient, _ = am.getK8sClient(client)\n\tauthSettings := am.settingsManager.GetAuthSettings(client)\n\tif authSettings == nil || !authSettings.Enabled || (authSettings.RootCAFile == \"\" && authSettings.RootCA == \"\") {\n\t\tam.HttpClient = http.DefaultClient\n\t\tam.HttpClient.Timeout = time.Second * 30\n\t} else if authSettings.RootCAFile != am.CAPath || authSettings.RootCA != am.CACert {\n\t\tvar err error\n\t\tam.HttpClient, err = authApi.GetClient(authSettings.RootCAFile, authSettings.RootCA)\n\t\tif err != nil {\n\t\t\tam.HttpClient = http.DefaultClient\n\t\t\tlog.Println(\"Error getting HTTP client:\", err)\n\t\t} else {\n\t\t\tam.CAPath = authSettings.RootCAFile\n\t\t\tam.CACert = authSettings.RootCA\n\t\t}\n\t}\n\treturn am.HttpClient\n}", "func (cc *Client) HTTPClient() *http.Client {\n\treturn cc.httpClient\n}", "func init() {\n\tvar currentResp *http.Response\n\trequestHeaders := make(http.Header)\n\n\tRegisterSteps(func(c *Context) {\n\n\t\tc.Then(`^I should get an HTTP response code (\\d+) on path \"(.+?)\" through the tunnel \"(.+?)\"$`, func(expectedResponseCode int, path string, tunnelName string) {\n\t\t\ttunnel := c.GetTunnel(tunnelName)\n\t\t\tif tunnel == nil {\n\t\t\t\tc.Fail(\"Could not find a tunnel named '%s'\", tunnelName)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turl := fmt.Sprintf(\"http://%s:%v%s\", \"localhost\", tunnel.LocalPort, path)\n\t\t\tresp, err := c.execHttpGetRequest(url, requestHeaders)\n\t\t\tcurrentResp = resp\n\t\t\tif err != nil {\n\t\t\t\tc.Fail(\"HTTP request on %s failed: %v\", url, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassert.Equal(c.T, expectedResponseCode, resp.StatusCode)\n\t\t\tresp.Body.Close()\n\t\t})\n\n\t\tc.Then(`^This response has header \"(.+?)\" equals to \"(.+?)\"$`, func(name, expectedValue string) {\n\t\t\tassert.Equal(c.T, expectedValue, currentResp.Header.Get(name))\n\t\t})\n\n\t\tc.Then(`^This response has no header \"(.+?)\"$`, func(name string) {\n\t\t\tassert.NotContains(c.T, name, currentResp.Header)\n\t\t})\n\n\t\tc.Then(`^I should have the text \"(.+?)\" on path \"(.+?)\" through the tunnel \"(.+?)\"$`, func(expectedContentText string, path string, tunnelName string) {\n\t\t\ttunnel := c.GetTunnel(tunnelName)\n\t\t\tif tunnel == nil {\n\t\t\t\tc.Fail(\"Could not find a tunnel named '%s'\", tunnelName)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\turl := fmt.Sprintf(\"http://%s:%v%s\", \"localhost\", tunnel.LocalPort, path)\n\t\t\tresp, err := c.execHttpGetRequest(url, requestHeaders)\n\t\t\tif err != nil {\n\t\t\t\tc.Fail(\"HTTP request on %s failed: %v\", url, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata, err := ioutil.ReadAll(resp.Body)\n\n\t\t\tassert.Contains(c.T, string(data), expectedContentText)\n\t\t\tresp.Body.Close()\n\t\t})\n\n\t\tc.Given(`^Using request header \"(.+?)\": \"(.+?)\"$`, func(name, value string) {\n\t\t\tfor _, v := range strings.Split(value, \";\") {\n\t\t\t\trequestHeaders.Add(name, v)\n\t\t\t}\n\t\t})\n\n\t})\n}", "func NewHttpController(app usecases.Application, errQueue chan error) http.Handler {\n\treturn &httpController{\n\t\tapp: app,\n\t\terrQueue: errQueue,\n\t}\n}", "func (p *Probe) doHTTPRequest(req *http.Request, targetName string, result *probeResult, resultMu *sync.Mutex) {\n\n\tif len(p.requestBody) >= largeBodyThreshold {\n\t\treq = req.Clone(req.Context())\n\t\treq.Body = ioutil.NopCloser(bytes.NewReader(p.requestBody))\n\t}\n\n\tif p.c.GetKeepAlive() {\n\t\ttrace := &httptrace.ClientTrace{\n\t\t\tConnectDone: func(_, addr string, err error) {\n\t\t\t\tresult.connEvent++\n\t\t\t\tif err != nil {\n\t\t\t\t\tp.l.Warning(\"Error establishing a new connection to: \", addr, \". Err: \", err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tp.l.Info(\"Established a new connection to: \", addr)\n\t\t\t},\n\t\t}\n\t\treq = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))\n\t}\n\n\tstart := time.Now()\n\tresp, err := p.client.Do(req)\n\tlatency := time.Since(start)\n\n\tif resultMu != nil {\n\t\t// Note that we take lock on result object outside of the actual request.\n\t\tresultMu.Lock()\n\t\tdefer resultMu.Unlock()\n\t}\n\n\tresult.total++\n\n\tif err != nil {\n\t\tif isClientTimeout(err) {\n\t\t\tp.l.Warning(\"Target:\", targetName, \", URL:\", req.URL.String(), \", http.doHTTPRequest: timeout error: \", err.Error())\n\t\t\tresult.timeouts++\n\t\t\treturn\n\t\t}\n\t\tp.l.Warning(\"Target:\", targetName, \", URL:\", req.URL.String(), \", http.doHTTPRequest: \", err.Error())\n\t\treturn\n\t}\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tp.l.Warning(\"Target:\", targetName, \", URL:\", req.URL.String(), \", http.doHTTPRequest: \", err.Error())\n\t\treturn\n\t}\n\n\tp.l.Debug(\"Target:\", targetName, \", URL:\", req.URL.String(), \", response: \", string(respBody))\n\n\t// Calling Body.Close() allows the TCP connection to be reused.\n\tresp.Body.Close()\n\tresult.respCodes.IncKey(strconv.FormatInt(int64(resp.StatusCode), 10))\n\n\tif p.opts.Validators != nil {\n\t\tfailedValidations := validators.RunValidators(p.opts.Validators, &validators.Input{Response: resp, ResponseBody: respBody}, result.validationFailure, p.l)\n\n\t\t// If any validation failed, return now, leaving the success and latency\n\t\t// counters unchanged.\n\t\tif len(failedValidations) > 0 {\n\t\t\tp.l.Debug(\"Target:\", targetName, \", URL:\", req.URL.String(), \", http.doHTTPRequest: failed validations: \", strings.Join(failedValidations, \",\"))\n\t\t\treturn\n\t\t}\n\t}\n\n\tresult.success++\n\tresult.latency.AddFloat64(latency.Seconds() / p.opts.LatencyUnit.Seconds())\n\tif result.respBodies != nil && len(respBody) <= maxResponseSizeForMetrics {\n\t\tresult.respBodies.IncKey(string(respBody))\n\t}\n}", "func (c *Client) HTTPClient() *http.Client {\n\treturn c.http\n}" ]
[ "0.50657016", "0.50615436", "0.50130624", "0.49709573", "0.49220985", "0.49121484", "0.49045214", "0.4903276", "0.4830333", "0.47424307", "0.47421747", "0.47300133", "0.47285676", "0.4725351", "0.47202286", "0.47041163", "0.4699457", "0.4673111", "0.4672279", "0.46473005", "0.46375734", "0.46355462", "0.46330684", "0.46313247", "0.46277267", "0.462521", "0.46238244", "0.46210793", "0.46152487", "0.46140495", "0.45845073", "0.4582075", "0.4581246", "0.45757788", "0.45710814", "0.4568632", "0.4568012", "0.45624086", "0.45411584", "0.45366868", "0.4530033", "0.45262018", "0.45232385", "0.4519028", "0.45178998", "0.45092607", "0.45033547", "0.44904795", "0.44870594", "0.4465987", "0.44608963", "0.4454086", "0.44476068", "0.44288427", "0.44236758", "0.44219208", "0.4421887", "0.44157675", "0.44147405", "0.4414339", "0.44133803", "0.44090727", "0.44084656", "0.4402996", "0.4394973", "0.43873543", "0.43818897", "0.43795705", "0.4374441", "0.43662575", "0.43651924", "0.43649426", "0.4363573", "0.43610203", "0.4360503", "0.43601233", "0.4359527", "0.4357517", "0.43527424", "0.4352646", "0.43482003", "0.43475", "0.43418625", "0.43406534", "0.43391442", "0.43354687", "0.43345684", "0.43333203", "0.43274608", "0.43225288", "0.4321294", "0.43208203", "0.43148473", "0.4308962", "0.4306319", "0.43061563", "0.4306155", "0.43055397", "0.4296058", "0.42921314" ]
0.7810919
0
AddSSLKeys adds the given ssl keys to the given delivery service.
func AddSSLKeys(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil) if userErr != nil || sysErr != nil { api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) return } defer inf.Close() if !inf.Config.RiakEnabled { api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("adding SSL keys to Riak for delivery service: Riak is not configured")) return } req := tc.DeliveryServiceAddSSLKeysReq{} if err := api.Parse(r.Body, inf.Tx.Tx, &req); err != nil { api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("parsing request: "+err.Error()), nil) return } if userErr, sysErr, errCode := tenant.Check(inf.User, *req.DeliveryService, inf.Tx.Tx); userErr != nil || sysErr != nil { api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) return } certChain, isUnknownAuth, err := verifyCertificate(req.Certificate.Crt, "") if err != nil { api.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New("verifying certificate: "+err.Error()), nil) return } req.Certificate.Crt = certChain base64EncodeCertificate(req.Certificate) dsSSLKeys := tc.DeliveryServiceSSLKeys{ CDN: *req.CDN, DeliveryService: *req.DeliveryService, Hostname: *req.HostName, Key: *req.Key, Version: *req.Version, Certificate: *req.Certificate, } if err := riaksvc.PutDeliveryServiceSSLKeysObj(dsSSLKeys, inf.Tx.Tx, inf.Config.RiakAuthOptions); err != nil { api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("putting SSL keys in Riak for delivery service '"+*req.DeliveryService+"': "+err.Error())) return } if err := updateSSLKeyVersion(*req.DeliveryService, req.Version.ToInt64(), inf.Tx.Tx); err != nil { api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("adding SSL keys to delivery service '"+*req.DeliveryService+"': "+err.Error())) return } if isUnknownAuth { api.WriteRespAlert(w, r, tc.WarnLevel, "WARNING: SSL keys were successfully added for '"+*req.DeliveryService+"', but the certificate is signed by an unknown authority and may be invalid") return } api.WriteResp(w, r, "Successfully added ssl keys for "+*req.DeliveryService) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *KeyStore) AddKeys(role string, threshold uint, expiry string, keys map[string]*KeyInfo) error {\n\tif threshold == 0 {\n\t\treturn errors.Errorf(\"invalid threshold (0)\")\n\t}\n\n\trk := roleKeys{threshold: threshold, expiry: expiry, keys: &sync.Map{}}\n\n\tfor id, info := range keys {\n\t\tpub, err := info.publicKey()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trk.keys.Store(id, pub)\n\t}\n\ts.Store(role, rk)\n\n\treturn nil\n}", "func (i *Ingress) AddTLS(TLSConfig api.IngressTLSConfig) {\n\ttls := v1beta1.IngressTLS{\n\t\tHosts: TLSConfig.Hosts,\n\t\tSecretName: TLSConfig.SecretName,\n\t}\n\ti.Spec.TLS = append(i.Spec.TLS, tls)\n}", "func (s Interactor) AddCertKeys(uri string, mod string, exp string) error {\n\tprofileURI := strings.Split(uri, \"#\")[0]\n\tresource, _ := s.pathInformer.GetPathInfo(profileURI)\n\tg := domain.NewGraph(profileURI)\n\n\ts.fileHandler.UpdateGraphFromFile(g, s.parser, resource.File)\n\tkeyTerm := domain.NewResource(profileURI + \"#key\" + s.uuidGenerator.UUID()[:4])\n\tg.AddTriple(domain.NewResource(uri), domain.NewNS(\"cert\").Get(\"key\"), keyTerm)\n\tg.AddTriple(keyTerm, domain.NewNS(\"rdf\").Get(\"type\"), domain.NewNS(\"cert\").Get(\"RSAPublicKey\"))\n\tg.AddTriple(keyTerm, domain.NewNS(\"rdfs\").Get(\"label\"), domain.NewLiteral(\"Created \"+time.Now().Format(time.RFC822)+\" on \"+resource.Obj.Host))\n\tg.AddTriple(keyTerm, domain.NewNS(\"cert\").Get(\"modulus\"), domain.NewLiteralWithDatatype(mod, domain.NewResource(\"http://www.w3.org/2001/XMLSchema#hexBinary\")))\n\tg.AddTriple(keyTerm, domain.NewNS(\"cert\").Get(\"exponent\"), domain.NewLiteralWithDatatype(exp, domain.NewResource(\"http://www.w3.org/2001/XMLSchema#int\")))\n\n\t// write account acl to disk\n\tserializedGraph, err := s.parser.Serialize(g, constant.TextTurtle)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := s.fileHandler.CreateOrUpdateFile(resource.File, strings.NewReader(serializedGraph)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (a SSHAgent) AddCertificates(privateKey PrivateKey, publicKey ssh.PublicKey, ttl uint32) error {\n\tconn, err := net.Dial(\"unix\", a.Socket)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\tcert, ok := publicKey.(*ssh.Certificate)\n\tif !ok {\n\t\treturn fmt.Errorf(\"public key is not a valid ssh certificate\")\n\t}\n\tagentClient := agent.NewClient(conn)\n\treturn agentClient.Add(agent.AddedKey{\n\t\tPrivateKey: privateKey.Raw(),\n\t\tCertificate: cert,\n\t\tLifetimeSecs: ttl,\n\t})\n}", "func GetDeliveryServiceURLSigKeys(toClient *toclient.Session, dsName string, opts *toclient.RequestOptions) (tc.URLSigKeys, toclientlib.ReqInf, error) {\n\tif opts == nil {\n\t\topts = &toclient.RequestOptions{}\n\t}\n\tresp, reqInf, err := toClient.GetDeliveryServiceURLSignatureKeys(dsName, *opts)\n\treturn resp.Response, reqInf, err\n}", "func (s *AccountsService) AddGPGKeys(accountID string, input *GpgKeysInput) (*map[string]GpgKeyInfo, *Response, error) {\n\tu := fmt.Sprintf(\"accounts/%s/gpgkeys\", accountID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, input)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new(map[string]GpgKeyInfo)\n\tresp, err := s.client.Do(req, v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func (n *Notification) AddKey(key string) error {\n\n\tif len(key) != 40 {\n\t\treturn errors.New(\"Error, Apikey must be 40 characters long.\")\n\t}\n\n\tn.apikeys = append(n.apikeys, key)\n\treturn nil\n}", "func (bs basicElsService) AddRoutingKey(ctx context.Context, addRoutingKeyRequest *api.AddRoutingKeyRequest) (*api.ServiceInstanceReponse, error) {\n\tif addRoutingKeyRequest.ServiceUri== \"\" {\n\t\treturn &api.ServiceInstanceReponse{}, ErrInvalid\n\t}\n\tif addRoutingKeyRequest.RoutingKey== \"\" {\n\t\treturn &api.ServiceInstanceReponse{}, ErrNotFound\n\t}\n\n\tinstance := &routingkeys.ServiceInstance{addRoutingKeyRequest.RoutingKey,\n\t\taddRoutingKeyRequest.ServiceUri,\n\t\t[]string{addRoutingKeyRequest.Tags}}\n\n\tbs.rksrv.Add(instance)\n\n\treturn &api.ServiceInstanceReponse{instance.Uri,\n\t\tinstance.Tags[0]}, nil\n\n}", "func GetSSLKeysByHostName(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, []string{\"hostname\"}, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\n\tif inf.Config.RiakEnabled == false {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New(\"the Riak service is unavailable\"), errors.New(\"getting SSL keys from Riak by host name: Riak is not configured\"))\n\t\treturn\n\t}\n\n\thostName := inf.Params[\"hostname\"]\n\tdomainName := \"\"\n\thostRegex := \"\"\n\tstrArr := strings.Split(hostName, \".\")\n\tln := len(strArr)\n\tif ln > 1 {\n\t\tfor i := 2; i < ln-1; i++ {\n\t\t\tdomainName += strArr[i] + \".\"\n\t\t}\n\t\tdomainName += strArr[ln-1]\n\t\thostRegex = `.*\\.` + strArr[1] + `\\..*`\n\t}\n\n\t// lookup the cdnID\n\tcdnID, ok, err := getCDNIDByDomainname(domainName, inf.Tx.Tx)\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"getting cdn id by domain name: \"+err.Error()))\n\t\treturn\n\t}\n\tif !ok {\n\t\tapi.WriteRespAlert(w, r, tc.InfoLevel, \" - a cdn does not exist for the domain: \"+domainName+\" parsed from hostname: \"+hostName)\n\t\treturn\n\t}\n\t// now lookup the deliveryservice xmlID\n\txmlID, ok, err := getXMLID(cdnID, hostRegex, inf.Tx.Tx)\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"getting xml id: \"+err.Error()))\n\t\treturn\n\t}\n\tif !ok {\n\t\tapi.WriteRespAlert(w, r, tc.InfoLevel, \" - a delivery service does not exist for a host with hostname of \"+hostName)\n\t\treturn\n\t}\n\n\tgetSSLKeysByXMLIDHelper(xmlID, inf, w, r)\n}", "func AddKeys(sum, k1, k2 *Key) {\n\ta := k1.ToExtended()\n\tb := new(CachedGroupElement)\n\tk2.ToExtended().ToCached(b)\n\tc := new(CompletedGroupElement)\n\tgeAdd(c, a, b)\n\ttmp := new(ExtendedGroupElement)\n\tc.ToExtended(tmp)\n\ttmp.ToBytes(sum)\n\treturn\n}", "func (s *Service) AddPrivateKey(keyID string, privateKey crypto.PrivateKey) error {\n\tif _, ok := s.keys[keyID]; ok {\n\t\ts.log.Error(\"The specified key ID is already in use\", \"keyID\", keyID)\n\t\treturn signingkeys.ErrSigningKeyAlreadyExists.Errorf(\"The specified key ID is already in use: %s\", keyID)\n\t}\n\ts.keys[keyID] = privateKey.(crypto.Signer)\n\treturn nil\n}", "func (g *GroupsService) AddServices(group Group, services ...string) (bool, *Response, error) {\n\treturn g.AddIdentities(group, \"SERVICE\", services...)\n}", "func (p *WCSPayload) Add(key string, value string) {\n\tif key != \"\" && value != \"\" {\n\t\tfor _, v := range validkeys {\n\t\t\tif v == key {\n\t\t\t\tp.wcs[key] = value\n\t\t\t}\n\t\t}\n\t}\n}", "func (ks *KeyStore) Add(privateKey *rsa.PrivateKey, kid string) {\n\tks.mu.Lock()\n\tdefer ks.mu.Unlock()\n\n\tks.store[kid] = privateKey\n}", "func (i service) AddKeysForAccount(acc config.Account) error {\n\ttctx, err := contextutil.New(context.Background(), acc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkeys, err := getKeyPairsFromAccount(acc)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = i.AddKey(tctx, keys[id.KeyPurposeP2P])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = i.AddKey(tctx, keys[id.KeyPurposeSigning])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = i.AddKey(tctx, keys[id.KeyPurposeEthMsgAuth])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Connect) AddKeySshAgent(sshAgent interface{}, key interface{}) {\n\taddedKey := agent.AddedKey{\n\t\tPrivateKey: key,\n\t\tConfirmBeforeUse: true,\n\t\tLifetimeSecs: 3000,\n\t}\n\n\tswitch ag := sshAgent.(type) {\n\tcase agent.Agent:\n\t\tag.Add(addedKey)\n\tcase agent.ExtendedAgent:\n\t\tag.Add(addedKey)\n\t}\n}", "func (mr *MockKeysServiceMockRecorder) KeysAdd(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysAdd\", reflect.TypeOf((*MockKeysService)(nil).KeysAdd), arg0, arg1, arg2)\n}", "func (r *Client) EnableTLS(key, cert, cacert string) error {\n\n\t// validate input params\n\tif len(key) == 0 || len(cert) == 0 || len(cacert) == 0 {\n\t\treturn fmt.Errorf(\"key/cert paths not valid\")\n\t}\n\n\tif fileNotFound(key) || fileNotFound(cert) || fileNotFound(cacert) {\n\t\treturn fmt.Errorf(\"key/cert file not found\")\n\t}\n\n\t// update the fields in the object\n\tr.key = key\n\tr.cert = cert\n\tr.cacert = cacert\n\n\tr.TLS = true\n\treturn nil\n}", "func (c CryptoServiceTester) TestAddKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add the key to the targets role\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Check that we added the key and its info to only the first keystore\n\tretrievedKey, retrievedRole, err := cryptoService.keyStores[0].GetKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\n\tretrievedKeyInfo, err := cryptoService.keyStores[0].GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// The key should not exist in the second keystore\n\t_, _, err = cryptoService.keyStores[1].GetKey(privKey.ID())\n\trequire.Error(t, err)\n\t_, err = cryptoService.keyStores[1].GetKeyInfo(privKey.ID())\n\trequire.Error(t, err)\n\n\t// We should be able to successfully get the key from the cryptoservice level\n\tretrievedKey, retrievedRole, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\tretrievedKeyInfo, err = cryptoService.GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// Add the same key to the targets role, since the info is the same we should have no error\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Try to add the same key to the snapshot role, which should error due to the role mismatch\n\trequire.Error(t, cryptoService.AddKey(data.CanonicalSnapshotRole, c.gun, privKey))\n}", "func (s *KeyAgentTestSuite) TestAddKey(c *check.C) {\n\t// make a new local agent\n\tlka, err := NewLocalAgent(s.keyDir, s.hostname, s.username)\n\tc.Assert(err, check.IsNil)\n\n\t// add the key to the local agent, this should write the key\n\t// to disk as well as load it in the agent\n\t_, err = lka.AddKey(s.key)\n\tc.Assert(err, check.IsNil)\n\n\t// check that the key has been written to disk\n\tfor _, ext := range []string{fileExtCert, \"\", fileExtPub} {\n\t\t_, err := os.Stat(fmt.Sprintf(\"%v/keys/%v/%v%v\", s.keyDir, s.hostname, s.username, ext))\n\t\tc.Assert(err, check.IsNil)\n\t}\n\n\t// get all agent keys from teleport agent and system agent\n\tteleportAgentKeys, err := lka.Agent.List()\n\tc.Assert(err, check.IsNil)\n\tsystemAgentKeys, err := lka.sshAgent.List()\n\tc.Assert(err, check.IsNil)\n\n\t// check that we've loaded a cert as well as a private key into the teleport agent\n\t// and it's for the user we expected to add a certificate for\n\tc.Assert(teleportAgentKeys, check.HasLen, 2)\n\tc.Assert(teleportAgentKeys[0].Type(), check.Equals, \"[email protected]\")\n\tc.Assert(teleportAgentKeys[0].Comment, check.Equals, \"teleport:\"+s.username)\n\tc.Assert(teleportAgentKeys[1].Type(), check.Equals, \"ssh-rsa\")\n\tc.Assert(teleportAgentKeys[1].Comment, check.Equals, \"teleport:\"+s.username)\n\n\t// check that we've loaded a cert as well as a private key into the system again\n\tfound := false\n\tfor _, sak := range systemAgentKeys {\n\t\tif sak.Comment == \"teleport:\"+s.username && sak.Type() == \"ssh-rsa\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tc.Assert(true, check.Equals, found)\n\tfound = false\n\tfor _, sak := range systemAgentKeys {\n\t\tif sak.Comment == \"teleport:\"+s.username && sak.Type() == \"[email protected]\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tc.Assert(true, check.Equals, found)\n\n\t// unload all keys for this user from the teleport agent and system agent\n\terr = lka.UnloadKey()\n\tc.Assert(err, check.IsNil)\n}", "func skykeyAdd(c client.Client, skykeyString string) error {\n\tvar sk skykey.Skykey\n\terr := sk.FromString(skykeyString)\n\tif err != nil {\n\t\treturn errors.AddContext(err, \"Could not decode skykey string\")\n\t}\n\n\t// Rename the skykey if the --rename-as flag was provided.\n\tif skykeyRenameAs != \"\" {\n\t\tsk.Name = skykeyRenameAs\n\t}\n\n\terr = c.SkykeyAddKeyPost(sk)\n\tif err != nil {\n\t\treturn errors.AddContext(err, \"Could not add skykey\")\n\t}\n\n\treturn nil\n}", "func sslCLIFlags(c *config.Config) []cli.Flag {\n\treturn withDefaults(sslCategoryDescription, []cli.Flag{\n\t\t&cli.PathFlag{\n\t\t\tName: \"ssl_cert\",\n\t\t\tUsage: \"SSL certificate path\",\n\t\t\tDestination: &c.SSL.CertPath,\n\t\t},\n\n\t\t&cli.PathFlag{\n\t\t\tName: \"ssl_key\",\n\t\t\tUsage: \"SSL private key path\",\n\t\t\tDestination: &c.SSL.KeyPath,\n\t\t},\n\t})\n}", "func (services *DNSSdServices) Add(srv DNSSdSvcInfo) {\n\t*services = append(*services, srv)\n}", "func addCertsToConfig(config fab.EndpointConfig, pemCertsList [][]byte) {\n\n\tif len(pemCertsList) == 0 {\n\t\treturn\n\t}\n\n\tvar certs []*x509.Certificate\n\tfor _, pemCerts := range pemCertsList {\n\t\tfor len(pemCerts) > 0 {\n\t\t\tvar block *pem.Block\n\t\t\tblock, pemCerts = pem.Decode(pemCerts)\n\t\t\tif block == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif block.Type != \"CERTIFICATE\" || len(block.Headers) != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcert, err := x509.ParseCertificate(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = verifier.ValidateCertificateDates(cert)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Warn(\"%v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcerts = append(certs, cert)\n\t\t}\n\t}\n\n\tconfig.TLSCACertPool().Add(certs...)\n}", "func (p *WCSPayload) AddURLDict(m map[string][]string) {\n\t// convert m to map[string]string\n\tfor key, _ := range m {\n\t\tif len(m[key]) > 0 {\n\t\t\tp.Add(key, m[key][0])\n\t\t}\n\t}\n}", "func (s *Server) EnableHTTPS(certFile, keyFile string, tlsConfig ...*tls.Config) {\n\tcertFileRealPath := gfile.RealPath(certFile)\n\tif certFileRealPath == \"\" {\n\t\tcertFileRealPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + certFile)\n\t\tif certFileRealPath == \"\" {\n\t\t\tcertFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + certFile)\n\t\t}\n\t}\n\tif certFileRealPath == \"\" {\n\t\ts.Logger().Fatal(fmt.Sprintf(`[ghttp] EnableHTTPS failed: certFile \"%s\" does not exist`, certFile))\n\t}\n\tkeyFileRealPath := gfile.RealPath(keyFile)\n\tif keyFileRealPath == \"\" {\n\t\tkeyFileRealPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + keyFile)\n\t\tif keyFileRealPath == \"\" {\n\t\t\tkeyFileRealPath = gfile.RealPath(gfile.MainPkgPath() + gfile.Separator + keyFile)\n\t\t}\n\t}\n\tif keyFileRealPath == \"\" {\n\t\ts.Logger().Fatal(fmt.Sprintf(`[ghttp] EnableHTTPS failed: keyFile \"%s\" does not exist`, keyFile))\n\t}\n\ts.config.HTTPSCertPath = certFileRealPath\n\ts.config.HTTPSKeyPath = keyFileRealPath\n\tif len(tlsConfig) > 0 {\n\t\ts.config.TLSConfig = tlsConfig[0]\n\t}\n}", "func (znp *Znp) ZdoSecAddLinkKey(shortAddress string, extendedAddress string, key [16]uint8) (rsp *StatusResponse, err error) {\n\treq := &ZdoSecAddLinkKey{ShortAddress: shortAddress, ExtendedAddress: extendedAddress, Key: key}\n\terr = znp.ProcessRequest(unp.C_SREQ, unp.S_ZDO, 0x42, req, &rsp)\n\treturn\n}", "func updateSslKeyPair(ovndb, certFile, privKeyFile string, tlsConfig *tls.Config, ovndbclient goovn.Client) error {\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif ok && event.Op&(fsnotify.Write|fsnotify.Remove) != 0 {\n\t\t\t\t\tcert, err := tls.LoadX509KeyPair(certFile, privKeyFile)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.Infof(\"Cannot load new cert with cert %s key %s err %s\", certFile, privKeyFile, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif reflect.DeepEqual(tlsConfig.Certificates, []tls.Certificate{cert}) {\n\t\t\t\t\t\tklog.Infof(\"TLS update already finished\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\ttlsConfig.Certificates = []tls.Certificate{cert}\n\t\t\t\t\terr = ovndbclient.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tklog.Errorf(\"Cannot close %s connection: %s\", ovndb, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tklog.Infof(\"TLS connection to %s force reconnected with new tlsconfig\", ovndb)\n\t\t\t\t}\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif ok {\n\t\t\t\t\tklog.Errorf(\"Error watching for changes: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tif err := watcher.Add(certFile); err != nil {\n\t\treturn err\n\t}\n\tif err := watcher.Add(privKeyFile); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (tm *ServiceTracerouteManager) AddService(service ServiceConfiguration) {\n\tif tm.Configuration.DNSResolver {\n\t\ttm.DNS.UpdateService(service)\n\t\tfor i, _ := range tm.Configuration.Services {\n\t\t\tif tm.Configuration.Services[i].Service == service.Service {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ttm.Configuration.Services = append(tm.Configuration.Services, service)\n\t}\n}", "func (option *SignOption) AddHeadersToSign(headers ...string) {\n\tif option.HeadersToSign == nil {\n\t\toption.HeadersToSign = []string{}\n\t\toption.HeadersToSign = append(option.HeadersToSign, headers...)\n\t} else {\n\t\tfor _, header := range headers {\n\t\t\tif !util.Contains(option.HeadersToSign, header, true) {\n\t\t\t\toption.HeadersToSign = append(option.HeadersToSign, header)\n\t\t\t}\n\t\t}\n\t}\n}", "func (b *BigIP) AddKey(config *Key) error {\n\treturn b.post(config, uriSys, uriCrypto, uriKey)\n}", "func (c *FilesBuilder) AddKeyPair(ctx context.Context, name string,\n\tf func(context.Context, *cke.Node) (cert, key []byte, err error)) error {\n\tvar mu sync.Mutex\n\tcertMap := make(map[string][]byte)\n\tkeyMap := make(map[string][]byte)\n\n\tenv := well.NewEnvironment(ctx)\n\tfor _, n := range c.nodes {\n\t\tn := n\n\t\tenv.Go(func(ctx context.Context) error {\n\t\t\tcertData, keyData, err := f(ctx, n)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmu.Lock()\n\t\t\tcertMap[n.Address] = certData\n\t\t\tkeyMap[n.Address] = keyData\n\t\t\tmu.Unlock()\n\t\t\treturn nil\n\t\t})\n\t}\n\tenv.Stop()\n\terr := env.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.files = append(c.files, fileData{name + \".crt\", certMap})\n\tc.files = append(c.files, fileData{name + \".key\", keyMap})\n\treturn nil\n}", "func (o *APIKey) AddUserAPIKeys(exec boil.Executor, insert bool, related ...*UserAPIKey) error {\n\tvar err error\n\tfor _, rel := range related {\n\t\tif insert {\n\t\t\trel.APIKeyID = o.ID\n\t\t\tif err = rel.Insert(exec); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t\t}\n\t\t} else {\n\t\t\tupdateQuery := fmt.Sprintf(\n\t\t\t\t\"UPDATE \\\"user_api_keys\\\" SET %s WHERE %s\",\n\t\t\t\tstrmangle.SetParamNames(\"\\\"\", \"\\\"\", 1, []string{\"api_key_id\"}),\n\t\t\t\tstrmangle.WhereClause(\"\\\"\", \"\\\"\", 2, userAPIKeyPrimaryKeyColumns),\n\t\t\t)\n\t\t\tvalues := []interface{}{o.ID, rel.ID}\n\n\t\t\tif boil.DebugMode {\n\t\t\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\t\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t\t\t}\n\n\t\t\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to update foreign table\")\n\t\t\t}\n\n\t\t\trel.APIKeyID = o.ID\n\t\t}\n\t}\n\n\tif o.R == nil {\n\t\to.R = &apiKeyR{\n\t\t\tUserAPIKeys: related,\n\t\t}\n\t} else {\n\t\to.R.UserAPIKeys = append(o.R.UserAPIKeys, related...)\n\t}\n\n\tfor _, rel := range related {\n\t\tif rel.R == nil {\n\t\t\trel.R = &userAPIKeyR{\n\t\t\t\tAPIKey: o,\n\t\t\t}\n\t\t} else {\n\t\t\trel.R.APIKey = o\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Config) AppendServices(newServices []*services.ServiceConfig) error {\n\tlog.Printf(\"Appending %d services.\\n\", len(newServices))\n\tif c.ServiceMap == nil {\n\t\tc.ServiceMap = make(map[string]*services.ServiceConfig)\n\t}\n\tfor _, s := range newServices {\n\t\tif _, found := c.ServiceMap[s.Name]; !found {\n\t\t\tc.ServiceMap[s.Name] = s\n\t\t\tc.Services = append(c.Services, *s)\n\t\t}\n\t}\n\treturn nil\n}", "func WithSecureTLS(rootCAs *x509.CertPool) Option {\n\treturn func(args *Client) {\n\t\targs.httpClientSetupFuncs = append(args.httpClientSetupFuncs, httpclient.SecureTLSOption(rootCAs))\n\t}\n}", "func RegisterHttpsServicesAndStartListener() {\n\taph := aphService{}\n\n\t// HelloWorldHandler := httptransport.NewServer(\n\t// \tmakeHelloWorldEndpoint(aph),\n\t// \tdecodeHelloWorldRequest,\n\t// \tencodeResponse,\n\t// )\n\t// HelloDaerahHandler := httptransport.NewServer(\n\t// \tmakeHelloDaerahEndpoint(aph),\n\t// \tdecodeHelloDaerahRequest,\n\t// \tencodeResponse,\n\t// )\n\tGetItenaryHandler := httptransport.NewServer(\n\t\tmakeGetItenaryEndpoint(aph),\n\t\tdecodeGetItenaryRequest,\n\t\tencodeResponse,\n\t)\n\t// http.Handle(\"/HelloWorld\", HelloWorldHandler)\n\t// http.Handle(\"/HelloDaerah\", HelloDaerahHandler)\n\thttp.Handle(\"/GetItenary\", GetItenaryHandler)\n}", "func (s ServiceClientWrapper) AddKey(name string, password string) (addr string, mnemonic string, err error) {\n\treturn s.ServiceClient.Insert(name, password)\n}", "func (k Keeper) AddCerts(ctx sdk.Context, msg MsgSetCerts) (sdk.Tags, sdk.Error) {\n\t// check owner to add certificate\n\tif !k.hasOwner(ctx, msg.Issuer, msg.Sender) {\n\t\treturn nil, sdk.ErrUnauthorized(fmt.Sprintf(\"addr %s unauthorized to add\", msg.Sender))\n\t}\n\n\tfor _, value := range msg.Values {\n\t\tif value.Confidence == true {\n\t\t\tcert, found := k.GetCert(ctx, value.Owner, value.Property, msg.Issuer)\n\t\t\tif !found {\n\t\t\t\t// new cert\n\t\t\t\tcert = Cert{\n\t\t\t\t\tProperty: value.Property,\n\t\t\t\t\tOwner: value.Owner,\n\t\t\t\t\tCertifier: msg.Issuer,\n\t\t\t\t\tData: value.Data,\n\t\t\t\t\tCreatedAt: ctx.BlockHeader().Time.Unix(),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// update cert\n\t\t\t\tcert.Data = value.Data\n\t\t\t}\n\n\t\t\t// add cert\n\t\t\tk.setCert(ctx, value.Owner, cert)\n\n\t\t} else {\n\t\t\t// delete cert\n\t\t\tk.deleteCert(ctx, value.Owner, value.Property, msg.Issuer)\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (o *APIKey) AddUserAPIKeysGP(insert bool, related ...*UserAPIKey) {\n\tif err := o.AddUserAPIKeys(boil.GetDB(), insert, related...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (a *LocalKeyAgent) addKey(key *Key) error {\n\tif key == nil {\n\t\treturn trace.BadParameter(\"key is nil\")\n\t}\n\tif key.ProxyHost == \"\" {\n\t\tkey.ProxyHost = a.proxyHost\n\t}\n\tif key.Username == \"\" {\n\t\tkey.Username = a.username\n\t}\n\n\t// In order to prevent unrelated key data to be left over after the new\n\t// key is added, delete any already stored key with the same index if their\n\t// RSA private keys do not match.\n\tstoredKey, err := a.keyStore.GetKey(key.KeyIndex)\n\tif err != nil {\n\t\tif !trace.IsNotFound(err) {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t} else {\n\t\tif subtle.ConstantTimeCompare(storedKey.Priv, key.Priv) == 0 {\n\t\t\ta.log.Debugf(\"Deleting obsolete stored key with index %+v.\", storedKey.KeyIndex)\n\t\t\tif err := a.keyStore.DeleteKey(storedKey.KeyIndex); err != nil {\n\t\t\t\treturn trace.Wrap(err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Save the new key to the keystore (usually into ~/.tsh).\n\tif err := a.keyStore.AddKey(key); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\treturn nil\n}", "func (agent *MonitorAgent) addDeploymentsServices(deps map[string]appsv1.Deployment, services map[string]*pb.ServiceHealthReport) {\n\tfor depName, dep := range deps {\n\t\tserviceMsg, err := agent.buildDeploymentMessage(dep)\n\t\tif err != nil {\n\t\t\tlogger.Error(err, \"error building Deployment message\")\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := services[depName]; ok {\n\t\t\tlogger.Info(\"duplicate service name\", \"service\", depName)\n\t\t}\n\t\tservices[depName] = serviceMsg\n\t}\n}", "func (s String) Add(keys ...string) {\n\tfor _, key := range keys {\n\t\ts[key] = yes\n\t}\n}", "func (c *cfService) ServiceKeys() ServiceKeys {\n\treturn newServiceKeyAPI(c.Client)\n}", "func (a *LocalKeyAgent) AddHostSignersToCache(certAuthorities []auth.TrustedCerts) error {\n\tfor _, ca := range certAuthorities {\n\t\tpublicKeys, err := ca.SSHCertPublicKeys()\n\t\tif err != nil {\n\t\t\ta.log.Error(err)\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\ta.log.Debugf(\"Adding CA key for %s\", ca.ClusterName)\n\t\terr = a.keyStore.AddKnownHostKeys(ca.ClusterName, a.proxyHost, publicKeys)\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t}\n\treturn nil\n}", "func AddCryptoFuncs(f map[string]interface{}) {\n\tfor k, v := range CreateCryptoFuncs(context.Background()) {\n\t\tf[k] = v\n\t}\n}", "func WithTLS(service string, tlsCfg *tls.Config) Option {\n\treturn func(ctx context.Context, s *Server) error {\n\t\ts.svcConfigs[service].TLSConfig = tlsCfg\n\t\treturn nil\n\t}\n}", "func (s *Synthetics) AddSecureCredential(key, value, description string) (*SecureCredential, error) {\n\treturn s.AddSecureCredentialWithContext(context.Background(), key, value, description)\n}", "func addToGRPCSSLServerList(server *grpc.Server) {\n\tgrpcServersMutex.Lock()\n\tgrpcServers = append(grpcServers, server)\n\tgrpcServersMutex.Unlock()\n}", "func (o *SMTPOptions) AddRecipients(addresses ...string) error {\n\tif len(addresses) == 0 {\n\t\treturn errors.New(\"AddRecipients requires one or more strings that contain comma \" +\n\t\t\t\"separated email addresses\")\n\t}\n\n\to.mutex.Lock()\n\tdefer o.mutex.Unlock()\n\n\taddrs, err := mail.ParseAddressList(strings.Join(addresses, \",\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.toAddrs = append(o.toAddrs, addrs...)\n\n\treturn nil\n}", "func (i *instances) AddSSHKeyToAllInstances(_ context.Context, _ string, _ []byte) error {\n\treturn errors.New(\"not implemented\")\n}", "func (p *WCSPayload) AddDict(wcs map[string]string) {\n\tfor key, value := range wcs {\n\t\tp.Add(key, value)\n\t}\n}", "func addSSHKey(serverKey string, sshKey string) core.BeforeFunc {\n\treturn func(ctx *core.BeforeFuncCtx) error {\n\t\tserver := ctx.Meta[serverKey].(*instance.Server)\n\t\ttags := append(server.Tags, formatSSHKeyToTag(sshKey))\n\n\t\tresp, err := instance.NewAPI(ctx.Client).UpdateServer(&instance.UpdateServerRequest{\n\t\t\tZone: server.Zone,\n\t\t\tServerID: server.ID,\n\t\t\tTags: &tags,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tctx.Meta[serverKey] = resp.Server\n\n\t\treturn nil\n\t}\n}", "func (a *LocalKeyAgent) AddDatabaseKey(key *Key) error {\n\tif len(key.DBTLSCerts) == 0 {\n\t\treturn trace.BadParameter(\"key must contains at least one database access certificate\")\n\t}\n\treturn a.addKey(key)\n}", "func startHTTPSListener(service, certFile, keyFile string) error {\n\ts := http.Server{}\n\n\t// If certFile and/or keyFile are blank, generate a self-signed TLS cert\n\tif len(certFile) == 0 || len(keyFile) == 0 {\n\t\tselfSignedCert, err := privatetls.NewCert()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ts.TLSConfig = &tls.Config{\n\t\t\tCertificates: []tls.Certificate{selfSignedCert},\n\t\t}\n\t}\n\n\ts.Addr = service\n\n\treturn s.ListenAndServeTLS(certFile, keyFile)\n}", "func (s *PiperConfig) AddHostKey(key Signer) {\n\tfor i, k := range s.hostKeys {\n\t\tif k.PublicKey().Type() == key.PublicKey().Type() {\n\t\t\ts.hostKeys[i] = key\n\t\t\treturn\n\t\t}\n\t}\n\n\ts.hostKeys = append(s.hostKeys, key)\n}", "func AddSSHCAToClient(publicKey ssh.PublicKey, hosts []string, sshDir string) error {\n\tcaPublic := string(ssh.MarshalAuthorizedKey(publicKey))\n\tknownHosts := filepath.Join(sshDir, KnownHosts)\n\tknownHostsFile, err := os.OpenFile(knownHosts, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"could not create known_hosts file: %w\", err)\n\t\t}\n\t\treturn err\n\t}\n\tdefer knownHostsFile.Close()\n\texistingKnownHostsContent, err := ioutil.ReadAll(knownHostsFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error reading %s: %w\", knownHosts, err)\n\t}\n\tfor _, dns := range hosts {\n\t\t// caPublic terminates with a '\\n', added by ssh.MarshalAuthorizedKey\n\t\tpublicFormat := fmt.Sprintf(\"%s %s %s\", CAPrefix, dns, caPublic)\n\t\tif strings.Contains(string(existingKnownHostsContent), publicFormat) {\n\t\t\tcontinue\n\t\t}\n\t\t_, err = knownHostsFile.WriteString(publicFormat)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not add key %s to known_hosts file: %w\", publicFormat, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (p *Params) InstallTLSFlags(cmd *cobra.Command) {\n\tpf := cmd.PersistentFlags()\n\n\tpf.BoolVar(&p.enableKafkaTLS, FlagEnableTLS, false, \"Enable TLS for the Kafka API (not necessary if specifying custom certs)\")\n\tpf.StringVar(&p.kafkaCAFile, FlagTLSCA, \"\", \"The CA certificate to be used for TLS communication with the broker\")\n\tpf.StringVar(&p.kafkaCertFile, FlagTLSCert, \"\", \"The certificate to be used for TLS authentication with the broker\")\n\tpf.StringVar(&p.kafkaKeyFile, FlagTLSKey, \"\", \"The certificate key to be used for TLS authentication with the broker\")\n}", "func AddService(Domain string, Service func(http.ResponseWriter, *http.Request), Ports ...string) {\n\tserviceMap[Domain] = service{\n\t\taction: Service,\n\t\tports: Ports,\n\t}\n}", "func AppendDeliverySubscriptionOptions(sbOpts []SubscriptionOption, glb globals.Accessor) []SubscriptionOption {\n\td := glb.Delivery()\n\n\tif d == nil {\n\t\treturn sbOpts\n\t}\n\n\tif r := d.Retries; r != nil {\n\t\tsbOpts = append(sbOpts, Retries(*r))\n\t}\n\tif dls := d.DeadLetterSink; !dls.IsNull() && dls.IsKnown() {\n\t\tsbOpts = append(sbOpts, DeadLetterSink(dls))\n\t}\n\n\treturn sbOpts\n}", "func (o *NotificationConfig) SetServiceApiKey(v string) {\n\to.ServiceApiKey = &v\n}", "func addKeyUsages(data *dataBundle, certTemplate *x509.Certificate) {\n\tif data.params.IsCA {\n\t\tcertTemplate.KeyUsage = x509.KeyUsage(x509.KeyUsageCertSign | x509.KeyUsageCRLSign)\n\t\treturn\n\t}\n\n\tcertTemplate.KeyUsage = data.params.KeyUsage\n\n\tif data.params.ExtKeyUsage&anyExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageAny)\n\t}\n\n\tif data.params.ExtKeyUsage&serverAuthExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageServerAuth)\n\t}\n\n\tif data.params.ExtKeyUsage&clientAuthExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageClientAuth)\n\t}\n\n\tif data.params.ExtKeyUsage&codeSigningExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageCodeSigning)\n\t}\n\n\tif data.params.ExtKeyUsage&emailProtectionExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageEmailProtection)\n\t}\n\n\tif data.params.ExtKeyUsage&ipsecEndSystemExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECEndSystem)\n\t}\n\n\tif data.params.ExtKeyUsage&ipsecTunnelExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECTunnel)\n\t}\n\n\tif data.params.ExtKeyUsage&ipsecUserExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageIPSECUser)\n\t}\n\n\tif data.params.ExtKeyUsage&timeStampingExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageTimeStamping)\n\t}\n\n\tif data.params.ExtKeyUsage&ocspSigningExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageOCSPSigning)\n\t}\n\n\tif data.params.ExtKeyUsage&microsoftServerGatedCryptoExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftServerGatedCrypto)\n\t}\n\n\tif data.params.ExtKeyUsage&netscapeServerGatedCryptoExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageNetscapeServerGatedCrypto)\n\t}\n\n\tif data.params.ExtKeyUsage&microsoftCommercialCodeSigningExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftCommercialCodeSigning)\n\t}\n\n\tif data.params.ExtKeyUsage&microsoftKernelCodeSigningExtKeyUsage != 0 {\n\t\tcertTemplate.ExtKeyUsage = append(certTemplate.ExtKeyUsage, x509.ExtKeyUsageMicrosoftKernelCodeSigning)\n\t}\n}", "func (self *Proxy) StartTLS(cert string, key string) error {\n\n\tself.srv = http.Server{\n\t\tAddr: self.Bind,\n\t\tHandler: self,\n\t}\n\n\tlog.Printf(\"Listening for HTTPs client request at %s.\\n\", self.Bind)\n\n\treturn self.srv.ListenAndServeTLS(cert, key)\n}", "func (option *SignOption) AddHeaders(headers map[string]string) {\n\tif headers == nil {\n\t\treturn\n\t}\n\tif option.Headers == nil {\n\t\toption.Headers = make(map[string]string)\n\t}\n\tfor key, value := range headers {\n\t\toption.AddHeader(key, value)\n\t}\n}", "func (i service) AddKey(ctx context.Context, key id.KeyDID) error {\n\tDID, err := NewDIDFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontract, opts, err := i.prepareTransaction(ctx, DID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"Add key to identity contract %s\", DID.ToAddress().String())\n\ttxID, done, err := i.txManager.ExecuteWithinTX(context.Background(), DID, transactions.NilTxID(), \"Check TX for add key\",\n\t\ti.ethereumTX(opts, contract.AddKey, key.GetKey(), key.GetPurpose(), key.GetType()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisDone := <-done\n\t// non async task\n\tif !isDone {\n\t\treturn errors.New(\"add key TX failed: txID:%s\", txID.String())\n\n\t}\n\treturn nil\n\n}", "func (d *ExtensibleTransport) AddOptions(options ...Option) {\n\tfor _, opt := range options {\n\t\topt(d)\n\t}\n}", "func (m *ttlMap) AddWithTTL(key interface{}, value interface{}, ttl time.Duration) {\n\top := &opAdd{\n\t\tkey: key,\n\t\tvalue: value,\n\t\texpiresAt: time.Now().Add(ttl),\n\t\tchanAdded: make(chan *opFetchResult, 1),\n\t}\n\tgo func() {\n\t\tm.processOnce()\n\t\tm.chanOp <- op\n\t}()\n\t<-op.chanAdded\n\treturn\n}", "func (to *Session) CreateDeliveryServiceRequest(dsr tc.DeliveryServiceRequest) (tc.Alerts, toclientlib.ReqInf, error) {\n\tvar alerts tc.Alerts\n\tif dsr.AssigneeID == 0 && dsr.Assignee != \"\" {\n\t\tres, reqInf, err := to.GetUserByUsernameWithHdr(dsr.Assignee, nil)\n\t\tif err != nil {\n\t\t\treturn alerts, reqInf, err\n\t\t}\n\t\tif len(res) == 0 {\n\t\t\treturn alerts, reqInf, errors.New(\"no user with name \" + dsr.Assignee)\n\t\t}\n\t\tdsr.AssigneeID = *res[0].ID\n\t}\n\n\tif dsr.AuthorID == 0 && dsr.Author != \"\" {\n\t\tres, reqInf, err := to.GetUserByUsernameWithHdr(dsr.Author, nil)\n\t\tif err != nil {\n\t\t\treturn alerts, reqInf, err\n\t\t}\n\t\tif len(res) == 0 {\n\t\t\treturn alerts, reqInf, errors.New(\"no user with name \" + dsr.Author)\n\t\t}\n\t\tdsr.AuthorID = tc.IDNoMod(*res[0].ID)\n\t}\n\n\tif dsr.DeliveryService.TypeID == 0 && dsr.DeliveryService.Type.String() != \"\" {\n\t\tty, reqInf, err := to.GetTypeByNameWithHdr(dsr.DeliveryService.Type.String(), nil)\n\t\tif err != nil || len(ty) == 0 {\n\t\t\treturn alerts, reqInf, errors.New(\"no type named \" + dsr.DeliveryService.Type.String())\n\t\t}\n\t\tdsr.DeliveryService.TypeID = ty[0].ID\n\t}\n\n\tif dsr.DeliveryService.CDNID == 0 && dsr.DeliveryService.CDNName != \"\" {\n\t\tcdns, reqInf, err := to.GetCDNByNameWithHdr(dsr.DeliveryService.CDNName, nil)\n\t\tif err != nil || len(cdns) == 0 {\n\t\t\treturn alerts, reqInf, errors.New(\"no CDN named \" + dsr.DeliveryService.CDNName)\n\t\t}\n\t\tdsr.DeliveryService.CDNID = cdns[0].ID\n\t}\n\n\tif dsr.DeliveryService.ProfileID == 0 && dsr.DeliveryService.ProfileName != \"\" {\n\t\tprofiles, reqInf, err := to.GetProfileByNameWithHdr(dsr.DeliveryService.ProfileName, nil)\n\t\tif err != nil || len(profiles) == 0 {\n\t\t\treturn alerts, reqInf, errors.New(\"no Profile named \" + dsr.DeliveryService.ProfileName)\n\t\t}\n\t\tdsr.DeliveryService.ProfileID = profiles[0].ID\n\t}\n\n\tif dsr.DeliveryService.TenantID == 0 && dsr.DeliveryService.Tenant != \"\" {\n\t\tten, reqInf, err := to.TenantByNameWithHdr(dsr.DeliveryService.Tenant, nil)\n\t\tif err != nil || ten == nil {\n\t\t\treturn alerts, reqInf, errors.New(\"no Tenant named \" + dsr.DeliveryService.Tenant)\n\t\t}\n\t\tdsr.DeliveryService.TenantID = ten.ID\n\t}\n\n\treqInf, err := to.post(APIDSRequests, dsr, nil, &alerts)\n\treturn alerts, reqInf, err\n}", "func AddKey(sshFilePath string) error {\n\tconfigRepository := config.NewConfigRepository(func(error) {})\n\tuserRepo := api.NewUserRepository(configRepository, net.NewCloudControllerGateway(configRepository))\n\n\tuser, err := userRepo.GetUser(configRepository.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\tpublic, name, err := getKey(sshFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkeyParams := api.KeyParams{\n\t\tPublic: public,\n\t\tName: name,\n\t}\n\t_, err = user.UploadKey(keyParams)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Key already exists\")\n\t}\n\n\tfmt.Println(\"Upload key successfully\")\n\treturn err\n}", "func (m *Model) AddServices(services []*Service) {\n\tfor _, service := range services {\n\t\tm.AddService(service)\n\t}\n}", "func AddService(svc Service) error {\n\tic := &ipvsCommand{Service: newIPVSService(&svc)}\n\tif err := netlink.SendMessageMarshalled(C.IPVS_CMD_NEW_SERVICE, family, 0, ic); err != nil {\n\t\treturn err\n\t}\n\tfor _, dst := range svc.Destinations {\n\t\tif err := AddDestination(svc, *dst); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (kc *Keychain) Add(key *crypto.PublicKeySECP256K1R) {\n\taddr := key.Address()\n\tkc.Addrs.Add(addr)\n}", "func AddHeadersHandler(addHeaders map[string]string, h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\tfor key, value := range addHeaders {\n\t\t\tw.Header().Set(key, value)\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}", "func (o *APIKey) AddUserAPIKeysG(insert bool, related ...*UserAPIKey) error {\n\treturn o.AddUserAPIKeys(boil.GetDB(), insert, related...)\n}", "func (s *LunaKeyStore) AddKey(keyInfo trustmanager.KeyInfo, privKey data.PrivateKey) error {\n\n\tvar (\n\t\tecdsaPublicKey *data.ECDSAPublicKey\n\t\trsaPublicKey *data.RSAPublicKey\n\t\terr error\n\t)\n\n\tlogrus.Debugf(\"LunaKeyStore.AddKey\")\n\n\trole := keyInfo.Role\n\n\tgeneratateRootKeyOnly := strings.ToLower(os.Getenv(\"NOTARY_LUNA_GENERATE_ROOT_KEYS_ONLY\")) == \"true\"\n\n\tif generatateRootKeyOnly && role != data.CanonicalRootRole {\n\t\treturn errors.New(\"Can only generate root keys in generate root keys only mode.\")\n\t}\n\n\talg := privKey.Algorithm()\n\n\tif alg == data.ECDSAKey {\n\t\tecdsaPublicKey, err = getECDSAPublicKeyFromPrivateKey(privKey)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"Error getting ECDSA Public key: %s\", err)\n\t\t\treturn err\n\t\t}\n\t} else if alg == data.RSAKey {\n\t\trsaPublicKey, err = getRSAPublicKeyFromPrivateKey(privKey)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"Error getting RSA Public key: %s\", err)\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn errors.New(\"Invalid key type.\")\n\t}\n\n\tp, session, c, err := SetupLuna(true, s.passRetriever)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer CleanupLuna(p, session, c)\n\tgun := keyInfo.Gun\n\n\tif alg == data.ECDSAKey {\n\t\tlunaPrivateKey, err := generateECDSAKey(p, session, gun, s.passRetriever, role)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t//Store the public key value for the generated key in the public key for the added key.\n\t\tlunaECDSAPublicKey, ok := lunaPrivateKey.PublicKey.(*data.ECDSAPublicKey)\n\t\tif !ok {\n\t\t\treturn errors.New(\"Unable to get PublicKey from luna private key.\")\n\t\t}\n\t\tecdsaPublicKey.Value = lunaECDSAPublicKey.Value\n\t\tecdsaPublicKey.ResetID()\n\t} else if alg == data.RSAKey {\n\t\tlunaPrivateKey, err := generateRSAKey(p, session, gun, s.passRetriever, role)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlunaRSAPublicKey, ok := lunaPrivateKey.PublicKey.(*data.RSAPublicKey)\n\t\tif !ok {\n\t\t\treturn errors.New(\"Unable to get PublicKey from luna private key.\")\n\t\t}\n\t\trsaPublicKey.Value = lunaRSAPublicKey.Value\n\t\trsaPublicKey.ResetID()\n\t}\n\tfmt.Printf(\"Luna: Generated %s key: %s\\n\", role, privKey.ID())\n\n\treturn nil\n}", "func (_ECC *ECCCaller) AddKeyProposals(opts *bind.CallOpts, arg0 common.Address) (struct {\n\tUnixTime int64\n\tKeyType uint8\n\tKey common.Address\n\tProposer common.Address\n\tVoteCount int64\n}, error) {\n\tret := new(struct {\n\t\tUnixTime int64\n\t\tKeyType uint8\n\t\tKey common.Address\n\t\tProposer common.Address\n\t\tVoteCount int64\n\t})\n\tout := ret\n\terr := _ECC.contract.Call(opts, out, \"addKeyProposals\", arg0)\n\treturn *ret, err\n}", "func GetSSLKeysByXMLID(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, []string{\"xmlid\"}, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\tif inf.Config.RiakEnabled == false {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New(\"the Riak service is unavailable\"), errors.New(\"getting SSL keys from Riak by xml id: Riak is not configured\"))\n\t\treturn\n\t}\n\txmlID := inf.Params[\"xmlid\"]\n\tgetSSLKeysByXMLIDHelper(xmlID, inf, w, r)\n}", "func (f *Fs) addHeaders(headers fs.CommaSepList) {\n\tfor i := 0; i < len(headers); i += 2 {\n\t\tkey := f.opt.Headers[i]\n\t\tvalue := f.opt.Headers[i+1]\n\t\tf.srv.SetHeader(key, value)\n\t}\n}", "func (r *ReferenceAdapter) AddOrUpdateBindings(serviceAccountEmail string) (AddorUpdateBindingResponse, error) {\n\tpolicy, err := r.gcpClient.GetIamPolicy(r.projectReference.Spec.GCPProjectID)\n\tif err != nil {\n\t\treturn AddorUpdateBindingResponse{}, err\n\t}\n\n\t//Checking if policy is modified\n\tnewBindings, modified := util.AddOrUpdateBinding(policy.Bindings, OSDRequiredRoles, serviceAccountEmail)\n\n\t// add new bindings to policy\n\tpolicy.Bindings = newBindings\n\treturn AddorUpdateBindingResponse{\n\t\tmodified: modified,\n\t\tpolicy: policy,\n\t}, nil\n}", "func (s * SortedBySizeKeys) AddKey(key Key) {\n\tif _, ok := keysMap[key]; ok { return }\n\tkeysMap[key] = true;\n\t*s = append(*s, key)\n}", "func (o LinkEnds) Add(key Key, linkend []string) {\n\to[key] = linkend\n}", "func (_ECC *ECCSession) AddKeyProposals(arg0 common.Address) (struct {\n\tUnixTime int64\n\tKeyType uint8\n\tKey common.Address\n\tProposer common.Address\n\tVoteCount int64\n}, error) {\n\treturn _ECC.Contract.AddKeyProposals(&_ECC.CallOpts, arg0)\n}", "func (s *APIServer) AddOutboundFiles(files []string) error {\n\toutbounds := make([]*core.OutboundHandlerConfig, 0)\n\tfor _, file := range files {\n\t\touts, err := jsonToOutboundHandlerConfigs(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutbounds = append(outbounds, outs...)\n\t}\n\treturn s.AddOutbounds(outbounds)\n}", "func (r *extendedKeyring) Add(key agent.AddedKey) error {\n\t// Figure out what key type we're trying to inject\n\tswitch key.PrivateKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\t// Load the injected key\n\t\tdata := &pem.Block{\n\t\t\tType: \"RSA PRIVATE KEY\",\n\t\t\tBytes: x509.MarshalPKCS1PrivateKey(key.PrivateKey.(*rsa.PrivateKey)),\n\t\t}\n\n\t\t// Ensure the key doesn't exist\n\t\tos.Remove(r.targetKeyLocation)\n\n\t\t// Write the key out to disk\n\t\tvar file, err = os.Create(r.targetKeyLocation)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"\\nssh_agent_download: Could not create key file\", err.Error())\n\t\t}\n\t\tdefer file.Close() // Ensure we close the file later\n\n\t\t// Secure before writing\n\t\t// Note: Technically someone could write in here before we do this\n\t\tos.Chmod(r.targetKeyLocation, 0400)\n\n\t\t// Dump the (un-encrypted) key into this file\n\t\tpem.Encode(file, data)\n\n\t\t// Let the keyboard monkey know\n\t\tfmt.Printf(\"ssh_agent_download: saved key to %s\\n\", r.targetKeyLocation)\n\n\t// Let the user know this won't work\n\tdefault:\n\t\tlog.Fatal(\"ssh_agent_download: unsupported key type %T\", key.PrivateKey)\n\t}\n\n\treturn nil\n}", "func (f5 *f5LTM) AddCert(routename, hostname, cert, privkey,\n\tdestCACert string) error {\n\tif f5.privkey == \"\" {\n\t\treturn fmt.Errorf(\"Cannot configure TLS for route %s\"+\n\t\t\t\" because router was not provided an SSH private key\",\n\t\t\troutename)\n\t}\n\n\tvar deleteServerSslProfile,\n\t\tdeleteClientSslProfileFromVserver, deleteClientSslProfile,\n\t\tdeletePrivateKey, deleteCert, deleteCACert bool\n\n\tsuccess := false\n\n\tdefer func() {\n\t\tif success != true {\n\t\t\tf5.deleteCertParts(routename, false, deleteServerSslProfile,\n\t\t\t\tdeleteClientSslProfileFromVserver, deleteClientSslProfile,\n\t\t\t\tdeletePrivateKey, deleteCert, deleteCACert)\n\t\t}\n\t}()\n\n\tvar err error\n\n\tcertname := fmt.Sprintf(\"%s-https-cert\", routename)\n\terr = f5.uploadCert(cert, certname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeleteCert = true\n\n\tkeyname := fmt.Sprintf(\"%s-https-key\", routename)\n\terr = f5.uploadKey(privkey, keyname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeletePrivateKey = true\n\n\tclientSslProfileName := fmt.Sprintf(\"%s-client-ssl-profile\", routename)\n\terr = f5.createClientSslProfile(clientSslProfileName,\n\t\thostname, certname, keyname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeleteClientSslProfile = true\n\n\terr = f5.associateClientSslProfileWithVserver(clientSslProfileName,\n\t\tf5.httpsVserver)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeleteClientSslProfileFromVserver = true\n\n\tif destCACert != \"\" {\n\t\tcacertname := fmt.Sprintf(\"%s-https-chain\", routename)\n\t\terr = f5.uploadCert(destCACert, cacertname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdeleteCACert = true\n\n\t\tserverSslProfileName := fmt.Sprintf(\"%s-server-ssl-profile\", routename)\n\t\terr = f5.createServerSslProfile(serverSslProfileName,\n\t\t\thostname, cacertname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdeleteServerSslProfile = true\n\n\t\terr = f5.associateServerSslProfileWithVserver(serverSslProfileName,\n\t\t\tf5.httpsVserver)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tsuccess = true\n\n\treturn nil\n}", "func (a *Agent) AddService(service *structs.NodeService, chkTypes []*structs.CheckType, persist bool, token string, source configSource) error {\n\ta.stateLock.Lock()\n\tdefer a.stateLock.Unlock()\n\treturn a.addServiceLocked(service, chkTypes, persist, token, source)\n}", "func (_ECC *ECCCallerSession) AddKeyProposals(arg0 common.Address) (struct {\n\tUnixTime int64\n\tKeyType uint8\n\tKey common.Address\n\tProposer common.Address\n\tVoteCount int64\n}, error) {\n\treturn _ECC.Contract.AddKeyProposals(&_ECC.CallOpts, arg0)\n}", "func AppendCertificate(config *tls.Config, crt, key string) error {\n\tfmt.Println(\"TLS: Loading certificates (crt, key):\", crt, key)\n\tcer, err := tls.LoadX509KeyPair(crt, key)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tconfig.Certificates = append(config.Certificates, cer)\n\treturn nil\n}", "func AddDeliveries(m *Deliveries) (id int64, err error) {\n\to := orm.NewOrm()\n\n\tnow := jodaTime.Format(\"Y-M-d HH:mm:ss\", time.Now().In(orm.DefaultTimeLoc))\n\tm.Date = now\n\n\tid, err = o.Insert(m)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.ID = int(id)\n\n\treturn\n}", "func (i service) AddMultiPurposeKey(ctx context.Context, key [32]byte, purposes []*big.Int, keyType *big.Int) error {\n\tDID, err := NewDIDFromContext(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontract, opts, err := i.prepareTransaction(ctx, DID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxID, done, err := i.txManager.ExecuteWithinTX(context.Background(), DID, transactions.NilTxID(), \"Check TX for add multi purpose key\",\n\t\ti.ethereumTX(opts, contract.AddMultiPurposeKey, key, purposes, keyType))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tisDone := <-done\n\t// non async task\n\tif !isDone {\n\t\treturn errors.New(\"add key multi purpose TX failed: txID:%s\", txID.String())\n\n\t}\n\treturn nil\n}", "func (s *service) AddSubscription(subs ...Subscription) error {\n\t// validation ....\n\n\tfor _, subscription := range subs {\n\t\t_, err := s.r.AddSubscription(subscription)\n\t\tif err != nil {\n\t\t\treturn err // or error validation\n\t\t}\n\t}\n\n\treturn nil\n}", "func (k *Keychain) AddKey(newKey string) error {\n\tkey, err := hex.DecodeString(newKey)\n\tif err != nil {\n\t\treturn ErrInvalidKey\n\t}\n\tk.pushKey(key)\n\treturn nil\n}", "func AddKey(key * Key) {\n\tKeys = append(Keys, *key)\n\tSaveDatabase(Keys, \"keys\")\n}", "func CurveParamsAdd(curve *elliptic.CurveParams, x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)", "func (kw *pkcs11KeyWrapper) WrapKeys(ec *config.EncryptConfig, optsData []byte) ([]byte, error) {\n\tpkcs11Recipients, err := addPubKeys(&ec.DecryptConfig, append(ec.Parameters[\"pkcs11-pubkeys\"], ec.Parameters[\"pkcs11-yamls\"]...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// no recipients is not an error...\n\tif len(pkcs11Recipients) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tjsonString, err := pkcs11.EncryptMultiple(pkcs11Recipients, optsData)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"PKCS11 EncryptMulitple failed: %w\", err)\n\t}\n\treturn jsonString, nil\n}", "func AddServer(serverName string, roles []string) error {\n\tsshKey, err := sshkey.ReadSSHPublicKeyFromConf()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !sshKey.IsProvisioned() {\n\t\treturn fmt.Errorf(\n\t\t\t\"Could not add SSH key to server '%s'. The SSH key '%s' is not available in hcloud. Use the provision command first\", serverName, sshKey.Name)\n\t}\n\tserverConf := Config{\n\t\tName: serverName,\n\t\tSSHPublicKeyID: sshKey.ID,\n\t\tServerType: viper.GetString(confHCloudDefaultServerTypeKey),\n\t\tImageName: viper.GetString(confHCloudDefaultImageNameKey),\n\t\tLocationName: viper.GetString(confHCloudLocationNameKey),\n\t\tRoles: roles}\n\tserverConf.UpdateConfig()\n\treturn nil\n}", "func (*wsNotificationManager) addAddrRequests(addrMap map[string]map[chan struct{}]*wsClient,\n\twsc *wsClient, addrs []string) {\n\n\tfor _, addr := range addrs {\n\t\t// Track the request in the client as well so it can be quickly be\n\t\t// removed on disconnect.\n\t\twsc.addrRequests[addr] = struct{}{}\n\n\t\t// Add the client to the set of clients to notify when the\n\t\t// outpoint is seen. Create map as needed.\n\t\tcmap, ok := addrMap[addr]\n\t\tif !ok {\n\t\t\tcmap = make(map[chan struct{}]*wsClient)\n\t\t\taddrMap[addr] = cmap\n\t\t}\n\t\tcmap[wsc.quit] = wsc\n\t}\n}", "func Add(mgr manager.Manager, hubconfig *rest.Config, tlsKeyFile, tlsCrtFile string, disableTLS bool, createService bool) error {\n\tklog.V(2).Info(\"Setting up webhook listener ...\")\n\n\tif !disableTLS {\n\t\tdir := \"/root/certs\"\n\n\t\tif strings.EqualFold(tlsKeyFile, \"\") || strings.EqualFold(tlsCrtFile, \"\") {\n\t\t\terr := utils.GenerateServerCerts(dir)\n\n\t\t\tif err != nil {\n\t\t\t\tklog.Error(\"Failed to generate a self signed certificate. error: \", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\ttlsKeyFile = filepath.Join(dir, \"tls.key\")\n\t\t\ttlsCrtFile = filepath.Join(dir, \"tls.crt\")\n\t\t}\n\t}\n\n\tvar err error\n\n\twebhookListener, err = CreateWebhookListener(mgr.GetConfig(), hubconfig, mgr.GetScheme(), tlsKeyFile, tlsCrtFile, createService)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to create synchronizer. error: \", err)\n\t\treturn err\n\t}\n\n\treturn mgr.Add(webhookListener)\n}", "func (gw *GrpcWrapper) AddService(handlerFunc func(*grpc.Server)) {\n\tgw.handlerFuncs = append(gw.handlerFuncs, handlerFunc)\n}", "func addNewKeys(existing map[string]interface{}, newKeys []string) {\n\tfor _, n := range newKeys {\n\t\tif _, ok := existing[n]; !ok {\n\t\t\texisting[n] = true\n\t\t}\n\t}\n}", "func (e *Domain) AddIPs(ips ...net.IP) {\n\te.IPs = ips\n}" ]
[ "0.53601336", "0.523952", "0.5065318", "0.5049098", "0.501079", "0.49524736", "0.4897458", "0.48651546", "0.486056", "0.48080438", "0.47436917", "0.47358012", "0.4728572", "0.47049695", "0.46828505", "0.46395725", "0.4624217", "0.46203995", "0.45901638", "0.45896345", "0.45866615", "0.45816705", "0.4580981", "0.45335495", "0.45321202", "0.45189244", "0.4502981", "0.4482668", "0.44818896", "0.4480738", "0.4467508", "0.44631448", "0.44502148", "0.4436373", "0.44330937", "0.44272605", "0.44264865", "0.44262928", "0.4425266", "0.44250906", "0.44008374", "0.43929446", "0.43929207", "0.43771398", "0.4376431", "0.43730792", "0.43729928", "0.43672416", "0.43633556", "0.4362505", "0.43472016", "0.43444374", "0.43430722", "0.43276355", "0.43262082", "0.43091032", "0.42934394", "0.4280246", "0.42790166", "0.42719108", "0.42680976", "0.42606568", "0.42570683", "0.4251017", "0.4247302", "0.42332453", "0.42317832", "0.4230349", "0.4223167", "0.42229587", "0.42199415", "0.4219082", "0.42184493", "0.42163718", "0.42136458", "0.41994312", "0.41954622", "0.41948092", "0.41885573", "0.41837302", "0.41810134", "0.41803005", "0.41757143", "0.41682827", "0.416439", "0.41588598", "0.41556355", "0.41538984", "0.41512448", "0.41483742", "0.41350153", "0.4133227", "0.41292173", "0.41138133", "0.41111887", "0.41099548", "0.41063988", "0.41043243", "0.41000813", "0.40948" ]
0.8105353
0
GetSSLKeysByHostName fetches the ssl keys for a deliveryservice specified by the fully qualified hostname
func GetSSLKeysByHostName(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"hostname"}, nil) if userErr != nil || sysErr != nil { api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) return } defer inf.Close() if inf.Config.RiakEnabled == false { api.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New("the Riak service is unavailable"), errors.New("getting SSL keys from Riak by host name: Riak is not configured")) return } hostName := inf.Params["hostname"] domainName := "" hostRegex := "" strArr := strings.Split(hostName, ".") ln := len(strArr) if ln > 1 { for i := 2; i < ln-1; i++ { domainName += strArr[i] + "." } domainName += strArr[ln-1] hostRegex = `.*\.` + strArr[1] + `\..*` } // lookup the cdnID cdnID, ok, err := getCDNIDByDomainname(domainName, inf.Tx.Tx) if err != nil { api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("getting cdn id by domain name: "+err.Error())) return } if !ok { api.WriteRespAlert(w, r, tc.InfoLevel, " - a cdn does not exist for the domain: "+domainName+" parsed from hostname: "+hostName) return } // now lookup the deliveryservice xmlID xmlID, ok, err := getXMLID(cdnID, hostRegex, inf.Tx.Tx) if err != nil { api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New("getting xml id: "+err.Error())) return } if !ok { api.WriteRespAlert(w, r, tc.InfoLevel, " - a delivery service does not exist for a host with hostname of "+hostName) return } getSSLKeysByXMLIDHelper(xmlID, inf, w, r) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client IotHubResourceClient) GetKeysForKeyNameSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (*CaHostKeyCerts) GetPath() string { return \"/api/objects/ca/host_key_cert/\" }", "func GetSSLKeysByXMLID(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, []string{\"xmlid\"}, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\tif inf.Config.RiakEnabled == false {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New(\"the Riak service is unavailable\"), errors.New(\"getting SSL keys from Riak by xml id: Riak is not configured\"))\n\t\treturn\n\t}\n\txmlID := inf.Params[\"xmlid\"]\n\tgetSSLKeysByXMLIDHelper(xmlID, inf, w, r)\n}", "func (d *DecryptedStore) ByHostname(hostname string) (*tls.Certificate, error) {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\t// changes in encrypted store?\n\tif !d.cacheVersion.Equal(d.encryptedStore.Version()) {\n\t\t// discard all cache.\n\t\t// (not expecting cert changes so frequent as to have an overall effect)\n\t\td.cache = map[string]*tls.Certificate{}\n\t}\n\n\tcached, found := d.cache[hostname]\n\tif !found {\n\t\tmanagedCert := d.encryptedStore.ByHostname(hostname)\n\t\tif managedCert == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\t// our private key cannot decrypt this?\n\t\tif d.keyFingerprint != managedCert.Certificate.PrivateKeyEncrypted.KeyFingerprint {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tcertKey, err := managedCert.Certificate.PrivateKeyEncrypted.Decrypt(d.key, d.keyFingerprint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tkeypair, err := tls.X509KeyPair([]byte(managedCert.Certificate.CertPemBundle), certKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcached = &keypair\n\n\t\t// sprinkle cache entries for all aliases so for (\"*.example.com\", \"example.com\") cert\n\t\t// we won't end up polluting cache with a.example.com, b.example.com, c.example.com, ..\n\t\tfor _, domain := range managedCert.Domains {\n\t\t\td.cache[domain] = cached\n\t\t}\n\t}\n\n\treturn cached, nil\n}", "func (client IotHubResourceClient) GetKeysForKeyName(ctx context.Context, resourceGroupName string, resourceName string, keyName string) (result SharedAccessSignatureAuthorizationRule, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.GetKeysForKeyName\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.GetKeysForKeyNamePreparer(ctx, resourceGroupName, resourceName, keyName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"GetKeysForKeyName\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetKeysForKeyNameSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"GetKeysForKeyName\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetKeysForKeyNameResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"GetKeysForKeyName\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (rule L7Rule) GetDNSKeys(cookie keyvalue.Cookie, trafficType kernel.TrafficType, action interface{}) ([]*keyvalue.KeyValue, error) {\n\tvar err error\n\trep := []*keyvalue.KeyValue{}\n\tfor _, fqdn := range rule.DNS {\n\t\tkv := keyvalue.KeyValue{\n\t\t\tValue: action,\n\t\t}\n\t\tif kv.Key, err = keyvalue.NewDNSKey(\n\t\t\ttrafficType,\n\t\t\tcookie,\n\t\t\t7,\n\t\t\tfqdn,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trep = append(rep, &kv)\n\t}\n\treturn rep, nil\n}", "func certFuncForHost(hostCfg engine.Host, autoCertCache autocert.Cache, s stapler.Stapler) (getCertificateFunc, error) {\n\tac := hostCfg.Settings.AutoCert\n\n\t// Each host gets its own Autocert Manager - this allows individual\n\t// certs to use different autocert authorities, as well as auth keys\n\tautoCertMgr := &autocert.Manager{\n\t\tPrompt: autocert.AcceptTOS,\n\t\tCache: autoCertCache,\n\t\tHostPolicy: autocert.HostWhitelist(hostCfg.Name),\n\t\tEmail: ac.Email,\n\t}\n\n\tif ac.RenewBefore > 0 {\n\t\tautoCertMgr.RenewBefore = ac.RenewBefore\n\t}\n\n\t// if either directory or key are non-empty, we need to generate\n\t// a custom ACME client to override either.\n\tif ac.Key != \"\" || ac.DirectoryURL != \"\" {\n\n\t\t// If DirectoryURL is empty, the default Let's Encrypt URL will be picked.\n\t\tautoCertMgr.Client = &acme.Client{\n\t\t\tDirectoryURL: ac.DirectoryURL,\n\t\t}\n\n\t\t// If Key is non-empty, then decode it as RSA or EC which are the only two keys\n\t\t// we support. Go's crypto library doesn't support a generic function to provide back\n\t\t// a private key interface.\n\t\tif ac.Key != \"\" {\n\t\t\tblock, _ := pem.Decode([]byte(ac.Key))\n\t\t\tif block == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Autocert Key PEM Block for Host %s is invalid.\", hostCfg.Name)\n\t\t\t} else if block.Type == \"RSA PRIVATE KEY\" {\n\t\t\t\trsaPrivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrapf(err, \"Error parsing Autocert Key block of type %s, for Host %s, as an RSA Private Key.\", block.Type, hostCfg.Name)\n\t\t\t\t}\n\t\t\t\tautoCertMgr.Client.Key = rsaPrivateKey\n\t\t\t} else if block.Type == \"EC PRIVATE KEY\" {\n\t\t\t\tecPrivateKey, err := x509.ParseECPrivateKey(block.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, errors.Wrapf(err, \"Error parsing Autocert Key block of type %s, for Host %s, as an ECDSA Private Key.\", block.Type, hostCfg.Name)\n\t\t\t\t}\n\t\t\t\tautoCertMgr.Client.Key = ecPrivateKey\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"AutoCert Private Key for Host %s is of unrecognized type: %s. Supported types\"+\n\t\t\t\t\t\"are RSA PRIVATE KEY and EC PRIVATE KEY.\", hostCfg.Name, block.Type)\n\t\t\t}\n\t\t}\n\t}\n\n\tgetCertFuncForStapling := stapler.WithGetCertFunc(hostCfg.Name, stapler.GetCertificateFunc(autoCertMgr.GetCertificate))\n\n\t// Wrap the GetCert for this host, so we can generate and staple\n\t// an optional OCSP response when requested.\n\tstapledGetCert := func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\tkeyPair, err := autoCertMgr.GetCertificate(info)\n\t\tocspStapleToCert(s, hostCfg, keyPair, getCertFuncForStapling)\n\t\treturn keyPair, err\n\t}\n\n\treturn stapledGetCert, nil\n}", "func AddSSLKeys(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\tif !inf.Config.RiakEnabled {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"adding SSL keys to Riak for delivery service: Riak is not configured\"))\n\t\treturn\n\t}\n\treq := tc.DeliveryServiceAddSSLKeysReq{}\n\tif err := api.Parse(r.Body, inf.Tx.Tx, &req); err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New(\"parsing request: \"+err.Error()), nil)\n\t\treturn\n\t}\n\tif userErr, sysErr, errCode := tenant.Check(inf.User, *req.DeliveryService, inf.Tx.Tx); userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tcertChain, isUnknownAuth, err := verifyCertificate(req.Certificate.Crt, \"\")\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New(\"verifying certificate: \"+err.Error()), nil)\n\t\treturn\n\t}\n\treq.Certificate.Crt = certChain\n\tbase64EncodeCertificate(req.Certificate)\n\tdsSSLKeys := tc.DeliveryServiceSSLKeys{\n\t\tCDN: *req.CDN,\n\t\tDeliveryService: *req.DeliveryService,\n\t\tHostname: *req.HostName,\n\t\tKey: *req.Key,\n\t\tVersion: *req.Version,\n\t\tCertificate: *req.Certificate,\n\t}\n\tif err := riaksvc.PutDeliveryServiceSSLKeysObj(dsSSLKeys, inf.Tx.Tx, inf.Config.RiakAuthOptions); err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"putting SSL keys in Riak for delivery service '\"+*req.DeliveryService+\"': \"+err.Error()))\n\t\treturn\n\t}\n\tif err := updateSSLKeyVersion(*req.DeliveryService, req.Version.ToInt64(), inf.Tx.Tx); err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"adding SSL keys to delivery service '\"+*req.DeliveryService+\"': \"+err.Error()))\n\t\treturn\n\t}\n\tif isUnknownAuth {\n\t\tapi.WriteRespAlert(w, r, tc.WarnLevel, \"WARNING: SSL keys were successfully added for '\"+*req.DeliveryService+\"', but the certificate is signed by an unknown authority and may be invalid\")\n\t\treturn\n\t}\n\tapi.WriteResp(w, r, \"Successfully added ssl keys for \"+*req.DeliveryService)\n}", "func GetServerByHostName(toClient *toclient.Session, hostName string) (*tc.ServerV40, toclientlib.ReqInf, error) {\n\topts := toclient.NewRequestOptions()\n\topts.QueryParameters.Set(\"hostName\", hostName)\n\tresp, reqInf, err := toClient.GetServers(opts)\n\tif err != nil {\n\t\treturn nil, reqInf, err\n\t}\n\tif len(resp.Response) == 0 {\n\t\treturn nil, reqInf, errors.New(\"not found\")\n\t}\n\treturn &resp.Response[0], reqInf, nil\n}", "func (g *Gandi) GetDomainKeys(fqdn string) (keys []SigningKey, err error) {\n\t_, err = g.askGandi(mGET, \"domains/\"+fqdn+\"/keys\", nil, &keys)\n\treturn\n}", "func (er EgressRule) GetDNSKeys(cookie keyvalue.Cookie, trafficType kernel.TrafficType, action interface{}) ([]*keyvalue.KeyValue, error) {\n\tvar err error\n\trep := []*keyvalue.KeyValue{}\n\tfor _, fqdn := range er.FQDNs {\n\t\tkv := keyvalue.KeyValue{\n\t\t\tValue: action,\n\t\t}\n\t\tif kv.Key, err = keyvalue.NewDNSKey(\n\t\t\ttrafficType,\n\t\t\tcookie,\n\t\t\t3,\n\t\t\tfqdn,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trep = append(rep, &kv)\n\t}\n\treturn rep, nil\n}", "func getHostKey(opt *Options) (ssh.PublicKey, error) {\n\tvar reader io.Reader\n\n\tif opt.KnownHostsData != \"\" {\n\t\treader = strings.NewReader(opt.KnownHostsData)\n\t} else {\n\t\tfile, err := os.Open(opt.knownHostsFile()) //nolint:gosec\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer file.Close() //nolint:errcheck\n\n\t\treader = file\n\t}\n\n\tscanner := bufio.NewScanner(reader)\n\tfor scanner.Scan() {\n\t\t_, hosts, hostKey, _, _, err := ssh.ParseKnownHosts(scanner.Bytes())\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"error parsing %s\", scanner.Text())\n\t\t}\n\n\t\tif hostExists(opt.Host, hosts) {\n\t\t\treturn hostKey, nil\n\t\t}\n\t}\n\n\treturn nil, errors.Errorf(\"no hostkey found for %s\", opt.Host)\n}", "func (client Client) ListKeys(resourceGroupName string, name string) (result ListKeysResult, err error) {\n\treq, err := client.ListKeysPreparer(resourceGroupName, name)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"ListKeys\", nil, \"Failure preparing request\")\n\t}\n\n\tresp, err := client.ListKeysSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"redis.Client\", \"ListKeys\", resp, \"Failure sending request\")\n\t}\n\n\tresult, err = client.ListKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"redis.Client\", \"ListKeys\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (client IotHubResourceClient) GetKeysForKeyNameResponder(resp *http.Response) (result SharedAccessSignatureAuthorizationRule, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func GetCertificateForConnect(serverName string) ([]string, error) {\n\tdataPath := GetTLSCertificateDataPath()\n\tcertPath, err := filepath.Abs(filepath.Join(dataPath, ServerNameWithoutPort(serverName)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !strings.HasPrefix(certPath, dataPath) {\n\t\treturn nil, fmt.Errorf(\"could not get certificate for host %s\", serverName)\n\t}\n\tcertificates, err := ParseTLSCertificatesFromPath(certPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(certificates) == 0 {\n\t\treturn nil, fmt.Errorf(\"no certificates found in existing file\")\n\t}\n\n\treturn certificates, nil\n}", "func (client *WebAppsClient) listHostKeysCreateRequest(ctx context.Context, resourceGroupName string, name string, options *WebAppsListHostKeysOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/host/default/listkeys\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (a *Client) GetPlatformSShKeys(params *GetPlatformSShKeysParams) (*GetPlatformSShKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetPlatformSShKeysParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getPlatformSShKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/platform_resources/ssh_keys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetPlatformSShKeysReader{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.(*GetPlatformSShKeysOK), nil\n\n}", "func NewKeyStoreCertChecker(keyStore sshKnowHostGetter, host string) ssh.HostKeyCallback {\n\t// CheckHostSignature checks if the given host key was signed by a Teleport\n\t// certificate authority (CA) or a host certificate the user has seen before.\n\treturn func(addr string, remote net.Addr, key ssh.PublicKey) error {\n\t\tcertChecker := sshutils.CertChecker{\n\t\t\tCertChecker: ssh.CertChecker{\n\t\t\t\tIsHostAuthority: func(key ssh.PublicKey, addr string) bool {\n\t\t\t\t\tkeys, err := keyStore.GetKnownHostKeys(host)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Unable to fetch certificate authorities: %v.\", err)\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\tfor i := range keys {\n\t\t\t\t\t\tif sshutils.KeysEqual(key, keys[i]) {\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t},\n\t\t\t},\n\t\t\tFIPS: isFIPS(),\n\t\t}\n\t\terr := certChecker.CheckHostKey(addr, remote, key)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Host validation failed: %v.\", err)\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tlog.Debugf(\"Validated host %v.\", addr)\n\t\treturn nil\n\t}\n}", "func (client ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServicesClient.ListTestKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.ListTestKeysPreparer(ctx, resourceGroupName, serviceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListTestKeysSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListTestKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func getConfigsForHost(hostname host.Name, configs []model.Config) []model.Config {\n\tsvcConfigs := make([]model.Config, 0)\n\tfor index := range configs {\n\t\tvirtualService := configs[index].Spec.(*v1alpha3.VirtualService)\n\t\tfor _, vsHost := range virtualService.Hosts {\n\t\t\tif host.Name(vsHost).Matches(hostname) {\n\t\t\t\tsvcConfigs = append(svcConfigs, configs[index])\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn svcConfigs\n}", "func sshHostKey(host string) (ssh.PublicKey, error) {\n\tf, err := os.ReadFile(filepath.Join(os.Getenv(\"HOME\"), \".ssh\", \"known_hosts\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Can't read known_hosts file: %v\", err)\n\t}\n\n\tfor {\n\t\tmarker, hosts, pubKey, _, rest, err := ssh.ParseKnownHosts(f)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Parse error in known_hosts: %v\", err)\n\t\t}\n\t\tif marker != \"\" {\n\t\t\t//ignore CA or revoked key\n\t\t\tfmt.Printf(\"ignoring marker: %s\\n\", marker)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, h := range hosts {\n\t\t\tif h == host {\n\t\t\t\treturn pubKey, nil\n\t\t\t}\n\t\t}\n\t\tf = rest\n\t}\n\n\treturn nil, fmt.Errorf(\"No hostkey for %s\", host)\n}", "func (client *WebAppsClient) listHostKeysHandleResponse(resp *http.Response) (WebAppsListHostKeysResponse, error) {\n\tresult := WebAppsListHostKeysResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.HostKeys); err != nil {\n\t\treturn WebAppsListHostKeysResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func GetHostKey(host string, isProduction bool) ssh.PublicKey {\n\tvar file *os.File\n\tvar err error\n\n\tif isProduction {\n\t\tfile, err = os.Open(filepath.Join(\"/\", \"home\", \"ubuntu\", \".ssh\", \"known_hosts\")) // Busca na pasta do usuario ubuntu\n\t} else {\n\t\tfile, err = os.Open(filepath.Join(os.Getenv(\"HOME\"), \".ssh\", \"known_hosts\")) // Não busca no root, quando o crontab executa busca no root\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tvar hostKey ssh.PublicKey\n\tfor scanner.Scan() {\n\t\tfields := strings.Split(scanner.Text(), \" \")\n\t\tif len(fields) != 3 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Contains(fields[0], host) {\n\t\t\tvar err error\n\t\t\thostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"error parsing %q: %v\", fields[2], err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif hostKey == nil {\n\t\tlog.Fatalf(\"no hostkey found for %s\", host)\n\t}\n\treturn hostKey\n}", "func certForHost(hostCfg engine.Host) (tls.Certificate, error) {\n\tc := hostCfg.Settings.KeyPair\n\tcert, err := tls.X509KeyPair(c.Cert, c.Key)\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\treturn cert, nil\n}", "func (m *InventoryServiceModel) GetServicesByHostname(hostname string) ([]*models.InventoryService, error) {\n\tstmt := `SELECT id, environment, hostname, ip, title, techname, value, port, approved, delete, status_in_consul\n\tFROM inventory_host_services WHERE hostname = $1 ORDER BY title ASC`\n\n\thostServices := []*models.InventoryService{}\n\trows, err := m.DB.Query(stmt, hostname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\thostService := &models.InventoryService{}\n\t\terr := rows.Scan(\n\t\t\t&hostService.ID,\n\t\t\t&hostService.Host.Environment,\n\t\t\t&hostService.Host.Hostname,\n\t\t\t&hostService.Host.IP,\n\t\t\t&hostService.Title,\n\t\t\t&hostService.TechName,\n\t\t\t&hostService.Value,\n\t\t\t&hostService.Port,\n\t\t\t&hostService.Approved,\n\t\t\t&hostService.Delete,\n\t\t\t&hostService.StatusInConsul,\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thostServices = append(hostServices, hostService)\n\n\t\tif err = rows.Err(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn hostServices, nil\n}", "func ExampleDatabasesClient_ListKeys() {\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, err := armredisenterprise.NewDatabasesClient(\"subid\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := client.ListKeys(ctx,\n\t\t\"rg1\",\n\t\t\"cache1\",\n\t\t\"default\",\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// TODO: use response item\n\t_ = res\n}", "func GetDeliveryServiceURLSigKeys(toClient *toclient.Session, dsName string, opts *toclient.RequestOptions) (tc.URLSigKeys, toclientlib.ReqInf, error) {\n\tif opts == nil {\n\t\topts = &toclient.RequestOptions{}\n\t}\n\tresp, reqInf, err := toClient.GetDeliveryServiceURLSignatureKeys(dsName, *opts)\n\treturn resp.Response, reqInf, err\n}", "func (client *Client) GetKeys(url string) []string {\n\tresp, err := http.Get(url)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tvar empty []string\n\t\treturn empty\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tvar empty []string\n\t\treturn empty\n\t}\n\tresponseString := string(body)\n\n\treturn strings.Split(responseString, \"\\n\")\n}", "func certFromHost(host, port string) (*x509.Certificate, error) {\n\tvar hostCert *x509.Certificate\n\td := &net.Dialer{\n\t\tTimeout: time.Duration(TimeoutSeconds) * time.Second,\n\t}\n\n\t// Connect insecurely to the host, range through all certificates found, find the cert that matches the host name for the check, and return it\n\tconn, err := tls.DialWithDialer(d, \"tcp\", host+\":\"+port, &tls.Config{\n\t\tInsecureSkipVerify: true,\n\t\tMinVersion: tls.VersionTLS12,\n\t})\n\n\tif err != nil {\n\t\tlog.Error(\"Error retrieving host certificate: \", []*x509.Certificate{&x509.Certificate{}}, \"\", err)\n\t\treturn hostCert, err\n\t}\n\n\tdefer conn.Close()\n\tcert := conn.ConnectionState().PeerCertificates\n\n\tfor _, clientCert := range cert {\n\t\tfor _, certDNS := range clientCert.DNSNames {\n\t\t\tif certDNS == host {\n\t\t\t\thostCert = clientCert\n\t\t\t}\n\t\t}\n\t}\n\n\tif hostCert == nil {\n\t\terr = errors.New(\"Empty certificate returned\")\n\t}\n\treturn hostCert, err\n}", "func (m *ThreatIntelligenceHostsItemSslCertificatesHostSslCertificateItemRequestBuilder) Get(ctx context.Context, requestConfiguration *ThreatIntelligenceHostsItemSslCertificatesHostSslCertificateItemRequestBuilderGetRequestConfiguration)(i084fa7ab3bba802bf5cc3b408e230cc64c167a57976e0d42c37e17154afd5b78.HostSslCertificateable, error) {\n requestInfo, err := m.ToGetRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return nil, err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n res, err := m.BaseRequestBuilder.RequestAdapter.Send(ctx, requestInfo, i084fa7ab3bba802bf5cc3b408e230cc64c167a57976e0d42c37e17154afd5b78.CreateHostSslCertificateFromDiscriminatorValue, errorMapping)\n if err != nil {\n return nil, err\n }\n if res == nil {\n return nil, nil\n }\n return res.(i084fa7ab3bba802bf5cc3b408e230cc64c167a57976e0d42c37e17154afd5b78.HostSslCertificateable), nil\n}", "func (client IotHubResourceClient) ListKeys(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.sasarlr.Response.Response != nil {\n\t\t\t\tsc = result.sasarlr.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.listKeysNextResults\n\treq, err := client.ListKeysPreparer(ctx, resourceGroupName, resourceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListKeysSender(req)\n\tif err != nil {\n\t\tresult.sasarlr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.sasarlr, err = client.ListKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.sasarlr.hasNextLink() && result.sasarlr.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *Client) CheckSSL(host string) (valid bool, err error) {\r\n\r\n\t// Lookup the host\r\n\tvar ips []net.IPAddr\r\n\tif ips, err = c.resolver.LookupIPAddr(context.Background(), host); err != nil {\r\n\t\treturn\r\n\t}\r\n\r\n\t// Loop through all found ip addresses\r\n\tif len(ips) > 0 {\r\n\t\tfor _, ip := range ips {\r\n\r\n\t\t\t// Set the dialer\r\n\t\t\tdialer := net.Dialer{\r\n\t\t\t\tTimeout: c.options.sslTimeout,\r\n\t\t\t\tDeadline: time.Now().Add(c.options.sslDeadline),\r\n\t\t\t}\r\n\r\n\t\t\t// Set the connection\r\n\t\t\tconnection, dialErr := tls.DialWithDialer(\r\n\t\t\t\t&dialer,\r\n\t\t\t\tDefaultProtocol,\r\n\t\t\t\tfmt.Sprintf(\"[%s]:%d\", ip.String(), DefaultPort),\r\n\t\t\t\t&tls.Config{\r\n\t\t\t\t\tServerName: host,\r\n\t\t\t\t},\r\n\t\t\t)\r\n\t\t\tif dialErr != nil {\r\n\t\t\t\t// catch missing ipv6 connectivity\r\n\t\t\t\t// if the ip is ipv6 and the resulting error is \"no route to host\", the record is skipped\r\n\t\t\t\t// otherwise the check will switch to critical\r\n\t\t\t\t/*\r\n\t\t\t\t\tif validate.IsValidIPv6(ip.String()) {\r\n\t\t\t\t\t\tswitch dialErr.(type) {\r\n\t\t\t\t\t\tcase *net.OpError:\r\n\t\t\t\t\t\t\t// https://stackoverflow.com/questions/38764084/proper-way-to-handle-missing-ipv6-connectivity\r\n\t\t\t\t\t\t\tif dialErr.(*net.OpError).Err.(*os.SyscallError).Err == syscall.EHOSTUNREACH {\r\n\t\t\t\t\t\t\t\t// log.Printf(\"%-15s - ignoring unreachable IPv6 address\", ip)\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t*/\r\n\t\t\t\tcontinue\r\n\t\t\t}\r\n\r\n\t\t\t// remember the checked certs based on their Signature\r\n\t\t\tcheckedCerts := make(map[string]struct{})\r\n\r\n\t\t\t// loop to all certs we get\r\n\t\t\t// there might be multiple chains, as there may be one or more CAs present on the current system,\r\n\t\t\t// so we have multiple possible chains\r\n\t\t\tfor _, chain := range connection.ConnectionState().VerifiedChains {\r\n\t\t\t\tfor _, cert := range chain {\r\n\t\t\t\t\tif _, checked := checkedCerts[string(cert.Signature)]; checked {\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcheckedCerts[string(cert.Signature)] = struct{}{}\r\n\r\n\t\t\t\t\t// Filter out CA certificates\r\n\t\t\t\t\tif cert.IsCA {\r\n\t\t\t\t\t\t// log.Printf(\"ignoring CA certificate on ip %s by %s\", ip, cert.Subject.CommonName)\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t// Fail if less than 1 day for expiration\r\n\t\t\t\t\t// remainingValidity := cert.NotAfter.Sub(time.Now())\r\n\t\t\t\t\tif time.Until(cert.NotAfter) > 24*time.Hour {\r\n\t\t\t\t\t\tvalid = true\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t_ = connection.Close()\r\n\t\t}\r\n\t}\r\n\r\n\treturn\r\n}", "func (client DnsClient) ListTsigKeys(ctx context.Context, request ListTsigKeysRequest) (response ListTsigKeysResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listTsigKeys, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListTsigKeysResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListTsigKeysResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListTsigKeysResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListTsigKeysResponse\")\n\t}\n\treturn\n}", "func (a *HyperflexApiService) GetHyperflexKeyEncryptionKeyList(ctx context.Context) ApiGetHyperflexKeyEncryptionKeyListRequest {\n\treturn ApiGetHyperflexKeyEncryptionKeyListRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func getKeys(client *http.Client, cache *keyCache) error {\n\tcache.Lock()\n\tdefer cache.Unlock()\n\n\tkeys := map[string]string{}\n\tres, err := client.Get(\"https://www.googleapis.com/robot/v1/metadata/x509/[email protected]\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(body, &keys)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkc := make(map[string]*rsa.PublicKey, len(keys))\n\tfor k, v := range keys {\n\t\tkey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(v))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkc[k] = key\n\t}\n\n\tcache.keys = kc\n\n\treturn nil\n}", "func getKeys() (sshKey, error) {\n\tvar keys sshKey\n\n\tecdsaPriv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)\n\tif err != nil {\n\t\treturn sshKey{}, err\n\t}\n\n\tpkiPriv := pki.NewPrivateKey(ecdsaPriv)\n\n\tkeys.Private, err = pkiPriv.MarshalText()\n\tif err != nil {\n\t\treturn sshKey{}, err\n\t}\n\tkeys.Public, err = getECDSAPublicKey(&pkiPriv.PrivateKey.PublicKey)\n\tif err != nil {\n\t\treturn sshKey{}, err\n\t}\n\n\treturn keys, nil\n\n}", "func (l Locksmith) GetKey(u string) ([]string, error) {\n\turl := u\n\tif !isURL.MatchString(u) {\n\t\tswitch u {\n\t\tcase \"new\":\n\t\t\turl = SSHKEYS_ONLINE\n\t\tdefault:\n\t\t\turl = fmt.Sprintf(\"%s/%s.keys\", l.URL, u)\n\t\t}\n\t}\n\tclient := &http.Client{}\n\t// create a new request\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"User-Agent\", \"ssh-vault\")\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\treader := bufio.NewReader(res.Body)\n\ttp := textproto.NewReader(reader)\n\tkeys := []string{}\n\trsa := bytes.Buffer{}\n\tisRSA := false\n\tfor {\n\t\tif line, err := tp.ReadLine(); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tif len(keys) == 0 {\n\t\t\t\t\treturn nil, fmt.Errorf(\"key %q not found\", u)\n\t\t\t\t}\n\t\t\t\treturn keys, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t} else if strings.HasPrefix(line, \"ssh-rsa\") {\n\t\t\tkeys = append(keys, line)\n\t\t} else if strings.HasPrefix(line, \"-----BEGIN RSA PRIVATE KEY-----\") {\n\t\t\tisRSA = true\n\t\t\tif _, err := rsa.WriteString(line + \"\\n\"); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else if strings.HasPrefix(line, \"-----END RSA PRIVATE KEY-----\") {\n\t\t\tif _, err := rsa.WriteString(line); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn []string{rsa.String()}, nil\n\t\t} else if isRSA {\n\t\t\tif _, err := rsa.WriteString(line + \"\\n\"); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n}", "func addressRecordsByHostName(records map[addressRecordID]addressRecord) map[hostName][]addressRecord {\n\tbyName := make(map[hostName][]addressRecord)\n\tfor _, record := range records {\n\t\tbyName[record.name] = append(byName[record.name], record)\n\t}\n\n\treturn byName\n}", "func (l *Libvirt) DomainAuthorizedSshKeysGet(Dom Domain, User string, Flags uint32) (rKeys []string, err error) {\n\tvar buf []byte\n\n\targs := DomainAuthorizedSshKeysGetArgs {\n\t\tDom: Dom,\n\t\tUser: User,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(424, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Keys: []string\n\t_, err = dec.Decode(&rKeys)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func ScanHostKey(host string, timeout time.Duration) ([]byte, error) {\n\tcol := &HostKeyCollector{}\n\tconfig := &ssh.ClientConfig{\n\t\tHostKeyCallback: col.StoreKey(),\n\t\tTimeout: timeout,\n\t}\n\tclient, err := ssh.Dial(\"tcp\", host, config)\n\tif err == nil {\n\t\tdefer client.Close()\n\t}\n\tif len(col.knownKeys) > 0 {\n\t\treturn col.knownKeys, nil\n\t}\n\treturn col.knownKeys, err\n}", "func (c *Client) GetKeys(opts map[string]string) (kl []Key, err error) {\n\n\t// First call\n\trawlist, err := c.fetchOneKeyPage(opts)\n\n\t// Empty answer\n\tif rawlist.Count == 0 {\n\t\treturn nil, fmt.Errorf(\"empty key list\")\n\t}\n\n\tvar res []Key\n\n\tres = append(res, rawlist.Results...)\n\tif rawlist.Next != \"\" {\n\t\t// We have pagination\n\t\tfor pn := getPageNum(rawlist.Next); rawlist.Next != \"\"; pn = getPageNum(rawlist.Next) {\n\t\t\topts[\"page\"] = pn\n\n\t\t\trawlist, err = c.fetchOneKeyPage(opts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tres = append(res, rawlist.Results...)\n\t\t}\n\t}\n\tkl = res\n\treturn\n}", "func ExampleClient_ListKeys() {\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\tclientFactory, err := armwebpubsub.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClient().ListKeys(ctx, \"myResourceGroup\", \"myWebPubSubService\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Keys = armwebpubsub.Keys{\n\t// }\n}", "func (c *ConsulClient) ListKeys(ctx context.Context, key string) ([]string, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"ConsulClient.ListKeys\")\n\tdefer span.Finish()\n\n\tregistryOperationCount.WithLabelValues(env, \"ListKeys\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"ListKeys\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\tkv, _, err := c.client.KV().List(key, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeys := []string{}\n\n\tfor _, pair := range kv {\n\t\tkeys = append(keys, pair.Key)\n\t}\n\n\treturn keys, nil\n}", "func (a *LocalKeyAgent) AddHostSignersToCache(certAuthorities []auth.TrustedCerts) error {\n\tfor _, ca := range certAuthorities {\n\t\tpublicKeys, err := ca.SSHCertPublicKeys()\n\t\tif err != nil {\n\t\t\ta.log.Error(err)\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\ta.log.Debugf(\"Adding CA key for %s\", ca.ClusterName)\n\t\terr = a.keyStore.AddKnownHostKeys(ca.ClusterName, a.proxyHost, publicKeys)\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *KeyServer) ListRecaptchaenterpriseKey(ctx context.Context, request *recaptchaenterprisepb.ListRecaptchaenterpriseKeyRequest) (*recaptchaenterprisepb.ListRecaptchaenterpriseKeyResponse, error) {\n\tcl, err := createConfigKey(ctx, request.GetServiceAccountFile())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources, err := cl.ListKey(ctx, request.GetProject())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar protos []*recaptchaenterprisepb.RecaptchaenterpriseKey\n\tfor _, r := range resources.Items {\n\t\trp := KeyToProto(r)\n\t\tprotos = append(protos, rp)\n\t}\n\tp := &recaptchaenterprisepb.ListRecaptchaenterpriseKeyResponse{}\n\tp.SetItems(protos)\n\treturn p, nil\n}", "func (client IotHubResourceClient) GetKeysForKeyNamePreparer(ctx context.Context, resourceGroupName string, resourceName string, keyName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"keyName\": autorest.Encode(\"path\", keyName),\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-04-30-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/IotHubKeys/{keyName}/listkeys\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (client IdentityClient) ListApiKeys(ctx context.Context, request ListApiKeysRequest) (response ListApiKeysResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listApiKeys, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListApiKeysResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListApiKeysResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListApiKeysResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListApiKeysResponse\")\n\t}\n\treturn\n}", "func getKmsKeyFromKeyCache(keyHandle string) (string, string, error) {\n\tcounter := 0\n\tgoto GetKey\nGetKey:\n\t//search for the key in keyring\n\tdata, _, err := getKeyFromKeyCache(keyHandle)\n\tif err != nil {\n\t\tlogrus.Debugf(\"secureoverlay2: Error: Not able to get the key from keyring - %s, counter = %d\", err.Error(), counter)\n\t\tif counter < MAXKEYPOLL {\n\t\t\tgoto WaitForKey\n\t\t}\n\t\treturn \"\", \"\", err\n\t}\n\tlogrus.Debugf(\"secureoverlay2: Got the key in the keyring\")\n\treturn data, \"\", nil\n\nWaitForKey:\n\tlogrus.Debugf(\"secureoverlay2: Waiting for the key\")\n\ttime.Sleep(250 * time.Millisecond)\n\tcounter++\n\tgoto GetKey\n}", "func (kc KVSClient) ListKeys(ctx context.Context, key string) (res responses.KeysResponse, err errors.EdgeX) {\n\tpath := utils.EscapeAndJoinPath(common.ApiKVSRoute, common.Key, key)\n\tqueryParams := url.Values{}\n\tqueryParams.Set(common.KeyOnly, common.ValueTrue)\n\terr = utils.GetRequest(ctx, &res, kc.baseUrl, path, queryParams)\n\tif err != nil {\n\t\treturn res, errors.NewCommonEdgeXWrapper(err)\n\t}\n\treturn res, nil\n}", "func RetrieveKeys(w http.ResponseWriter, req *http.Request) {\n\thaddr, err := address.NewHashFromHash(mux.Vars(req)[\"addr\"])\n\tif err != nil {\n\t\tErrorOut(w, http.StatusBadRequest, \"incorrect address\")\n\t\treturn\n\t}\n\n\t// Check if account exists\n\tar := container.GetAccountRepo()\n\tif !ar.Exists(*haddr) {\n\t\tErrorOut(w, http.StatusNotFound, \"public keys not found\")\n\t\treturn\n\t}\n\n\tkeys, err := ar.FetchKeys(*haddr)\n\tif err != nil {\n\t\tErrorOut(w, http.StatusNotFound, \"public keys not found\")\n\t\treturn\n\t}\n\n\t// Return public keys\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\t_ = json.NewEncoder(w).Encode(jsonOut{\n\t\t\"public_keys\": keys,\n\t})\n}", "func (s impl) List() ([]*computev1.SslCertificate, error) {\n\tsslCertificates, err := s.service.SslCertificates.List(s.projectID).Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sslCertificates.Items, nil\n}", "func (o *ServiceCheck) GetHostName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn o.HostName\n}", "func (a *LocalKeyAgent) certsForCluster(clusterName string) ([]ssh.Signer, error) {\n\tif clusterName != \"\" {\n\t\tk, err := a.GetKey(clusterName, WithSSHCerts{})\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\tsigner, err := k.AsSigner()\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn []ssh.Signer{signer}, nil\n\t}\n\n\t// Load all certs, including the ones from a local SSH agent.\n\tvar signers []ssh.Signer\n\tif a.sshAgent != nil {\n\t\tif sshAgentCerts, _ := a.sshAgent.Signers(); sshAgentCerts != nil {\n\t\t\tsigners = append(signers, sshAgentCerts...)\n\t\t}\n\t}\n\tif ourCerts, _ := a.Signers(); ourCerts != nil {\n\t\tsigners = append(signers, ourCerts...)\n\t}\n\t// Filter out non-certificates (like regular public SSH keys stored in the SSH agent).\n\tcerts := make([]ssh.Signer, 0, len(signers))\n\tfor _, s := range signers {\n\t\tif _, ok := s.PublicKey().(*ssh.Certificate); !ok {\n\t\t\tcontinue\n\t\t}\n\t\tcerts = append(certs, s)\n\t}\n\tif len(certs) == 0 {\n\t\treturn nil, trace.NotFound(\"no auth method available\")\n\t}\n\treturn certs, nil\n}", "func (*CaHostCerts) GetPath() string { return \"/api/objects/ca/host_cert/\" }", "func MakeDNSSECKeysFromTrafficVaultKeys(riakKeys tc.DNSSECKeysTrafficVault, dsTTL time.Duration) (tc.DNSSECKeys, error) {\n\tkeys := map[string]tc.DNSSECKeySet{}\n\tfor name, riakKeySet := range riakKeys {\n\t\tnewKeySet := tc.DNSSECKeySet{}\n\t\tfor _, zsk := range riakKeySet.ZSK {\n\t\t\tnewZSK := tc.DNSSECKey{DNSSECKeyV11: zsk}\n\t\t\t// ZSKs don't have DSRecords, so we don't need to check here\n\t\t\tnewKeySet.ZSK = append(newKeySet.ZSK, newZSK)\n\t\t}\n\t\tfor _, ksk := range riakKeySet.KSK {\n\t\t\tnewKSK := tc.DNSSECKey{DNSSECKeyV11: ksk}\n\t\t\tif ksk.DSRecord != nil {\n\t\t\t\tnewKSK.DSRecord = &tc.DNSSECKeyDSRecord{DNSSECKeyDSRecordV11: *ksk.DSRecord}\n\t\t\t\terr := error(nil)\n\t\t\t\tnewKSK.DSRecord.Text, err = MakeDSRecordText(ksk, dsTTL)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn tc.DNSSECKeys{}, errors.New(\"making DS record text: \" + err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t\tnewKeySet.KSK = append(newKeySet.KSK, newKSK)\n\t\t}\n\t\tkeys[name] = newKeySet\n\t}\n\treturn tc.DNSSECKeys(keys), nil\n}", "func getHostKey(host, port string) (ssh.PublicKey, error) {\n\t// $HOME/.ssh/known_hosts\n\tfile, err := os.Open(filepath.Join(os.Getenv(\"HOME\"), \".ssh\", \"known_hosts\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tvar hostport string\n\tif port == \"22\" {\n\t\t// standard port assumes 22\n\t\t// 192.168.10.53 ssh-rsa AAAAB3Nza...vguvx+81N1xaw==\n\t\thostport = host\n\t} else {\n\t\t// non-standard port(s)\n\t\t// [ssh.example.com]:1999,[93.184.216.34]:1999 ssh-rsa AAAAB3Nza...vguvx+81N1xaw==\n\t\thostport = \"[\" + host + \"]:\" + port\n\t}\n\n\tscanner := bufio.NewScanner(file)\n\tvar hostKey ssh.PublicKey\n\n\tfor scanner.Scan() {\n\t\tfields := strings.Split(scanner.Text(), \" \")\n\t\tif len(fields) != 3 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(fields[0], hostport) {\n\t\t\tvar err error\n\n\t\t\thostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbreak // scanning line by line, first occurrence will be returned\n\t\t}\n\t}\n\n\tif hostKey == nil {\n\t\treturn nil, fmt.Errorf(\"No hostkey for %s\", host+\":\"+port)\n\t}\n\n\treturn hostKey, nil\n}", "func GetKeys(pattern string) (interface{}, error) {\n\tconnect := Connect()\n\treply, err := connect.Do(\"KEYS\", pattern)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn reply, err\n}", "func cmdGetHostnames() ([]string, map[string]string, error) {\n\t// Sanity check conflictable values\n\tif *useHostname && *requiredSuffix != \"\" {\n\t\treturn []string{}, nil, errors.New(\"--use-hostname overrides --required-suffix, meaning it will have no effect.\")\n\t}\n\n\tvar suffix string\n\tif *useHostname {\n\t\tsuffix = *hostname\n\t} else if *requiredSuffix != \"\" {\n\t\tsuffix = *requiredSuffix\n\t}\n\n\tpairs, err := resolveIPsToHostnames()\n\tif err != nil {\n\t\treturn []string{}, nil, errors.New(fmt.Sprintln(\"Error while resolving local IPs to hostnames:\", err))\n\t}\n\n\tresultMap := make(map[string]string)\n\tmatchedIPs := []string{}\n\tfor _, pair := range pairs {\n\t\tfor _, hostname := range pair.Hostnames {\n\t\t\tif strings.HasSuffix(hostname, suffix) {\n\t\t\t\texistingValue, ok := resultMap[pair.Ip.String()]\n\t\t\t\tif ok {\n\t\t\t\t\tresultMap[pair.Ip.String()] = strings.Join([]string{existingValue, hostname}, *entryJoiner)\n\t\t\t\t} else {\n\t\t\t\t\tresultMap[pair.Ip.String()] = hostname\n\t\t\t\t\tmatchedIPs = append(matchedIPs, pair.Ip.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Debugln(\"Exiting successfully.\")\n\treturn matchedIPs, resultMap, nil\n}", "func (client DnsClient) listTsigKeys(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tsigKeys\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListTsigKeysResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (a *DefaultApiService) ListAPIKeys(consumerId string) (InlineResponse200, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t \tsuccessPayload InlineResponse200\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/consumers/{consumer_id}/key-auth\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"consumer_id\"+\"}\", fmt.Sprintf(\"%v\", consumerId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/json\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\t localVarHttpResponse, err := a.client.callAPI(r)\n\t if err != nil || localVarHttpResponse == nil {\n\t\t return successPayload, localVarHttpResponse, err\n\t }\n\t defer localVarHttpResponse.Body.Close()\n\t if localVarHttpResponse.StatusCode >= 300 {\n\t\treturn successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status)\n\t }\n\t\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t \treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}", "func getCertificates(certFile string, keyFile string) (certFilePath string, keyFilePath string) {\n\tif runtime.GOOS == \"windows\" {\n\t\tcertFilePath, _ = filepath.Abs(filepath.Join(\"https-server\", certFile))\n\t\tkeyFilePath, _ = filepath.Abs(filepath.Join(\"https-server\", keyFile))\n\t} else {\n\t\tcertFilePath, _ = filepath.Abs(certFile)\n\t\tkeyFilePath, _ = filepath.Abs(keyFile)\n\t}\n\treturn\n}", "func doGetAllIpKeys(d *db.DB, dbSpec *db.TableSpec) ([]db.Key, error) {\n\n var keys []db.Key\n\n intfTable, err := d.GetTable(dbSpec)\n if err != nil {\n return keys, err\n }\n\n keys, err = intfTable.GetKeys()\n log.Infof(\"Found %d INTF table keys\", len(keys))\n return keys, err\n}", "func (svc *SSHKeysService) List(ctx context.Context, prj string) ([]SSHKey, *http.Response, error) {\n\tret := make([]SSHKey, 0)\n\tresp, err := svc.client.resourceList(ctx, projectSSHKeysPath(prj), &ret)\n\treturn ret, resp, err\n}", "func (c *ChatClient) recoverKeysFromCacheKey(key string) (*sphinx.PublicKey, *sphinx.PublicKey) {\n\t// due to both keys having same and constant length, we can just split the key in half\n\t// and due to it being in base64, hence containing only ASCII, we don't need to bother with runes and UTF8 encoding\n\tbKey := []byte(key)\n\tkey1 := string(bKey[:len(bKey)/2])\n\tkey2 := string(bKey[len(bKey)/2:])\n\n\tdecodedKey1, err := base64.URLEncoding.DecodeString(key1)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\tdecodedKey2, err := base64.URLEncoding.DecodeString(key2)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\treturn utils.KeysFromBytes(decodedKey1, decodedKey2)\n}", "func (m *ApplicationResource) ListApplicationKeys(ctx context.Context, appId string) ([]*JsonWebKey, *Response, error) {\n\turl := fmt.Sprintf(\"/api/v1/apps/%v/credentials/keys\", appId)\n\n\trq := m.client.CloneRequestExecutor()\n\n\treq, err := rq.WithAccept(\"application/json\").WithContentType(\"application/json\").NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar jsonWebKey []*JsonWebKey\n\n\tresp, err := rq.Do(ctx, req, &jsonWebKey)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn jsonWebKey, resp, nil\n}", "func (a *SubAccountApiService) ListSubAccountKeys(ctx context.Context, userId int32) ([]SubAccountKey, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []SubAccountKey\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/sub_accounts/{user_id}/keys\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"user_id\"+\"}\", url.QueryEscape(parameterToString(userId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tif ctx.Value(ContextGateAPIV4) == nil {\n\t\t// for compatibility, set configuration key and secret to context if ContextGateAPIV4 value is not present\n\t\tctx = context.WithValue(ctx, ContextGateAPIV4, GateAPIV4{\n\t\t\tKey: a.client.cfg.Key,\n\t\t\tSecret: a.client.cfg.Secret,\n\t\t})\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status + \", \" + string(localVarBody),\n\t\t}\n\t\tvar gateErr GateAPIError\n\t\tif e := a.client.decode(&gateErr, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\")); e == nil && gateErr.Label != \"\" {\n\t\t\tgateErr.APIError = newErr\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, gateErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *Client) GetEncryptionKeys(params *GetEncryptionKeysParams) (*GetEncryptionKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetEncryptionKeysParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getEncryptionKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/platform_resources/encryption_keys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetEncryptionKeysReader{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.(*GetEncryptionKeysOK), nil\n\n}", "func GetSSHKeys(username string) string {\n\n\tproviders := map[string]string{\n\t\t\"Github\": \"https://github.com/%s.keys\",\n\t\t\"Gitlab\": \"https://gitlab.com/%s.keys\",\n\t}\n\n\tfoundKeys := \"\"\n\tfor provider, url := range providers {\n\t\turl = fmt.Sprintf(url, username)\n\t\tkeys := getURLContent(url)\n\t\tif len(keys) > 0 {\n\t\t\tfoundKeys += fmt.Sprintf(\"\\n# %s (%s):\\n%s\", username, provider, keys)\n\t\t}\n\t}\n\n\treturn foundKeys\n\n}", "func (r *FileSSLKeyResource) ListAll() (*FileSSLKeyConfigList, error) {\n\tvar list FileSSLKeyConfigList\n\tif err := r.c.ReadQuery(BasePath+FileSSLKeyEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (a *LocalKeyAgent) checkHostCertificateForClusters(clusters ...string) func(key ssh.PublicKey, addr string) bool {\n\treturn func(key ssh.PublicKey, addr string) bool {\n\t\t// Check the local cache (where all Teleport CAs are placed upon login) to\n\t\t// see if any of them match.\n\n\t\tvar keys []ssh.PublicKey\n\t\tfor _, cluster := range clusters {\n\t\t\tkey, err := a.keyStore.GetKnownHostKeys(cluster)\n\t\t\tif err != nil {\n\t\t\t\ta.log.Errorf(\"Unable to fetch certificate authorities: %v.\", err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tkeys = append(keys, key...)\n\n\t\t}\n\t\tfor i := range keys {\n\t\t\tif sshutils.KeysEqual(key, keys[i]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// If this certificate was not seen before, prompt the user essentially\n\t\t// treating it like a key.\n\t\terr := a.checkHostKey(addr, nil, key)\n\t\treturn err == nil\n\t}\n}", "func (client OperationsClient) ListKeys(ctx context.Context) (result *ListKeyResponse, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, \"ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\t/* \t\t\tif result.olr.Response.Response != nil {\n\t\t\t\tsc = result.olr.Response.Response.StatusCode\n\t\t\t} */\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.preparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.sender(req)\n\tif err != nil {\n\t\t// result.olr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.responder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func GetKeys(keyURL string) (tokens map[string]interface{}, maxAge int64, err error) {\n\n\t// r, err := myClient.Get(keyURL)\n\t// if err != nil {\n\t// \treturn tokens, maxAge, err\n\t// }\n\t// defer r.Body.Close()\n\n\t// maxAge, err = extractMaxAge(r.Header.Get(HeaderCacheControl))\n\t// if err != nil {\n\t// \treturn tokens, maxAge, err\n\t// }\n\n\t// err = json.NewDecoder(r.Body).Decode(&tokens)\n\n\treturn tokens, maxAge, err\n}", "func (a *Client) ListKeys(params *ListKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListKeysParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/runtime_config/mutable_keys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ListKeysReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListKeysOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for listKeys: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (b *B2) ListKeys(maxKeyCount int64, startApplicationKeyId string) (*ApplicationKeys, error) {\n\tvar (\n\t\turl = fmt.Sprintf(\"%s/b2api/v1/b2_list_keys\", b.auth.ApiUrl)\n\t\trequestBody = &struct {\n\t\t\tAccountId string `json:\"accountId\"`\n\t\t\tMaxKeyCount int64 `json:\"maxKeyCount,omitempty\"`\n\t\t\tStartApplicationKeyId string `json:\"startApplicationKeyId,omitempty\"`\n\t\t}{b.auth.AccountId, maxKeyCount, startApplicationKeyId}\n\t\tresponseBody = &ApplicationKeys{}\n\t)\n\n\tresponse, err := b.makeAuthedRequest(url, requestBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\tcase response.StatusCode == 200:\n\t\tif err = unmarshalResponseBody(response, responseBody); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn responseBody, nil\n\tcase response.StatusCode == 400 || response.StatusCode == 401:\n\t\treturn nil, handleErrorResponse(response)\n\tdefault:\n\t\treturn nil, handleUnknownResponse(response)\n\t}\n}", "func (a *HyperflexApiService) GetHyperflexKeyEncryptionKeyListExecute(r ApiGetHyperflexKeyEncryptionKeyListRequest) (*HyperflexKeyEncryptionKeyResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexKeyEncryptionKeyResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.GetHyperflexKeyEncryptionKeyList\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/KeyEncryptionKeys\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif r.filter != nil {\n\t\tlocalVarQueryParams.Add(\"$filter\", parameterToString(*r.filter, \"\"))\n\t}\n\tif r.orderby != nil {\n\t\tlocalVarQueryParams.Add(\"$orderby\", parameterToString(*r.orderby, \"\"))\n\t}\n\tif r.top != nil {\n\t\tlocalVarQueryParams.Add(\"$top\", parameterToString(*r.top, \"\"))\n\t}\n\tif r.skip != nil {\n\t\tlocalVarQueryParams.Add(\"$skip\", parameterToString(*r.skip, \"\"))\n\t}\n\tif r.select_ != nil {\n\t\tlocalVarQueryParams.Add(\"$select\", parameterToString(*r.select_, \"\"))\n\t}\n\tif r.expand != nil {\n\t\tlocalVarQueryParams.Add(\"$expand\", parameterToString(*r.expand, \"\"))\n\t}\n\tif r.apply != nil {\n\t\tlocalVarQueryParams.Add(\"$apply\", parameterToString(*r.apply, \"\"))\n\t}\n\tif r.count != nil {\n\t\tlocalVarQueryParams.Add(\"$count\", parameterToString(*r.count, \"\"))\n\t}\n\tif r.inlinecount != nil {\n\t\tlocalVarQueryParams.Add(\"$inlinecount\", parameterToString(*r.inlinecount, \"\"))\n\t}\n\tif r.at != nil {\n\t\tlocalVarQueryParams.Add(\"at\", parameterToString(*r.at, \"\"))\n\t}\n\tif r.tags != nil {\n\t\tlocalVarQueryParams.Add(\"tags\", parameterToString(*r.tags, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/csv\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (c APIClient) GetApikeys() ([]Apikey, error) {\n\tvar apikeys []Apikey\n\t_, err := c.doHTTPUnmarshal(\"GET\", \"https://api.nsone.net/v1/account/apikeys\", nil, &apikeys)\n\treturn apikeys, err\n}", "func (client *WebAppsClient) listHostKeysSlotHandleResponse(resp *http.Response) (WebAppsListHostKeysSlotResponse, error) {\n\tresult := WebAppsListHostKeysSlotResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.HostKeys); err != nil {\n\t\treturn WebAppsListHostKeysSlotResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}", "func (s *Client) GetSSLCertificates(appName string) ([]Certificate, error) {\n\tvar res []Certificate\n\treturn res, s.Get(&res, fmt.Sprintf(\"/apps/%s/sni-endpoints\", appName), &ListRange{})\n}", "func genKeys(dsName string, ksk bool, ttl time.Duration, tld bool) (string, string, *tc.DNSSECKeyDSRecordV11, error) {\n\tbits := 1024\n\tflags := 256\n\talgorithm := dns.RSASHA1 // 5 - http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml\n\tprotocol := 3\n\n\tif ksk {\n\t\tflags |= 1\n\t\tbits *= 2\n\t}\n\n\t// Note: currently, the Router appears to hard-code this in what it generates for the DS record (or at least the \"Publish this\" log message).\n\t// DO NOT change this, without verifying the Router works correctly with this digest/type, and specifically with the text generated by MakeDSRecordText inserted in the parent resolver.\n\tdigestType := dns.SHA256\n\n\tdnskey := dns.DNSKEY{\n\t\tHdr: dns.RR_Header{\n\t\t\tName: dsName,\n\t\t\tRrtype: dns.TypeDNSKEY,\n\t\t\tClass: dns.ClassINET,\n\t\t\tTtl: uint32(ttl / time.Second),\n\t\t},\n\t\tFlags: uint16(flags),\n\t\tProtocol: uint8(protocol),\n\t\tAlgorithm: algorithm,\n\t}\n\n\tpriKey, err := dnskey.Generate(bits)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, errors.New(\"error generating DNS key: \" + err.Error())\n\t}\n\n\tpriKeyStr := dnskey.PrivateKeyString(priKey) // BIND9 private-key-file format; cooresponds to Perl Net::DNS::SEC::Private->generate_rsa.dump_rsa_priv\n\tpriKeyStrBase64 := base64.StdEncoding.EncodeToString([]byte(priKeyStr))\n\n\tpubKeyStr := dnskey.String() // RFC1035 single-line zone file format; cooresponds to Perl Net::DNS::RR.plain\n\tpubKeyStrBase64 := base64.StdEncoding.EncodeToString([]byte(pubKeyStr))\n\n\tkeyDS := (*tc.DNSSECKeyDSRecordV11)(nil)\n\tif ksk && tld {\n\t\tdsRecord := dnskey.ToDS(digestType)\n\t\tif dsRecord == nil {\n\t\t\treturn \"\", \"\", nil, fmt.Errorf(\"creating DS record from DNSKEY record: converting dnskey %++v to DS failed\", dnskey)\n\t\t}\n\t\tkeyDS = &tc.DNSSECKeyDSRecordV11{Algorithm: int64(dsRecord.Algorithm), DigestType: int64(dsRecord.DigestType), Digest: dsRecord.Digest}\n\t}\n\n\treturn pubKeyStrBase64, priKeyStrBase64, keyDS, nil\n}", "func LookupDomainKey(selector string, parentDomain string) ([]byte, error) {\n\tselector = strings.ToLower(selector)\n\tnonce := dnsNonce(nonceStdSize)\n\tdomain := fmt.Sprintf(\"_%s.%s.%s.%s\", nonce, selector, domainKeyMsg, parentDomain)\n\n\ttxt, err := dnsLookup(domain)\n\tif err != nil {\n\t\t// {{if .Debug}}\n\t\tlog.Printf(\"Error fetching server certificate %v\", err)\n\t\t// {{end}}\n\t\treturn nil, err\n\t}\n\tcertPEM, err := base64.RawStdEncoding.DecodeString(txt)\n\tif err != nil {\n\t\t// {{if .Debug}}\n\t\tlog.Printf(\"Error decoding certificate %v\", err)\n\t\t// {{end}}\n\t\treturn nil, err\n\t}\n\treturn certPEM, nil\n}", "func SSHKey(i interface{}, k string) (warnings []string, errors []error) {\n\tv, ok := i.(string)\n\tif !ok {\n\t\treturn nil, []error{fmt.Errorf(\"expected type of %q to be string\", k)}\n\t}\n\n\tif strings.TrimSpace(v) == \"\" {\n\t\treturn nil, []error{fmt.Errorf(\"expected %q to not be an empty string or whitespace\", k)}\n\t}\n\n\tkeyParts := strings.Fields(v)\n\tif len(keyParts) > 1 {\n\t\tbyteStr, err := base64.StdEncoding.DecodeString(keyParts[1])\n\t\tif err != nil {\n\t\t\treturn nil, []error{fmt.Errorf(\"decoding %q for public key data\", k)}\n\t\t}\n\t\tpubKey, err := ssh.ParsePublicKey(byteStr)\n\t\tif err != nil {\n\t\t\treturn nil, []error{fmt.Errorf(\"parsing %q as a public key object\", k)}\n\t\t}\n\n\t\tif pubKey.Type() != ssh.KeyAlgoRSA {\n\t\t\treturn nil, []error{fmt.Errorf(\"- the provided %s SSH key is not supported. Only RSA SSH keys are supported by Azure\", pubKey.Type())}\n\t\t} else {\n\t\t\trsaPubKey, ok := pubKey.(ssh.CryptoPublicKey).CryptoPublicKey().(*rsa.PublicKey)\n\t\t\tif !ok {\n\t\t\t\treturn nil, []error{fmt.Errorf(\"- could not retrieve the RSA public key from the SSH public key\")}\n\t\t\t}\n\t\t\trsaPubKeyBits := rsaPubKey.Size() * 8\n\t\t\tif rsaPubKeyBits < 2048 {\n\t\t\t\treturn nil, []error{fmt.Errorf(\"- the provided RSA SSH key has %d bits. Only ssh-rsa keys with 2048 bits or higher are supported by Azure\", rsaPubKeyBits)}\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn nil, []error{fmt.Errorf(\"%q is not a complete SSH2 Public Key\", k)}\n\t}\n\n\treturn warnings, errors\n}", "func (client *KeyVaultClient) getKeysHandleResponse(resp *http.Response) (KeyVaultClientGetKeysResponse, error) {\n\tresult := KeyVaultClientGetKeysResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.KeyListResult); err != nil {\n\t\treturn KeyVaultClientGetKeysResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *WebAppsClient) listHostNameBindingsCreateRequest(ctx context.Context, resourceGroupName string, name string, options *WebAppsListHostNameBindingsOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hostNameBindings\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (s *AccountsService) ListSSHKeys(accountID string) (*[]SSHKeyInfo, *Response, error) {\n\tu := fmt.Sprintf(\"accounts/%s/sshkeys\", accountID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new([]SSHKeyInfo)\n\tresp, err := s.client.Do(req, v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func getHostKey(fn string) (ssh.Signer, error) {\n\t/* Read the key from the file */\n\tbs, err := ioutil.ReadFile(fn)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\t/* Parse it */\n\treturn ssh.ParsePrivateKey(bs)\n}", "func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error {\n\tcert, ok := key.(*Certificate)\n\tif !ok {\n\t\tif c.HostKeyFallback != nil {\n\t\t\treturn c.HostKeyFallback(addr, remote, key)\n\t\t}\n\t\treturn errors.New(\"ssh: non-certificate host key\")\n\t}\n\tif cert.CertType != HostCert {\n\t\treturn fmt.Errorf(\"ssh: certificate presented as a host key has type %d\", cert.CertType)\n\t}\n\tif !c.IsHostAuthority(cert.SignatureKey, addr) {\n\t\treturn fmt.Errorf(\"ssh: no authorities for hostname: %v\", addr)\n\t}\n\n\thostname, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Pass hostname only as principal for host certificates (consistent with OpenSSH)\n\treturn c.CheckCert(hostname, cert)\n}", "func ExampleTopicsClient_ListKeys() {\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\tclientFactory, err := armservicebus.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewTopicsClient().ListKeys(ctx, \"Default-ServiceBus-WestUS\", \"sdk-Namespace8408\", \"sdk-Topics2075\", \"sdk-Authrules5067\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.AccessKeys = armservicebus.AccessKeys{\n\t// \tKeyName: to.Ptr(\"sdk-AuthRules-4310\"),\n\t// \tPrimaryConnectionString: to.Ptr(\"Endpoint=sb://sdk-namespace-6261.servicebus.windows-int.net/;SharedAccessKeyName=sdk-AuthRules-4310;SharedAccessKey=#############################################;EntityPath=sdk-Topics-1984\"),\n\t// \tPrimaryKey: to.Ptr(\"#############################################\"),\n\t// \tSecondaryConnectionString: to.Ptr(\"Endpoint=sb://sdk-namespace-6261.servicebus.windows-int.net/;SharedAccessKeyName=sdk-AuthRules-4310;SharedAccessKey=#############################################;EntityPath=sdk-Topics-1984\"),\n\t// \tSecondaryKey: to.Ptr(\"#############################################\"),\n\t// }\n}", "func (s *RedisSession) GetKeys(pattern string) ([]string, error) {\r\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second*10))\r\n\tdefer cancel()\r\n\r\n\tc, err := s.getClient()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\t// only list keys with prefix for this app\r\n\tkeys, err := c.Keys(ctx, s.config.KeyPrefix+pattern).Result()\r\n\ts.logMsg(\"cache.GetKeys\", \"'%s' result: %v\", pattern, keys)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn keys, nil\r\n}", "func GetAllKeysForReplication(ctx context.Context, db *sql.DB) ([][]byte, error) {\n\tvar closerr error\n\tvar keys [][]byte\n\n\tctx, cancel := context.WithDeadline(ctx, time.Now().Add(3*time.Second))\n\tdefer cancel()\n\n\tquery := \"SELECT key FROM keys WHERE replication <= ?\"\n\trows, err := db.QueryContext(ctx, query, time.Now())\n\tif err != nil {\n\t\treturn [][]byte{}, errors.Errorf(\"could not retrieve keys: %w\", err).WithField(\"query\", query)\n\t}\n\n\tfor rows.Next() {\n\t\tvar key string\n\t\tif err := rows.Scan(&key); err != nil {\n\t\t\t// Check for a scan error.\n\t\t\t// Query rows will be closed with defer.\n\t\t\treturn [][]byte{}, errors.Errorf(\"could not scan columns: %w\", err)\n\t\t}\n\t\tkeys = append(keys, []byte(key))\n\t}\n\n\t// If the database is being written to ensure to check for Close\n\t// errors that may be returned from the driver. The query may\n\t// encounter an auto-commit error and be forced to rollback changes.\n\tif err := rows.Close(); err != nil {\n\t\treturn [][]byte{}, errors.Errorf(\"could not close the Rows: %w\", err)\n\t}\n\n\t// Rows.Err will report the last error encountered by Rows.Scan.\n\tif err := rows.Err(); err != nil {\n\t\treturn [][]byte{}, errors.Errorf(\"could not scann rows: %w\", err)\n\t}\n\n\treturn keys, closerr\n}", "func (hg *HostGroup) GetHostProducts(ctx context.Context, hostName string) ([]HostProductInfo, []byte, error) {\n\tin := []byte(fmt.Sprintf(`{\"strHostName\": \"%s\"}`, hostName))\n\tvar out getHostProductsResponse\n\traw, err := hg.client.PostInOut(ctx, \"/api/v1.0/HostGroup.GetHostProducts\", in, &out)\n\tvar products []HostProductInfo\n\tfor name, v1 := range out.PxgRetVal {\n\t\tfor version, v2 := range v1.Value {\n\t\t\tv2.HostProductInfo.Name = name\n\t\t\tv2.HostProductInfo.Version = version\n\t\t\tproducts = append(products, v2.HostProductInfo)\n\t\t}\n\t}\n\treturn products, raw, err\n}", "func (e *EtcdClientCert) PrivateKeyPath() string { return path.Join(e.BaseDir, etcdClientKeyFileName) }", "func loadCertFiles(ctx context.Context, certsDir string) ([]hostConfig, error) {\n\tfs, err := os.ReadDir(certsDir)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\thosts := make([]hostConfig, 1)\n\tfor _, f := range fs {\n\t\tif f.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(f.Name(), \".crt\") {\n\t\t\thosts[0].caCerts = append(hosts[0].caCerts, filepath.Join(certsDir, f.Name()))\n\t\t}\n\t\tif strings.HasSuffix(f.Name(), \".cert\") {\n\t\t\tvar pair [2]string\n\t\t\tcertFile := f.Name()\n\t\t\tpair[0] = filepath.Join(certsDir, certFile)\n\t\t\t// Check if key also exists\n\t\t\tkeyFile := filepath.Join(certsDir, certFile[:len(certFile)-5]+\".key\")\n\t\t\tif _, err := os.Stat(keyFile); err == nil {\n\t\t\t\tpair[1] = keyFile\n\t\t\t} else if !os.IsNotExist(err) {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\thosts[0].clientPairs = append(hosts[0].clientPairs, pair)\n\t\t}\n\t}\n\treturn hosts, nil\n}", "func ComputeHosts(routeHostnames []string, listenerHostname *string) []string {\n\tvar listenerHostnameVal string\n\tif listenerHostname != nil {\n\t\tlistenerHostnameVal = *listenerHostname\n\t}\n\n\t// No route hostnames specified: use the listener hostname if specified,\n\t// or else match all hostnames.\n\tif len(routeHostnames) == 0 {\n\t\tif len(listenerHostnameVal) > 0 {\n\t\t\treturn []string{listenerHostnameVal}\n\t\t}\n\n\t\treturn []string{allHosts}\n\t}\n\n\tvar hostnames []string\n\n\tfor i := range routeHostnames {\n\t\trouteHostname := routeHostnames[i]\n\n\t\tswitch {\n\t\t// No listener hostname: use the route hostname.\n\t\tcase len(listenerHostnameVal) == 0:\n\t\t\thostnames = append(hostnames, routeHostname)\n\n\t\t// Listener hostname matches the route hostname: use it.\n\t\tcase listenerHostnameVal == routeHostname:\n\t\t\thostnames = append(hostnames, routeHostname)\n\n\t\t// Listener has a wildcard hostname: check if the route hostname matches.\n\t\tcase strings.HasPrefix(listenerHostnameVal, allHosts):\n\t\t\tif hostnameMatchesWildcardHostname(routeHostname, listenerHostnameVal) {\n\t\t\t\thostnames = append(hostnames, routeHostname)\n\t\t\t}\n\n\t\t// Route has a wildcard hostname: check if the listener hostname matches.\n\t\tcase strings.HasPrefix(routeHostname, allHosts):\n\t\t\tif hostnameMatchesWildcardHostname(listenerHostnameVal, routeHostname) {\n\t\t\t\thostnames = append(hostnames, listenerHostnameVal)\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Strings(hostnames)\n\treturn hostnames\n}", "func (client ManagementClient) GetLocationByHostName() (result Location, err error) {\n\treq, err := client.GetLocationByHostNamePreparer()\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetLocationByHostName\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetLocationByHostNameSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetLocationByHostName\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetLocationByHostNameResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"intune.ManagementClient\", \"GetLocationByHostName\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (ks *KeyStore) HardwareListKeys(session pkcs11.SessionHandle) (map[string]common.HardwareSlot, error) {\n\tkeys := make(map[string]common.HardwareSlot)\n\n\tattrTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, []byte{0}),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VALUE, []byte{0}),\n\t}\n\n\tobjs, err := ks.listObjects(session)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(objs) == 0 {\n\t\treturn nil, common.ErrNoKeysFound{HSM: name}\n\t}\n\tlogrus.Debugf(\"Found %d objects matching list filters\", len(objs))\n\tfor _, obj := range objs {\n\t\tvar (\n\t\t\tcert *x509.Certificate\n\t\t\tslot []byte\n\t\t)\n\t\tattr, err := pkcs11Ctx.GetAttributeValue(session, obj, attrTemplate)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"Failed to get Attribute for: %v\", obj)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, a := range attr {\n\t\t\tif a.Type == pkcs11.CKA_ID {\n\t\t\t\tslot = a.Value\n\t\t\t}\n\t\t\tif a.Type == pkcs11.CKA_VALUE {\n\t\t\t\tcert, err = x509.ParseCertificate(a.Value)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !data.ValidRole(data.RoleName(cert.Subject.CommonName)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif cert == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar ecdsaPubKey *ecdsa.PublicKey\n\t\tswitch cert.PublicKeyAlgorithm {\n\t\tcase x509.ECDSA:\n\t\t\tecdsaPubKey = cert.PublicKey.(*ecdsa.PublicKey)\n\t\tdefault:\n\t\t\tlogrus.Infof(\"Unsupported x509 PublicKeyAlgorithm: %d\", cert.PublicKeyAlgorithm)\n\t\t\tcontinue\n\t\t}\n\n\t\tpubBytes, err := x509.MarshalPKIXPublicKey(ecdsaPubKey)\n\t\tif err != nil {\n\t\t\tlogrus.Debugf(\"Failed to Marshal public key\")\n\t\t\tcontinue\n\t\t}\n\t\tid := data.NewECDSAPublicKey(pubBytes).ID()\n\t\tkeys[id] = common.HardwareSlot{\n\t\t\tRole: data.RoleName(cert.Subject.CommonName),\n\t\t\tSlotID: slot,\n\t\t\tKeyID: id,\n\t\t}\n\t}\n\treturn keys, err\n}", "func (m *AccountsClientMock) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountListKeysResult, rerr *retry.Error) {\n\targs := m.Called(resourceGroupName, accountName)\n\tif args.Error(1) != nil {\n\t\treturn storage.AccountListKeysResult{}, &retry.Error{RawError: args.Error(1)}\n\t}\n\treturn storage.AccountListKeysResult{}, nil\n}", "func (d *database) getKeys(sender ...string) (s []keypair.KeyPair, err error) {\n\ts = []keypair.KeyPair{}\n\n\tvar query string\n\tif len(sender) > 0 {\n\t\tquery = fmt.Sprintf(\"SELECT letter_content FROM letters WHERE opened == 1 AND letter_purpose == '%s' AND sender == '%s' ORDER BY time DESC;\", purpose.ShareKey, sender[0])\n\t} else {\n\t\tquery = fmt.Sprintf(\"SELECT letter_content FROM letters WHERE opened == 1 AND letter_purpose == '%s' ORDER BY time DESC;\", purpose.ShareKey)\n\t}\n\tlogger.Log.Debug(query)\n\trows, err := d.db.Query(query)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"getKeys\")\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\t// loop through rows\n\tfor rows.Next() {\n\t\tvar mKeyPair string\n\t\terr = rows.Scan(&mKeyPair)\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"getKeys\")\n\t\t\treturn\n\t\t}\n\n\t\tvar kp keypair.KeyPair\n\t\terr = json.Unmarshal([]byte(mKeyPair), &kp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\ts = append(s, kp)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"getKeys\")\n\t}\n\treturn\n}", "func hostsFunc(ctx *TemplateContext) func(...string) (interface{}, error) {\n\treturn func(s ...string) (interface{}, error) {\n\t\treturn ctx.GetHosts(s...)\n\t}\n}", "func ListSSHKeys() error {\n\tclient, err := NewPacketClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk, _, err := client.SSHKeys.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te := MarshallAndPrint(k)\n\treturn e\n}", "func (client *WebAppsClient) listHostNameBindingsHandleResponse(resp *http.Response) (WebAppsListHostNameBindingsResponse, error) {\n\tresult := WebAppsListHostNameBindingsResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.HostNameBindingCollection); err != nil {\n\t\treturn WebAppsListHostNameBindingsResponse{}, runtime.NewResponseError(err, resp)\n\t}\n\treturn result, nil\n}" ]
[ "0.5425132", "0.5336563", "0.5303181", "0.5217682", "0.51962817", "0.518711", "0.51473093", "0.51252294", "0.5092041", "0.50768316", "0.50609934", "0.50054747", "0.49826443", "0.4936314", "0.493125", "0.49036396", "0.4879752", "0.48282203", "0.4825235", "0.48070812", "0.4803348", "0.47958547", "0.47914135", "0.47874647", "0.47789916", "0.47582227", "0.47149187", "0.47010106", "0.4696142", "0.4695346", "0.46884125", "0.46883827", "0.46878675", "0.468212", "0.46489942", "0.46379483", "0.46302253", "0.4627029", "0.46248794", "0.45869187", "0.457242", "0.4569585", "0.45600963", "0.45587143", "0.4555723", "0.45147723", "0.4514068", "0.45045072", "0.45028493", "0.44923076", "0.44896182", "0.448681", "0.4480436", "0.44796792", "0.44759482", "0.44725022", "0.44721407", "0.44314808", "0.4423971", "0.442038", "0.44182205", "0.44029284", "0.4399317", "0.43933615", "0.43900064", "0.4389779", "0.4389567", "0.4369245", "0.43628824", "0.43620843", "0.4361914", "0.4360297", "0.4358055", "0.43528467", "0.43437397", "0.43424642", "0.4332579", "0.43175337", "0.43097007", "0.43053737", "0.42971897", "0.42969263", "0.4296366", "0.42916405", "0.4288766", "0.4283374", "0.42830008", "0.4275346", "0.42695418", "0.4268127", "0.42672056", "0.42652223", "0.4263932", "0.42613098", "0.42532492", "0.4250533", "0.4248715", "0.42479885", "0.42475644", "0.42456007" ]
0.82809246
0
GetSSLKeysByXMLID fetches the deliveryservice ssl keys by the specified xmlID.
func GetSSLKeysByXMLID(w http.ResponseWriter, r *http.Request) { inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"xmlid"}, nil) if userErr != nil || sysErr != nil { api.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr) return } defer inf.Close() if inf.Config.RiakEnabled == false { api.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New("the Riak service is unavailable"), errors.New("getting SSL keys from Riak by xml id: Riak is not configured")) return } xmlID := inf.Params["xmlid"] getSSLKeysByXMLIDHelper(xmlID, inf, w, r) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (to *Session) GetDeliveryServiceRequestByXMLID(XMLID string) ([]tc.DeliveryServiceRequest, toclientlib.ReqInf, error) {\n\treturn to.GetDeliveryServiceRequestByXMLIDWithHdr(XMLID, nil)\n}", "func GetSSLKeysByHostName(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, []string{\"hostname\"}, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\n\tif inf.Config.RiakEnabled == false {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New(\"the Riak service is unavailable\"), errors.New(\"getting SSL keys from Riak by host name: Riak is not configured\"))\n\t\treturn\n\t}\n\n\thostName := inf.Params[\"hostname\"]\n\tdomainName := \"\"\n\thostRegex := \"\"\n\tstrArr := strings.Split(hostName, \".\")\n\tln := len(strArr)\n\tif ln > 1 {\n\t\tfor i := 2; i < ln-1; i++ {\n\t\t\tdomainName += strArr[i] + \".\"\n\t\t}\n\t\tdomainName += strArr[ln-1]\n\t\thostRegex = `.*\\.` + strArr[1] + `\\..*`\n\t}\n\n\t// lookup the cdnID\n\tcdnID, ok, err := getCDNIDByDomainname(domainName, inf.Tx.Tx)\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"getting cdn id by domain name: \"+err.Error()))\n\t\treturn\n\t}\n\tif !ok {\n\t\tapi.WriteRespAlert(w, r, tc.InfoLevel, \" - a cdn does not exist for the domain: \"+domainName+\" parsed from hostname: \"+hostName)\n\t\treturn\n\t}\n\t// now lookup the deliveryservice xmlID\n\txmlID, ok, err := getXMLID(cdnID, hostRegex, inf.Tx.Tx)\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"getting xml id: \"+err.Error()))\n\t\treturn\n\t}\n\tif !ok {\n\t\tapi.WriteRespAlert(w, r, tc.InfoLevel, \" - a delivery service does not exist for a host with hostname of \"+hostName)\n\t\treturn\n\t}\n\n\tgetSSLKeysByXMLIDHelper(xmlID, inf, w, r)\n}", "func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) {\n\tkeys := make([]*GPGKey, 0, 1)\n\treturn keys, db.GetEngine(db.DefaultContext).Where(\"key_id=?\", keyID).Find(&keys)\n}", "func AddSSLKeys(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, nil, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\tif !inf.Config.RiakEnabled {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"adding SSL keys to Riak for delivery service: Riak is not configured\"))\n\t\treturn\n\t}\n\treq := tc.DeliveryServiceAddSSLKeysReq{}\n\tif err := api.Parse(r.Body, inf.Tx.Tx, &req); err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New(\"parsing request: \"+err.Error()), nil)\n\t\treturn\n\t}\n\tif userErr, sysErr, errCode := tenant.Check(inf.User, *req.DeliveryService, inf.Tx.Tx); userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tcertChain, isUnknownAuth, err := verifyCertificate(req.Certificate.Crt, \"\")\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusBadRequest, errors.New(\"verifying certificate: \"+err.Error()), nil)\n\t\treturn\n\t}\n\treq.Certificate.Crt = certChain\n\tbase64EncodeCertificate(req.Certificate)\n\tdsSSLKeys := tc.DeliveryServiceSSLKeys{\n\t\tCDN: *req.CDN,\n\t\tDeliveryService: *req.DeliveryService,\n\t\tHostname: *req.HostName,\n\t\tKey: *req.Key,\n\t\tVersion: *req.Version,\n\t\tCertificate: *req.Certificate,\n\t}\n\tif err := riaksvc.PutDeliveryServiceSSLKeysObj(dsSSLKeys, inf.Tx.Tx, inf.Config.RiakAuthOptions); err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"putting SSL keys in Riak for delivery service '\"+*req.DeliveryService+\"': \"+err.Error()))\n\t\treturn\n\t}\n\tif err := updateSSLKeyVersion(*req.DeliveryService, req.Version.ToInt64(), inf.Tx.Tx); err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"adding SSL keys to delivery service '\"+*req.DeliveryService+\"': \"+err.Error()))\n\t\treturn\n\t}\n\tif isUnknownAuth {\n\t\tapi.WriteRespAlert(w, r, tc.WarnLevel, \"WARNING: SSL keys were successfully added for '\"+*req.DeliveryService+\"', but the certificate is signed by an unknown authority and may be invalid\")\n\t\treturn\n\t}\n\tapi.WriteResp(w, r, \"Successfully added ssl keys for \"+*req.DeliveryService)\n}", "func (a *apiKeyService) GetAPIKeys(userID portainer.UserID) ([]portainer.APIKey, error) {\n\treturn a.apiKeyRepository.GetAPIKeysByUserID(userID)\n}", "func (service *Service) GetAPIKeysByUserID(userID portainer.UserID) ([]portainer.APIKey, error) {\n\tvar result = make([]portainer.APIKey, 0)\n\n\terr := service.connection.GetAll(\n\t\tBucketName,\n\t\t&portainer.APIKey{},\n\t\tfunc(obj interface{}) (interface{}, error) {\n\t\t\trecord, ok := obj.(*portainer.APIKey)\n\t\t\tif !ok {\n\t\t\t\tlog.Debug().Str(\"obj\", fmt.Sprintf(\"%#v\", obj)).Msg(\"failed to convert to APIKey object\")\n\t\t\t\treturn nil, fmt.Errorf(\"Failed to convert to APIKey object: %s\", obj)\n\t\t\t}\n\n\t\t\tif record.UserID == userID {\n\t\t\t\tresult = append(result, *record)\n\t\t\t}\n\n\t\t\treturn &portainer.APIKey{}, nil\n\t\t})\n\n\treturn result, err\n}", "func (r *FileSSLKeyResource) Get(id string) (*FileSSLKeyConfig, error) {\n\tvar item FileSSLKeyConfig\n\tif err := r.c.ReadQuery(BasePath+FileSSLKeyEndpoint, &item); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &item, nil\n}", "func GetDeliveryServiceURLSigKeys(toClient *toclient.Session, dsName string, opts *toclient.RequestOptions) (tc.URLSigKeys, toclientlib.ReqInf, error) {\n\tif opts == nil {\n\t\topts = &toclient.RequestOptions{}\n\t}\n\tresp, reqInf, err := toClient.GetDeliveryServiceURLSignatureKeys(dsName, *opts)\n\treturn resp.Response, reqInf, err\n}", "func (e *EncryptOptions) SetKeyID(keyID primitive.Binary) *EncryptOptions {\n\te.KeyID = &keyID\n\treturn e\n}", "func (to *Session) GetDeliveryServiceRequestByID(id int) ([]tc.DeliveryServiceRequest, toclientlib.ReqInf, error) {\n\treturn to.GetDeliveryServiceRequestByIDWithHdr(id, nil)\n}", "func (g *GPG) KeysById(id uint64) []openpgp.Key {\n\treturn append(g.secring.KeysById(id), g.pubring.KeysById(id)...)\n}", "func (p *PKCS11) GetKeyID() (err error) {\n findTemplate := []*pkcs11.Attribute{\n pkcs11.NewAttribute(pkcs11.CKA_ID, true), // KeyID\n pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),\n pkcs11.NewAttribute(pkcs11.CKA_PRIVATE, true),\n pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),\n }\n\n p.Ctx.FindObjectsInit(p.SessionHandle, findTemplate)\n obj, _, err := p.Ctx.FindObjects(p.SessionHandle, 1000)\n if err != nil {\n return\n }\n\n err = p.Ctx.FindObjectsFinal(p.SessionHandle)\n if err != nil {\n return\n }\n\n p.KeyID = map[int][]byte{}\n for num, objValue := range obj {\n attrs, _ := p.Ctx.GetAttributeValue(p.SessionHandle, objValue, findTemplate)\n p.KeyID[num] = attrs[0].Value\n }\n\n return\n}", "func (ce *ClientEncryption) GetKeys(ctx context.Context) (*Cursor, error) {\n\treturn ce.keyVaultColl.Find(ctx, bson.D{})\n}", "func (a *API) GetImagesByID(id string) (*ecs.DescribeImagesResponse, error) {\n\trequest := ecs.CreateDescribeImagesRequest()\n\trequest.Scheme = \"https\"\n\trequest.ImageId = id\n\treturn a.ecs.DescribeImages(request)\n}", "func (mkr *multiKeyRing) KeysById(id uint64) []openpgp.Key {\n\tfor _, kr := range mkr.keyrings {\n\t\tif keys := kr.KeysById(id); len(keys) > 0 {\n\t\t\treturn keys\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Client) GetKeys(opts map[string]string) (kl []Key, err error) {\n\n\t// First call\n\trawlist, err := c.fetchOneKeyPage(opts)\n\n\t// Empty answer\n\tif rawlist.Count == 0 {\n\t\treturn nil, fmt.Errorf(\"empty key list\")\n\t}\n\n\tvar res []Key\n\n\tres = append(res, rawlist.Results...)\n\tif rawlist.Next != \"\" {\n\t\t// We have pagination\n\t\tfor pn := getPageNum(rawlist.Next); rawlist.Next != \"\"; pn = getPageNum(rawlist.Next) {\n\t\t\topts[\"page\"] = pn\n\n\t\t\trawlist, err = c.fetchOneKeyPage(opts)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tres = append(res, rawlist.Results...)\n\t\t}\n\t}\n\tkl = res\n\treturn\n}", "func (rule L7Rule) GetDNSKeys(cookie keyvalue.Cookie, trafficType kernel.TrafficType, action interface{}) ([]*keyvalue.KeyValue, error) {\n\tvar err error\n\trep := []*keyvalue.KeyValue{}\n\tfor _, fqdn := range rule.DNS {\n\t\tkv := keyvalue.KeyValue{\n\t\t\tValue: action,\n\t\t}\n\t\tif kv.Key, err = keyvalue.NewDNSKey(\n\t\t\ttrafficType,\n\t\t\tcookie,\n\t\t\t7,\n\t\t\tfqdn,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trep = append(rep, &kv)\n\t}\n\treturn rep, nil\n}", "func GetAPIKeys(user string) ([]APIKey, error) {\n\tdbQuery := `\n\t\tSELECT key, date_created\n\t\tFROM api_keys\n\t\tWHERE user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t)`\n\trows, err := pdb.Query(dbQuery, user)\n\tif err != nil {\n\t\tlog.Printf(\"Database query failed: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tvar keys []APIKey\n\tfor rows.Next() {\n\t\tvar key string\n\t\tvar dateCreated time.Time\n\t\terr = rows.Scan(&key, &dateCreated)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error retrieving API key list: %v\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tkeys = append(keys, APIKey{Key: key, DateCreated: dateCreated})\n\t}\n\treturn keys, nil\n}", "func (instance *DSInstance) GetKeys(ctx context.Context, query *datastore.Query) ([]*datastore.Key, error) {\n\t// attempt to populate results from Datastore client\n\treturn instance.client.GetAll(ctx, query, nil)\n}", "func (kr *hybridKeyRing) KeysById(id uint64) []openpgp.Key {\n\tif keys := kr.local.KeysById(id); len(keys) > 0 {\n\t\treturn keys\n\t}\n\n\t// No keys found in local keyring, check with keyserver.\n\tel, err := kr.remoteEntitiesByID(id)\n\tif err != nil {\n\t\tsylog.Warningf(\"failed to get key material: %v\", err)\n\t\treturn nil\n\t}\n\treturn el.KeysById(id)\n}", "func (a *appsConfig) Keys(id string) (keys []string, err error) {\n\tres, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar r appConfigResponse\n\tres.JSON(&r)\n\treturn r.Ocs.Data.Data, nil\n}", "func (g *Gandi) GetDomainKeys(fqdn string) (keys []SigningKey, err error) {\n\t_, err = g.askGandi(mGET, \"domains/\"+fqdn+\"/keys\", nil, &keys)\n\treturn\n}", "func (c *Client) GetAPIKeys() ([]*APIKey, error) {\n\tmethod := http.MethodGet\n\turl := fmt.Sprintf(\n\t\t\"%s://%s:%s/keys\",\n\t\tc.masterNode.Protocol,\n\t\tc.masterNode.Host,\n\t\tc.masterNode.Port,\n\t)\n\tresp, err := c.apiCall(method, url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"retrieve of api keys failed with status code: %d\",\n\t\t\tresp.StatusCode,\n\t\t)\n\t}\n\tvar keysWrapper struct {\n\t\tKeys []*APIKey `json:\"keys\"`\n\t}\n\tif err := json.NewDecoder(resp.Body).Decode(&keysWrapper); err != nil {\n\t\treturn nil, err\n\t}\n\treturn keysWrapper.Keys, nil\n}", "func (n *newsRedisRepo) GetNewsByIDCtx(ctx context.Context, key string) (*models.NewsBase, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"newsRedisRepo.GetNewsByIDCtx\")\n\tdefer span.Finish()\n\n\tnewsBytes, err := n.redisClient.Get(ctx, key).Bytes()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"newsRedisRepo.GetNewsByIDCtx.redisClient.Get\")\n\t}\n\tnewsBase := &models.NewsBase{}\n\tif err = json.Unmarshal(newsBytes, newsBase); err != nil {\n\t\treturn nil, errors.Wrap(err, \"newsRedisRepo.GetNewsByIDCtx.json.Unmarshal\")\n\t}\n\n\treturn newsBase, nil\n}", "func (er EgressRule) GetDNSKeys(cookie keyvalue.Cookie, trafficType kernel.TrafficType, action interface{}) ([]*keyvalue.KeyValue, error) {\n\tvar err error\n\trep := []*keyvalue.KeyValue{}\n\tfor _, fqdn := range er.FQDNs {\n\t\tkv := keyvalue.KeyValue{\n\t\t\tValue: action,\n\t\t}\n\t\tif kv.Key, err = keyvalue.NewDNSKey(\n\t\t\ttrafficType,\n\t\t\tcookie,\n\t\t\t3,\n\t\t\tfqdn,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trep = append(rep, &kv)\n\t}\n\treturn rep, nil\n}", "func (c *KeyStoreClient) Get(ctx context.Context, id int32) (*KeyStore, error) {\n\treturn c.Query().Where(keystore.ID(id)).Only(ctx)\n}", "func (el EntityList) KeysById(id uint64) (keys []Key) {\n\tfor _, e := range el {\n\t\tif e.PrimaryKey.KeyId == id {\n\t\t\tvar selfSig *packet.Signature\n\t\t\tfor _, ident := range e.Identities {\n\t\t\t\tif selfSig == nil {\n\t\t\t\t\tselfSig = ident.SelfSignature\n\t\t\t\t} else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {\n\t\t\t\t\tselfSig = ident.SelfSignature\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tkeys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig})\n\t\t}\n\n\t\tfor _, subKey := range e.Subkeys {\n\t\t\tif subKey.PublicKey.KeyId == id {\n\t\t\t\tkeys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig})\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (s *LunaKeyStore) GetKeyInfo(keyID string) (trustmanager.KeyInfo, error) {\n\treturn trustmanager.KeyInfo{}, fmt.Errorf(\"Not yet implemented\")\n}", "func (k Keeper) GetCertificates(ctx sdk.Context, subject string, subjectKeyID string) (val types.Certificates, found bool) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.CertificatesKey))\n\n\tval.Identifier = types.CertificatesIdentifier{\n\t\tSubject: subject,\n\t\tSubjectKeyID: subjectKeyID,\n\t}\n\tb := store.Get(types.KeyPrefix(val.Identifier.Index()))\n\tif b == nil {\n\t\treturn val, false\n\t}\n\n\tk.cdc.MustUnmarshalBinaryBare(b, &val)\n\treturn val, true\n}", "func (a *Client) GetEncryptionKeys(params *GetEncryptionKeysParams) (*GetEncryptionKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetEncryptionKeysParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getEncryptionKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/v1/platform_resources/encryption_keys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetEncryptionKeysReader{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.(*GetEncryptionKeysOK), nil\n\n}", "func (l *Libvirt) DomainAuthorizedSshKeysGet(Dom Domain, User string, Flags uint32) (rKeys []string, err error) {\n\tvar buf []byte\n\n\targs := DomainAuthorizedSshKeysGetArgs {\n\t\tDom: Dom,\n\t\tUser: User,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(424, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Keys: []string\n\t_, err = dec.Decode(&rKeys)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c APIClient) GetApikeys() ([]Apikey, error) {\n\tvar apikeys []Apikey\n\t_, err := c.doHTTPUnmarshal(\"GET\", \"https://api.nsone.net/v1/account/apikeys\", nil, &apikeys)\n\treturn apikeys, err\n}", "func (r *FileSSLKeyResource) ListAll() (*FileSSLKeyConfigList, error) {\n\tvar list FileSSLKeyConfigList\n\tif err := r.c.ReadQuery(BasePath+FileSSLKeyEndpoint, &list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &list, nil\n}", "func (m *ServicePrincipalRiskDetection) GetKeyIds()([]string) {\n val, err := m.GetBackingStore().Get(\"keyIds\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]string)\n }\n return nil\n}", "func (o AppProjectSpecSignatureKeysOutput) KeyID() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AppProjectSpecSignatureKeys) string { return v.KeyID }).(pulumi.StringOutput)\n}", "func GetAPIKeyStore(apiKey string) (storeID int, err error) {\n\tkey := stringutil.Build(\"apikey:\", apiKey, \":storeid\")\n\tstoreID, err = GetInt(key)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"cannot get int value from Redis\")\n\t}\n\treturn\n}", "func (c *KeyStoreClient) GetX(ctx context.Context, id int32) *KeyStore {\n\tobj, err := c.Get(ctx, id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn obj\n}", "func GetKeys(pattern string) (interface{}, error) {\n\tconnect := Connect()\n\treply, err := connect.Do(\"KEYS\", pattern)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn reply, err\n}", "func (client DnsClient) ListTsigKeys(ctx context.Context, request ListTsigKeysRequest) (response ListTsigKeysResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listTsigKeys, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListTsigKeysResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListTsigKeysResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListTsigKeysResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListTsigKeysResponse\")\n\t}\n\treturn\n}", "func SysCallGetCertByID(certID int64) (*models.CertItem, error) {\n\tfor _, cert := range Certs {\n\t\tif cert.ID == certID {\n\t\t\treturn cert, nil\n\t\t}\n\t}\n\treturn nil, errors.New(\"Certificate not found\")\n}", "func (a *StartupConfigurationApiService) GetKeyStore(ctx _context.Context) ApiGetKeyStoreRequest {\n\treturn ApiGetKeyStoreRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (o *ListSSHKeysParams) WithProjectID(projectID string) *ListSSHKeysParams {\n\to.SetProjectID(projectID)\n\treturn o\n}", "func (s *GCPCKMSSeal) KeyID() string {\n\treturn s.currentKeyID.Load().(string)\n}", "func (c *ConsulClient) ListKeys(ctx context.Context, key string) ([]string, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"ConsulClient.ListKeys\")\n\tdefer span.Finish()\n\n\tregistryOperationCount.WithLabelValues(env, \"ListKeys\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"ListKeys\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\tkv, _, err := c.client.KV().List(key, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeys := []string{}\n\n\tfor _, pair := range kv {\n\t\tkeys = append(keys, pair.Key)\n\t}\n\n\treturn keys, nil\n}", "func (service *AccountService) GetAccountKeys(ctx context.Context, req *protoAccount.GetAccountKeysRequest, res *protoAccount.AccountKeysResponse) error {\n\tkeys, err := repoAccount.FindAccountKeys(service.DB, req.AccountIDs)\n\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tres.Status = constRes.Nonentity\n\t\tres.Message = \"no accounts by those IDs\"\n\tcase err != nil:\n\t\tlog.Println(\"FindAccountKeys error: \", err.Error())\n\t\tres.Status = constRes.Error\n\t\tres.Message = err.Error()\n\tdefault:\n\t\tres.Status = constRes.Success\n\t\tres.Data = &protoAccount.KeysList{\n\t\t\tKeys: keys,\n\t\t}\n\t}\n\n\treturn nil\n}", "func GetAPIKeys(client lib.Client) (apiKeys brain.APIKeys, err error) {\n\tr, err := client.BuildRequest(\"GET\", lib.BrainEndpoint, \"/api_keys?view=overview\")\n\tif err != nil {\n\t\treturn\n\t}\n\t_, _, err = r.Run(nil, &apiKeys)\n\treturn\n}", "func (a *Client) GetIamAPIKeys(params *GetIamAPIKeysParams) (*GetIamAPIKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetIamAPIKeysParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetIamAPIKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/iam/ApiKeys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetIamAPIKeysReader{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\tsuccess, ok := result.(*GetIamAPIKeysOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\tunexpectedSuccess := result.(*GetIamAPIKeysDefault)\n\treturn nil, runtime.NewAPIError(\"unexpected success response: content available as default response in error\", unexpectedSuccess, unexpectedSuccess.Code())\n}", "func (k *KMSConfig) KeyID() string {\n\treturn fmt.Sprintf(\"%x\", sha1.Sum([]byte(k.KeyPath)))\n}", "func (client IdentityClient) ListApiKeys(ctx context.Context, request ListApiKeysRequest) (response ListApiKeysResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif client.RetryPolicy() != nil {\n\t\tpolicy = *client.RetryPolicy()\n\t}\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listApiKeys, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListApiKeysResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListApiKeysResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListApiKeysResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListApiKeysResponse\")\n\t}\n\treturn\n}", "func (a *DeviceAPI) GetKeys(ctx context.Context, req *api.GetDeviceKeysRequest) (*api.GetDeviceKeysResponse, error) {\n\tvar eui lorawan.EUI64\n\tif err := eui.UnmarshalText([]byte(req.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, err.Error())\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Update, eui); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\tdk, err := a.st.GetDeviceKeys(ctx, eui)\n\tif err != nil {\n\t\treturn nil, helpers.ErrToRPCError(err)\n\t}\n\n\treturn &api.GetDeviceKeysResponse{\n\t\tDeviceKeys: &api.DeviceKeys{\n\t\t\tDevEui: eui.String(),\n\t\t\tAppKey: dk.AppKey.String(),\n\t\t\tNwkKey: dk.NwkKey.String(),\n\t\t\tGenAppKey: dk.GenAppKey.String(),\n\t\t},\n\t}, nil\n}", "func (s *RedisSession) GetKeys(pattern string) ([]string, error) {\r\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second*10))\r\n\tdefer cancel()\r\n\r\n\tc, err := s.getClient()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\t// only list keys with prefix for this app\r\n\tkeys, err := c.Keys(ctx, s.config.KeyPrefix+pattern).Result()\r\n\ts.logMsg(\"cache.GetKeys\", \"'%s' result: %v\", pattern, keys)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn keys, nil\r\n}", "func (kc KVSClient) ListKeys(ctx context.Context, key string) (res responses.KeysResponse, err errors.EdgeX) {\n\tpath := utils.EscapeAndJoinPath(common.ApiKVSRoute, common.Key, key)\n\tqueryParams := url.Values{}\n\tqueryParams.Set(common.KeyOnly, common.ValueTrue)\n\terr = utils.GetRequest(ctx, &res, kc.baseUrl, path, queryParams)\n\tif err != nil {\n\t\treturn res, errors.NewCommonEdgeXWrapper(err)\n\t}\n\treturn res, nil\n}", "func GetPackageRowsByID(ctx context.Context, db SQLHandle, keys ...interface{}) (rows PackageRows, err error) {\n\trows = make(PackageRows, 0, len(keys))\n\tif _, err = queryWithJSONArgs(ctx, db, rows.ReceiveRows, SQLGetPackageRowsByID, Keys(keys)); err != nil {\n\t\treturn nil, formatError(\"GetPackageRowsByID\", err)\n\t}\n\treturn rows, nil\n}", "func (s CertStore) GetBySubjectId(keyId string) (res Cert, err error) {\n\tbThumb, err := hex.DecodeString(keyId)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar hashBlob C.CRYPT_HASH_BLOB\n\thashBlob.cbData = C.DWORD(len(bThumb))\n\tbThumbPtr := C.CBytes(bThumb)\n\tdefer C.free(bThumbPtr)\n\thashBlob.pbData = (*C.BYTE)(bThumbPtr)\n\tif res.pCert = s.getCert(C.CERT_FIND_KEY_IDENTIFIER, unsafe.Pointer(&hashBlob)); res.pCert == nil {\n\t\terr = getErr(\"Error looking up certificate by subject key id\")\n\t\treturn\n\t}\n\treturn\n}", "func (a *Client) GetSitesIDClients(params *GetSitesIDClientsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSitesIDClientsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSitesIDClientsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"getSitesIdClients\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/sites/{id}/clients\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetSitesIDClientsReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetSitesIDClientsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getSitesIdClients: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (a API) GetCasesBySiteID(siteID, lookback int) ([]*services.CaseDTO, error) {\n\tresponse := &caseEnvelope{}\n\taction := \"http://webservices.blackbaud.com/clarify/case/GetCasesByClarifySiteId\"\n\tbody := \"<GetCasesByClarifySiteId xmlns=\\\"http://webservices.blackbaud.com/clarify/case/\\\">\" +\n\t\tfmt.Sprintf(\"<siteId>%d</siteId>\", siteID) +\n\t\tfmt.Sprintf(\"<daysBeforeToday>%d</daysBeforeToday>\", lookback) +\n\t\t\"<condition></condition><family></family>\" +\n\t\t\"</GetCasesByClarifySiteId>\"\n\n\tdata, err := a.Relay.CallEndpoint(caseEndpoint, action, body)\n\n\tif err != nil {\n\t\treturn response.Body.Response.Message.CasesElem.CaseSlice, err\n\t}\n\n\terr = xml.Unmarshal(data, response)\n\n\treturn response.Body.Response.Message.CasesElem.CaseSlice, err\n}", "func (d *Driver) getKeys(ctx context.Context, prefix string, sortResults bool) ([]string, error) {\n\twatcher, err := d.kv.Watch(prefix, nats.MetaOnly(), nats.IgnoreDeletes(), nats.Context(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\terr := watcher.Stop()\n\t\tif err != nil {\n\t\t\tlogrus.Warnf(\"failed to stop %s getKeys watcher\", prefix)\n\t\t}\n\t}()\n\n\tvar keys []string\n\t// grab all matching keys immediately\n\tfor entry := range watcher.Updates() {\n\t\tif entry == nil {\n\t\t\tbreak\n\t\t}\n\t\tkeys = append(keys, entry.Key())\n\t}\n\n\tif sortResults {\n\t\tsort.Strings(keys)\n\t}\n\n\treturn keys, nil\n}", "func (client *Client) GetKeys(url string) []string {\n\tresp, err := http.Get(url)\n\tif err != nil || resp.StatusCode != 200 {\n\t\tvar empty []string\n\t\treturn empty\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tvar empty []string\n\t\treturn empty\n\t}\n\tresponseString := string(body)\n\n\treturn strings.Split(responseString, \"\\n\")\n}", "func (orm ksORM) GetEncryptedV1CSAKeys() (retrieved []csakey.Key, err error) {\n\treturn retrieved, orm.q.Select(&retrieved, `SELECT * FROM csa_keys`)\n}", "func (_m *TranslationKeyStore) GetClientIDSymmetricKeys(id []byte) ([][]byte, error) {\n\tret := _m.Called(id)\n\n\tvar r0 [][]byte\n\tif rf, ok := ret.Get(0).(func([]byte) [][]byte); ok {\n\t\tr0 = rf(id)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([][]byte)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]byte) error); ok {\n\t\tr1 = rf(id)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *PooledWrapper) KeyId(ctx context.Context) (string, error) {\n\treturn m.encryptor().KeyId(ctx)\n}", "func (client ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServicesClient.ListTestKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.ListTestKeysPreparer(ctx, resourceGroupName, serviceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListTestKeysSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListTestKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func GetKeys() (keys []string, err error) {\n\treturn DefaultCache.GetKeys()\n}", "func (o InventoryDestinationBucketEncryptionSseKmsOutput) KeyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v InventoryDestinationBucketEncryptionSseKms) string { return v.KeyId }).(pulumi.StringOutput)\n}", "func (symmetricKey *SymmetricKey) GetKeyID() string {\n\tsymmetricKey.mutex.RLock()\n\tdefer symmetricKey.mutex.RUnlock()\n\treturn symmetricKey.KeyID\n}", "func (ts *TaskService) GetTestCasesByTaskID(ctx context.Context, id int) ([]models.TestCase, error) {\n\treturn ts.TaskRepository.GetTestCasesByTaskID(ctx, id)\n}", "func ChildCertificatesKey(\n\tissuer string,\n\tauthorityKeyID string,\n) []byte {\n\tvar key []byte\n\n\tissuerBytes := []byte(issuer)\n\tkey = append(key, issuerBytes...)\n\tkey = append(key, []byte(\"/\")...)\n\n\tauthorityKeyIDBytes := []byte(authorityKeyID)\n\tkey = append(key, authorityKeyIDBytes...)\n\tkey = append(key, []byte(\"/\")...)\n\n\treturn key\n}", "func GetKeys(keyURL string) (tokens map[string]interface{}, maxAge int64, err error) {\n\n\t// r, err := myClient.Get(keyURL)\n\t// if err != nil {\n\t// \treturn tokens, maxAge, err\n\t// }\n\t// defer r.Body.Close()\n\n\t// maxAge, err = extractMaxAge(r.Header.Get(HeaderCacheControl))\n\t// if err != nil {\n\t// \treturn tokens, maxAge, err\n\t// }\n\n\t// err = json.NewDecoder(r.Body).Decode(&tokens)\n\n\treturn tokens, maxAge, err\n}", "func (s *Services) GetKey(ctx context.Context, keyID string) *KeyConfig {\n\treturn s.Access.GetKeyConfig(keyID)\n}", "func (c *CoinInfoClient) QueryKeys(ci *CoinInfo) *KeyStoreQuery {\n\tquery := &KeyStoreQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := ci.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(coininfo.Table, coininfo.FieldID, id),\n\t\t\tsqlgraph.To(keystore.Table, keystore.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, coininfo.KeysTable, coininfo.KeysColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(ci.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func (s *Server) GetSSLCerts(ctx context.Context, req *dnsmgrpb.GetSSLCertsRequest) (*dnsmgrpb.GetSSLCertsResponse, error) {\n\tuseDefault := viper.GetBool(\"use_default_dns_cert\")\n\tif useDefault {\n\t\tcert, err := s.getDefaultSSLCert()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif cert == nil {\n\t\t\treturn nil, errors.New(\"Could not get default SSL cert\")\n\t\t}\n\t\treturn &dnsmgrpb.GetSSLCertsResponse{\n\t\t\tKey: cert.Key,\n\t\t\tCert: cert.Cert,\n\t\t}, nil\n\t}\n\n\tclusterID, err := utils.UUIDFromProto(req.ClusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcert, err := s.getClusterSSLCert(clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cert != nil {\n\t\treturn &dnsmgrpb.GetSSLCertsResponse{\n\t\t\tKey: cert.Key,\n\t\t\tCert: cert.Cert,\n\t\t}, nil\n\t}\n\n\tcert, err = s.createSSLCert(clusterID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dnsmgrpb.GetSSLCertsResponse{\n\t\tKey: cert.Key,\n\t\tCert: cert.Cert,\n\t}, nil\n}", "func (client DnsClient) getTsigKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tsigKeys/{tsigKeyId}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetTsigKeyResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (a *SubAccountApiService) ListSubAccountKeys(ctx context.Context, userId int32) ([]SubAccountKey, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []SubAccountKey\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/sub_accounts/{user_id}/keys\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"user_id\"+\"}\", url.QueryEscape(parameterToString(userId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tif ctx.Value(ContextGateAPIV4) == nil {\n\t\t// for compatibility, set configuration key and secret to context if ContextGateAPIV4 value is not present\n\t\tctx = context.WithValue(ctx, ContextGateAPIV4, GateAPIV4{\n\t\t\tKey: a.client.cfg.Key,\n\t\t\tSecret: a.client.cfg.Secret,\n\t\t})\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status + \", \" + string(localVarBody),\n\t\t}\n\t\tvar gateErr GateAPIError\n\t\tif e := a.client.decode(&gateErr, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\")); e == nil && gateErr.Label != \"\" {\n\t\t\tgateErr.APIError = newErr\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, gateErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func NewGetUserKeysKeyIDForbidden() *GetUserKeysKeyIDForbidden {\n\treturn &GetUserKeysKeyIDForbidden{}\n}", "func (session *Session) GetKeys(args *SessionSignArgs) (error) {\n\tkeys, err := session.SearchValidKeys()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif args.CreateKeys {\n\t\tdefaultExpDate := time.Now().AddDate(1, 0, 0)\n\t\tvar public, private pkcs11.ObjectHandle\n\t\tif keys.PublicZSK != nil {\n\t\t\terr = session.ExpireKey(keys.PublicZSK.Handle)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif keys.PrivateZSK != nil {\n\t\t\terr = session.ExpireKey(keys.PrivateZSK.Handle)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tsession.Log.Printf(\"generating zsk\\n\")\n\t\tpublic, private, err = session.GenerateRSAKeyPair(\n\t\t\t\"zsk\",\n\t\t\ttrue,\n\t\t\tdefaultExpDate,\n\t\t\t1024,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkeys.PublicZSK = &Key{\n\t\t\tHandle: public,\n\t\t\tExpDate: defaultExpDate,\n\t\t}\n\t\tkeys.PrivateZSK = &Key{\n\t\t\tHandle: private,\n\t\t\tExpDate: defaultExpDate,\n\t\t}\n\n\t\tif keys.PublicKSK != nil {\n\t\t\terr = session.ExpireKey(keys.PublicKSK.Handle)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif keys.PrivateKSK != nil {\n\t\t\terr = session.ExpireKey(keys.PrivateKSK.Handle)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tsession.Log.Printf(\"generating ksk\\n\")\n\t\tpublic, private, err = session.GenerateRSAKeyPair(\n\t\t\t\"ksk\",\n\t\t\ttrue,\n\t\t\tdefaultExpDate,\n\t\t\t2048,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkeys.PublicKSK = &Key{\n\t\t\tHandle: public,\n\t\t\tExpDate: defaultExpDate,\n\t\t}\n\t\tkeys.PrivateKSK = &Key{\n\t\t\tHandle: private,\n\t\t\tExpDate: defaultExpDate,\n\t\t}\n\t\tsession.Log.Printf(\"keys generated.\\n\")\n\t}\n\n\tif keys.PublicZSK == nil || keys.PublicKSK == nil {\n\t\terr = fmt.Errorf(\n\t\t\t\"valid keys not found. If you have not keys stored \" +\n \"in the HSM, you can create a new pair with \" +\n \"--create-keys flag\",\n\t\t)\n\t\treturn err\n\t}\n args.Keys = keys\n\n // ok, we create DNSKEYS\n\n\tzskBytes, err := session.GetKeyBytes(keys.PublicZSK.Handle)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs.Zsk = CreateNewDNSKEY(\n\t\targs.Zone,\n\t\t256,\n\t\t8, // RSA/SHA256 (https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml)\n\t\targs.MinTTL,\n\t\tbase64.StdEncoding.EncodeToString(zskBytes),\n\t)\n\n\tkskBytes, err := session.GetKeyBytes(keys.PublicKSK.Handle)\n\tif err != nil {\n\t\treturn err\n\t}\n\targs.Ksk = CreateNewDNSKEY(\n\t\targs.Zone,\n\t\t257,\n\t\t8, // RSA/SHA256 (https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml)\n\t\targs.MinTTL, // SOA -> minimum TTL\n\t\tbase64.StdEncoding.EncodeToString(kskBytes),\n\t)\n\n\treturn nil\n}", "func (s *SecretService) GetSecretKeys(ctx context.Context, orgID influxdb.ID) ([]string, error) {\n\tif err := authorizeReadSecret(ctx, orgID); err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tsecrets, err := s.s.GetSecretKeys(ctx, orgID)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\treturn secrets, nil\n}", "func (o *SecurityCertificateCollectionGetParams) WithKeySize(keySize *int64) *SecurityCertificateCollectionGetParams {\n\to.SetKeySize(keySize)\n\treturn o\n}", "func FetchX509SVIDs(ctx context.Context, options ...ClientOption) ([]*x509svid.SVID, error) {\n\tc, err := New(ctx, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer c.Close()\n\treturn c.FetchX509SVIDs(ctx)\n}", "func (s Set) LookupKeyID(kid string) []Key {\n\tvar keys []Key\n\tfor iter := s.Iterate(context.TODO()); iter.Next(context.TODO()); {\n\t\tpair := iter.Pair()\n\t\tkey := pair.Value.(Key)\n\t\tif key.KeyID() == kid {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\treturn keys\n}", "func (client *Client) GetAllKeys() ([]string, error) {\n\tif client.maxWaitTimeForSyncCalls > 0 {\n\t\tjson, err := client.refreshPolicy.getConfigurationAsync().getOrTimeout(client.maxWaitTimeForSyncCalls)\n\t\tif err != nil {\n\t\t\tclient.logger.Errorf(\"Policy could not provide the configuration: %s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn client.parser.GetAllKeys(json.(string))\n\t}\n\n\tjson, _ := client.refreshPolicy.getConfigurationAsync().get().(string)\n\treturn client.parser.GetAllKeys(json)\n}", "func (h *Handler) FetchX509SVID(server node.Node_FetchX509SVIDServer) (err error) {\n\tfor {\n\t\trequest, err := server.Recv()\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tctx := server.Context()\n\n\t\tpeerCert, err := h.getCertFromCtx(ctx)\n\t\tif err != nil {\n\t\t\th.c.Log.Error(err)\n\t\t\treturn errors.New(\"An SVID is required for this request\")\n\t\t}\n\n\t\turiNames, err := uri.GetURINamesFromCertificate(peerCert)\n\t\tif err != nil {\n\t\t\th.c.Log.Error(err)\n\t\t\treturn errors.New(\"An SPIFFE ID is required for this request\")\n\t\t}\n\t\tctxSpiffeID := uriNames[0]\n\n\t\tregEntries, err := regentryutil.FetchRegistrationEntries(ctx, h.c.Catalog.DataStores()[0], ctxSpiffeID)\n\t\tif err != nil {\n\t\t\th.c.Log.Error(err)\n\t\t\treturn errors.New(\"Error trying to get registration entries\")\n\t\t}\n\n\t\tsvids, err := h.signCSRs(ctx, peerCert, request.Csrs, regEntries)\n\t\tif err != nil {\n\t\t\th.c.Log.Error(err)\n\t\t\treturn errors.New(\"Error trying sign CSRs\")\n\t\t}\n\n\t\tbundle, err := h.getBundle(ctx)\n\t\tif err != nil {\n\t\t\th.c.Log.Errorf(\"Error retreiving bundle from datastore: %v\", err)\n\t\t\treturn fmt.Errorf(\"Error retreiving bundle\")\n\t\t}\n\n\t\terr = server.Send(&node.FetchX509SVIDResponse{\n\t\t\tSvidUpdate: &node.SvidUpdate{\n\t\t\t\tSvids: svids,\n\t\t\t\tBundle: bundle,\n\t\t\t\tRegistrationEntries: regEntries,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\th.c.Log.Errorf(\"Error sending FetchX509SVIDResponse: %v\", err)\n\t\t}\n\t}\n}", "func (a *Client) GetSitesIDImages(params *GetSitesIDImagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSitesIDImagesOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetSitesIDImagesParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"getSitesIdImages\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/sites/{id}/images\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\"},\n\t\tParams: params,\n\t\tReader: &GetSitesIDImagesReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetSitesIDImagesOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for getSitesIdImages: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (s *Client) GetSSLCertificates(appName string) ([]Certificate, error) {\n\tvar res []Certificate\n\treturn res, s.Get(&res, fmt.Sprintf(\"/apps/%s/sni-endpoints\", appName), &ListRange{})\n}", "func (o *GetSubscriptionsParams) WithPublisherID(publisherID *int32) *GetSubscriptionsParams {\n\to.SetPublisherID(publisherID)\n\treturn o\n}", "func (client *Client) GetKeyPair(id string) (*model.KeyPair, error) {\n\treturn client.feclt.GetKeyPair(id)\n}", "func (client DnsClient) listTsigKeys(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/tsigKeys\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response ListTsigKeysResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (client *NginxClient) GetKeyValPairs(zone string) (KeyValPairs, error) {\n\treturn client.getKeyValPairs(zone, httpContext)\n}", "func (ks *KeyStore) GetECDSAKey(session pkcs11.SessionHandle, hwslot common.HardwareSlot, passwd string) (*data.ECDSAPublicKey, data.RoleName, error) {\n\terr := pkcs11Ctx.Login(session, pkcs11.CKU_USER, passwd)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdefer pkcs11Ctx.Logout(session)\n\tfindTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_CERTIFICATE_TYPE, pkcs11.CKC_X_509),\n\t\tpkcs11.NewAttribute(pkcs11.CKA_ID, hwslot.KeyID),\n\t}\n\tpubTemplate := []*pkcs11.Attribute{\n\t\tpkcs11.NewAttribute(pkcs11.CKA_VALUE, []byte{0}),\n\t}\n\n\tif err := pkcs11Ctx.FindObjectsInit(session, findTemplate); err != nil {\n\t\tlogrus.Debugf(\"Failed to init: %s\", err.Error())\n\t\treturn nil, \"\", err\n\t}\n\tobj, _, err := pkcs11Ctx.FindObjects(session, 1)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to find objects: %v\", err)\n\t\treturn nil, \"\", err\n\t}\n\tif err := pkcs11Ctx.FindObjectsFinal(session); err != nil {\n\t\tlogrus.Debugf(\"Failed to finalize: %s\", err.Error())\n\t\treturn nil, \"\", err\n\t}\n\tif len(obj) != 1 {\n\t\treturn nil, \"\", fmt.Errorf(\"no matching keys found inside of %s\", name)\n\t}\n\tval, err := pkcs11Ctx.GetAttributeValue(session, obj[0], pubTemplate)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to get Certificate for: %v\", obj[0])\n\t\treturn nil, \"\", err\n\t}\n\tcert, err := x509.ParseCertificate(val[0].Value)\n\tpub := cert.PublicKey\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to parse Certificate for: %v\", obj[0])\n\t\treturn nil, \"\", err\n\t}\n\tattr := pub.(*ecdsa.PublicKey)\n\tecdsaPubKey := ecdsa.PublicKey{Curve: elliptic.P256(), X: attr.X, Y: attr.Y}\n\tpubBytes, err := x509.MarshalPKIXPublicKey(&ecdsaPubKey)\n\tif err != nil {\n\t\tlogrus.Debugf(\"Failed to Marshal public key\")\n\t\treturn nil, \"\", err\n\t}\n\n\treturn data.NewECDSAPublicKey(pubBytes), data.CanonicalRootRole, nil\n}", "func (client *Client) GetKeyPair(id string) (*model.KeyPair, error) {\n\treturn client.osclt.GetKeyPair(id)\n}", "func processx509Certs(keys []string) ([][]byte, error) {\n\tvar x509s [][]byte\n\tfor _, key := range keys {\n\t\tfileName := strings.Split(key, \":\")[0]\n\t\tif _, err := os.Stat(fileName); os.IsNotExist(err) {\n\t\t\tcontinue\n\t\t}\n\t\ttmp, err := os.ReadFile(fileName)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to read file: %w\", err)\n\t\t}\n\t\tif !encutils.IsCertificate(tmp) {\n\t\t\tcontinue\n\t\t}\n\t\tx509s = append(x509s, tmp)\n\n\t}\n\treturn x509s, nil\n}", "func (p *ServicesService) GetServicesByApplicationID(applicationID string) (*[]Service, *Response, error) {\n\topt := &GetServiceOptions{\n\t\tApplicationID: &applicationID,\n\t}\n\treq, err := p.client.NewRequest(IDM, \"GET\", \"authorize/identity/Service\", opt, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treq.Header.Set(\"api-version\", servicesAPIVersion)\n\n\tvar responseStruct struct {\n\t\tTotal int `json:\"total\"`\n\t\tEntry []Service `json:\"entry\"`\n\t}\n\n\tresp, err := p.client.Do(req, &responseStruct)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn &responseStruct.Entry, resp, err\n}", "func (ks PublicKeySet) GetKey(id string) (*rsa.PublicKey, error) {\n\tkey, ok := ks.Keys[id]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"key [%s] not found in set of size %d\", id, len(ks.Keys))\n\t}\n\treturn key, nil\n}", "func (c *cfService) ServiceKeys() ServiceKeys {\n\treturn newServiceKeyAPI(c.Client)\n}", "func (o *GetContentSourcesUsingGETParams) WithIntegrationID(integrationID *string) *GetContentSourcesUsingGETParams {\n\to.SetIntegrationID(integrationID)\n\treturn o\n}", "func GetCryptoKey(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *CryptoKeyState, opts ...pulumi.ResourceOption) (*CryptoKey, error) {\n\tvar resource CryptoKey\n\terr := ctx.ReadResource(\"gcp:kms/cryptoKey:CryptoKey\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (c *Session) CertifyDevIDKey() ([]byte, []byte, error) {\n\treturn c.ak.Certify(c.devID.Handle, c.devID.password)\n}", "func (c *APIGateway) GetApiKeysRequest(input *GetApiKeysInput) (req *request.Request, output *GetApiKeysOutput) {\n\top := &request.Operation{\n\t\tName: opGetApiKeys,\n\t\tHTTPMethod: \"GET\",\n\t\tHTTPPath: \"/apikeys\",\n\t\tPaginator: &request.Paginator{\n\t\t\tInputTokens: []string{\"position\"},\n\t\t\tOutputTokens: []string{\"position\"},\n\t\t\tLimitToken: \"limit\",\n\t\t\tTruncationToken: \"\",\n\t\t},\n\t}\n\n\tif input == nil {\n\t\tinput = &GetApiKeysInput{}\n\t}\n\n\treq = c.newRequest(op, input, output)\n\toutput = &GetApiKeysOutput{}\n\treq.Data = output\n\treturn\n}", "func (s *AccountsService) ListSSHKeys(accountID string) (*[]SSHKeyInfo, *Response, error) {\n\tu := fmt.Sprintf(\"accounts/%s/sshkeys\", accountID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tv := new([]SSHKeyInfo)\n\tresp, err := s.client.Do(req, v)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn v, resp, err\n}", "func (o *SecurityCertificateCollectionGetParams) WithSubjectKeyIdentifier(subjectKeyIdentifier *string) *SecurityCertificateCollectionGetParams {\n\to.SetSubjectKeyIdentifier(subjectKeyIdentifier)\n\treturn o\n}", "func (k Keeper) GetRevokedCertificates(ctx sdk.Context, subject string, subjectKeyID string) (val types.Certificates, found bool) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RevokedCertificatesKey))\n\n\tval.Identifier = types.CertificatesIdentifier{\n\t\tSubject: subject,\n\t\tSubjectKeyID: subjectKeyID,\n\t}\n\tb := store.Get(types.KeyPrefix(val.Identifier.Index()))\n\tif b == nil {\n\t\treturn val, false\n\t}\n\n\tk.cdc.MustUnmarshalBinaryBare(b, &val)\n\treturn val, true\n}" ]
[ "0.61564887", "0.5915994", "0.5859082", "0.5506592", "0.5346934", "0.5332263", "0.52300006", "0.506717", "0.50242484", "0.4996197", "0.48781332", "0.47579432", "0.47013146", "0.46787006", "0.46667585", "0.46625802", "0.46300685", "0.46164986", "0.46141317", "0.46038184", "0.45986432", "0.45974657", "0.45964554", "0.45818987", "0.45639002", "0.4558069", "0.45330182", "0.45323503", "0.45264795", "0.45049766", "0.44938537", "0.44618693", "0.44531235", "0.44389164", "0.44381726", "0.44304428", "0.4429178", "0.44176352", "0.43933064", "0.43908405", "0.4365607", "0.43653402", "0.43460822", "0.43458655", "0.43440235", "0.43437323", "0.43329424", "0.42988122", "0.42974657", "0.42952526", "0.42928046", "0.42776763", "0.42770484", "0.42671812", "0.4262387", "0.42510566", "0.42344615", "0.42330235", "0.42095616", "0.42075703", "0.4195911", "0.41883028", "0.41879785", "0.41745013", "0.4173054", "0.4165314", "0.41584283", "0.41576388", "0.41557375", "0.41483063", "0.4143687", "0.4134833", "0.4113997", "0.41032532", "0.41031602", "0.4097981", "0.40974644", "0.4092673", "0.40807244", "0.40780538", "0.40777257", "0.40659484", "0.40642545", "0.40631568", "0.40578797", "0.40567186", "0.40551934", "0.40547872", "0.4050997", "0.40422317", "0.40387374", "0.40368208", "0.4034724", "0.4029093", "0.40273622", "0.40197304", "0.40164158", "0.40155342", "0.40129328", "0.40127513" ]
0.8322349
0
returns the cdn_id found by domainname.
func getCDNIDByDomainname(domainName string, tx *sql.Tx) (int64, bool, error) { cdnID := int64(0) if err := tx.QueryRow(`SELECT id from cdn WHERE domain_name = $1`, domainName).Scan(&cdnID); err != nil { if err == sql.ErrNoRows { return 0, false, nil } return 0, false, err } return cdnID, true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func lookupDomainName(domainName string) string {\n\tif du, ok := domainUuid[domainName]; ok {\n\t\treturn du\n\t}\n\treturn \"\"\n}", "func (o GetGroupResultOutput) DomainId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetGroupResult) string { return v.DomainId }).(pulumi.StringOutput)\n}", "func domainConfig(cfg *admin.CertificateAuthorityConfig, domain string) *admin.DomainConfig {\n\tfor _, domainCfg := range cfg.KnownDomains {\n\t\tfor _, domainInCfg := range domainCfg.Domain {\n\t\t\tif domainInCfg == domain || strings.HasSuffix(domain, \".\"+domainInCfg) {\n\t\t\t\treturn domainCfg\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (r Dns_Domain) GetByDomainName(name *string) (resp []datatypes.Dns_Domain, err error) {\n\tparams := []interface{}{\n\t\tname,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Dns_Domain\", \"getByDomainName\", params, &r.Options, &resp)\n\treturn\n}", "func DomainNameAndId(compositeDomainName string) (string, string) {\n\tif parts := strings.Split(compositeDomainName, \":\"); len(parts) == 2 {\n\t\treturn parts[0], parts[1]\n\t}\n\treturn compositeDomainName, \"\"\n}", "func getZoneID(cfg *Config, c *CfVars) (ZoneID string, err error) {\n\n\tid, err := c.API.ZoneIDByName(cfg.Domain)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn id, nil\n\n}", "func (d *dnsClient) GetDomainName(ctx context.Context, domainId string) (string, error) {\n\tdomains, err := d.getDomainsWithCache(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdomain, ok := domains[domainId]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"DNS domain with id %s not found\", domainId)\n\t}\n\treturn CompositeDomainName(domain.DomainName, domain.DomainId), nil\n}", "func (id *authIdentity) DomainID() string {\n\treturn id.domainID\n}", "func GetDSDomainName(dsExampleURLs []string) (string, error) {\n\t// TODO move somewhere generic\n\tif len(dsExampleURLs) == 0 {\n\t\treturn \"\", errors.New(\"no example URLs\")\n\t}\n\n\tdsName := dsExampleURLs[0] + \".\"\n\tfirstDot := strings.Index(dsName, \".\")\n\tif firstDot == -1 {\n\t\treturn \"\", errors.New(\"malformed example URL, no dots\")\n\t}\n\tif len(dsName) < firstDot+2 {\n\t\treturn \"\", errors.New(\"malformed example URL, nothing after first dot\")\n\t}\n\tdsName = dsName[firstDot+1:]\n\tdsName = strings.ToLower(dsName)\n\treturn dsName, nil\n}", "func (lc *LibvirtConnect) GetDomainByName(name string) (*LibvirtDomain, error) {\n\treturn nil, fmt.Errorf(\"not supported\")\n}", "func (internet Internet) DomainName(v reflect.Value) (interface{}, error) {\n\treturn internet.domainName()\n}", "func (o *IpamNetworkDataData) GetDomainId() string {\n\tif o == nil || o.DomainId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DomainId\n}", "func (curre *CurrentExecution) GetDomainID() string {\n\treturn curre.DomainID\n}", "func (x *CreateNodeRequest) GetDnsDomainId() int64 {\n\tif x != nil {\n\t\treturn x.DnsDomainId\n\t}\n\treturn 0\n}", "func (d *DNSProviderPublic) getHostedZoneID(ctx context.Context, fqdn string) (string, error) {\n\tif zone := env.GetOrFile(EnvZoneName); zone != \"\" {\n\t\treturn zone, nil\n\t}\n\n\tauthZone, err := dns01.FindZoneByFqdn(fqdn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tzone, err := d.zoneClient.Get(ctx, d.config.ResourceGroup, dns01.UnFqdn(authZone), nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// zone.Name shouldn't have a trailing dot(.)\n\treturn dns01.UnFqdn(deref(zone.Name)), nil\n}", "func (ce *ConcreteExecution) GetDomainID() string {\n\treturn ce.DomainID\n}", "func (mdms *GSuiteMDMService) GetDomainCustomerID(domain string) (string, error) {\n\t// Range through the slice of configured domains and look for the specified domain\n\tfor _, d := range mdms.C.Domains {\n\t\tswitch d.DomainName {\n\t\tcase domain:\n\t\t\t// Domain found, return the domain's CustomerID\n\t\t\treturn d.CustomerID, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(fmt.Sprintf(\"Could not find CustomerID for domain %s\", domain))\n}", "func (o *VlanVlanDataData) GetDomainId() string {\n\tif o == nil || o.DomainId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DomainId\n}", "func (d *DHCPv4) DomainName() string {\n\treturn GetString(OptionDomainName, d.Options)\n}", "func DomainName() string {\n\treturn fmt.Sprintf(\"%s.%s\",\n\t\tAlpha(\"\", 14),\n\t\tItem(\"net\", \"com\", \"org\", \"io\", \"gov\"))\n}", "func NamedDomain(domainName string) Domain { return domains.NamedDomain(domainName) }", "func NamedDomain(domainName string) Domain { return domains.NamedDomain(domainName) }", "func (o AdConnectorDirectoryOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AdConnectorDirectory) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (o CertificateOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Certificate) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func getHostedZoneIDByNameLookup(svc *route53.Route53, hostedZoneName string) (string, error) {\n\n\tlistParams := &route53.ListHostedZonesByNameInput{\n\t\tDNSName: aws.String(hostedZoneName), // Required\n\t\tMaxItems: aws.String(\"1\"),\n\t}\n\thzOut, err := svc.ListHostedZonesByName(listParams)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tzones := hzOut.HostedZones\n\n\tif len(zones) < 1 {\n\t\tfmt.Printf(\"No zone found for %s\\n\", hostedZoneName)\n\t\treturn \"\", err\n\t}\n\n\tzoneID := *zones[0].Id\n\tzoneName := *zones[0].Name\n\n\t// Safety check because sometimes the first row is not the same hosted zone you are looking for,\n\t// but rather the first zone that is found and if the zones does not exist, it will return\n\t// the nearest zone which is not what you are looking for\n\tif zoneName != hostedZoneName {\n\t\tlog.Fatalf(\"Hosted zones names do not match, quiting: [%s] - [%s]\", hostedZoneName, zoneName)\n\t}\n\n\t// remove the /hostedzone/ path if it's there\n\tif strings.HasPrefix(zoneID, \"/hostedzone/\") {\n\t\tzoneID = strings.TrimPrefix(zoneID, \"/hostedzone/\")\n\t}\n\n\treturn zoneID, nil\n}", "func (rp *ResolverPool) SubdomainToDomain(name string) string {\n\trp.domainLock.Lock()\n\tdefer rp.domainLock.Unlock()\n\n\tvar domain string\n\t// Obtain all parts of the subdomain name\n\tlabels := strings.Split(strings.TrimSpace(name), \".\")\n\t// Check the cache for all parts of the name\n\tfor i := len(labels); i >= 0; i-- {\n\t\tsub := strings.Join(labels[i:], \".\")\n\n\t\tif _, ok := rp.domainCache[sub]; ok {\n\t\t\tdomain = sub\n\t\t\tbreak\n\t\t}\n\t}\n\tif domain != \"\" {\n\t\treturn domain\n\t}\n\t// Check the DNS for all parts of the name\n\tfor i := 0; i < len(labels)-1; i++ {\n\t\tsub := strings.Join(labels[i:], \".\")\n\n\t\tif ns, _, err := rp.Resolve(context.TODO(), sub, \"NS\", PriorityHigh); err == nil {\n\t\t\tpieces := strings.Split(ns[0].Data, \",\")\n\t\t\trp.domainCache[pieces[0]] = struct{}{}\n\t\t\tdomain = pieces[0]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn domain\n}", "func Domain(named Named) string {\n\tif r, ok := named.(namedRepository); ok {\n\t\treturn r.Domain()\n\t}\n\tdomain, _ := splitDomain(named.Name())\n\treturn domain\n}", "func (l *Libvirt) DomainLookupByName(Name string) (rDom Domain, err error) {\n\tvar buf []byte\n\n\targs := DomainLookupByNameArgs {\n\t\tName: Name,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(23, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Dom: Domain\n\t_, err = dec.Decode(&rDom)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (d *DeviceProp) PciDomainID() int32 {\n\treturn (int32)(d.pciDomainID)\n}", "func DomainName(opts ...options.OptionFunc) string {\n\treturn singleFakeData(DomainNameTag, func() interface{} {\n\t\topt := options.BuildOptions(opts)\n\t\ti := Internet{fakerOption: *opt}\n\t\td, err := i.domainName()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\treturn d\n\t}, opts...).(string)\n}", "func (k Keeper) GetCdpID(ctx sdk.Context, owner sdk.AccAddress, denom string) (uint64, bool) {\n\n\tcdpIDs, found := k.GetCdpIdsByOwner(ctx, owner)\n\tif !found {\n\t\treturn 0, false\n\t}\n\tfor _, id := range cdpIDs {\n\t\t_, found = k.GetCDP(ctx, denom, id)\n\t\tif found {\n\t\t\treturn id, true\n\t\t}\n\t}\n\treturn 0, false\n\n}", "func (p *v1Provider) FindDomainFromRequest(w http.ResponseWriter, r *http.Request, cluster *core.Cluster) *db.Domain {\n\tdomainUUID := mux.Vars(r)[\"domain_id\"]\n\tif domainUUID == \"\" {\n\t\thttp.Error(w, \"domain ID missing\", 400)\n\t\treturn nil\n\t}\n\n\tvar domain db.Domain\n\terr := db.DB.SelectOne(&domain, `SELECT * FROM domains WHERE uuid = $1 AND cluster_id = $2`,\n\t\tdomainUUID, cluster.ID,\n\t)\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\thttp.Error(w, \"no such domain (if it was just created, try to POST /domains/discover)\", 404)\n\t\treturn nil\n\tcase respondwith.ErrorText(w, err):\n\t\treturn nil\n\tdefault:\n\t\treturn &domain\n\t}\n}", "func (o *Service) GetIDByName() (string, error) {\n\tif o.Name == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Service name must be provided\")\n\t}\n\n\tresult, err := o.Query()\n\tif err != nil {\n\t\tlogger.Errorf(err.Error())\n\t\treturn \"\", fmt.Errorf(\"Error retrieving service: %s\", err)\n\t}\n\to.ID = result[\"ID\"].(string)\n\n\treturn o.ID, nil\n}", "func (o DnsDomainOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DnsDomain) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (u *User) MyDomainID() string {\n\tfor _, dm := range u.DomainMembershipMap {\n\t\tif dm.DomainPageID == u.ID {\n\t\t\treturn dm.DomainID\n\t\t}\n\t}\n\treturn \"\"\n}", "func (o *VlanRangeEditInput) GetDomainId() int32 {\n\tif o == nil || o.DomainId == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.DomainId\n}", "func (d *DB) Get_domain(ipaddress string) (IP2Locationrecord, error) {\n\treturn d.query(ipaddress, domain)\n}", "func (c *Client) GetDomain(customerID, domain string) (*Domain, error) {\n\tdomainURL := fmt.Sprintf(pathDomains, c.baseURL, domain)\n\treq, err := http.NewRequest(http.MethodGet, domainURL, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := new(Domain)\n\tif err := c.execute(customerID, req, &d); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func GetRedisDomainKey(domain string) string {\n\treturn GetRedisKey(fmt.Sprintf(\"cache:domain-%s\", domain))\n}", "func databaseID(dbOwner, dbFolder, dbName string) (dbID int, err error) {\n\t// Retrieve the database id\n\tdbQuery := `\n\t\tSELECT db_id\n\t\tFROM sqlite_databases\n\t\tWHERE user_id = (\n\t\t\t\tSELECT user_id\n\t\t\t\tFROM users\n\t\t\t\tWHERE lower(user_name) = lower($1))\n\t\t\tAND folder = $2\n\t\t\tAND db_name = $3\n\t\t\tAND is_deleted = false`\n\terr = pdb.QueryRow(dbQuery, dbOwner, dbFolder, dbName).Scan(&dbID)\n\tif err != nil {\n\t\tlog.Printf(\"Error looking up database id. Owner: '%s', Database: '%s'. Error: %v\\n\", dbOwner, dbName,\n\t\t\terr)\n\t}\n\treturn\n}", "func dbnameOfDSN(dsn string) (string, string) {\n\tvar dbname string\n\ti := strings.LastIndex(dsn, \"/\")\n\tif i >= 0 {\n\t\tdbname = dsn[i+1:] // save the database name\n\t\tj := strings.Index(dbname, \"?\")\n\t\tif j >= 0 {\n\t\t\tdbname = dbname[:j]\n\t\t}\n\t\tdsn = dsn[:i+1] // stomp on the database name in conf. Requires trailing '/'.\n\t}\n\n\treturn dbname, dsn\n}", "func (cs *CachingAuthClient) GetDomainName() (clusterName string, err error) {\n\tcs.fetch(params{\n\t\t// key is a key of the cached value\n\t\tkey: \"clusterName\",\n\t\t// fetch will be called if cache has expired\n\t\tfetch: func() error {\n\t\t\tclusterName, err = cs.ap.GetDomainName()\n\t\t\treturn err\n\t\t},\n\t\tuseCache: func() error {\n\t\t\tclusterName, err = cs.presence.GetLocalClusterName()\n\t\t\treturn err\n\t\t},\n\t\tupdateCache: func() ([]string, error) {\n\t\t\treturn nil, cs.presence.UpsertLocalClusterName(clusterName)\n\t\t},\n\t})\n\treturn\n}", "func resolveCNAME(domain string) (string, error) {\n\tresolver := net.Resolver{}\n\treturn resolver.LookupCNAME(context.Background(), domain)\n}", "func (p *Provider) queryMainDomain(ctx context.Context, name string) (string, string, error) {\n\tp.client.mutex.Lock()\n\tdefer p.client.mutex.Unlock()\n\tp.getClient()\n\tp.client.aClient.addReqBody(\"Action\", \"GetMainDomainName\")\n\tp.client.aClient.addReqBody(\"InputString\", strings.Trim(name, \".\"))\n\trs := aliResult{}\n\terr := p.doAPIRequest(ctx, &rs)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn rs.Rr, rs.DName, err\n}", "func DnsDomain(s string) string {\n\tl := strings.Split(s, \"/\")\n\t// start with 1, to strip /skydns\n\tfor i, j := 1, len(l)-1; i < j; i, j = i+1, j-1 {\n\t\tl[i], l[j] = l[j], l[i]\n\t}\n\treturn dns.Fqdn(strings.Join(l[2:len(l)-1], \".\"))\n}", "func (c *Client) NetworkIDByName(name string) (string, error) {\n\tendpoint := fmt.Sprintf(\"%snetworks\", baseAddr)\n\tr, err := c.http.Get(endpoint)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err = statusCode(r.StatusCode, http.StatusOK); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnetworks := []struct {\n\t\tDriver string `json:\"Driver\"`\n\t\tID string `json:\"ID\"`\n\t\tName string `json:\"Name\"`\n\t}{}\n\n\tif err := json.NewDecoder(r.Body).Decode(&networks); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, n := range networks {\n\t\tif ok := strings.Contains(n.Name, name); ok {\n\t\t\treturn n.ID, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"can not extract containerID for %s\", name)\n}", "func TrustDomainID(trustDomain string) string {\n\treturn TrustDomainURI(trustDomain).String()\n}", "func (o IpaDomainOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IpaDomain) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (c *AcmednsClient) acmeDnsAccountForDomain(domain string) (goacmedns.Account, error) {\n\tadnsacct, err := c.Storage.Fetch(domain)\n\tif err != nil && err != goacmedns.ErrDomainNotFound{\n\t\treturn goacmedns.Account{}, err\n\t} else if err == goacmedns.ErrDomainNotFound {\n\t\treturn goacmedns.Account{}, nil\n\t}\n\treturn adnsacct, err\n}", "func lookupCanonID(\n\tacct string,\n\tsess *session.Session) (string, error) {\n\n\tlog.Println(\"Looking up canonical id for \", acct)\n\tsvc := s3.New(sess)\n\tcount.Incr(\"aws-listbuckets-canon\")\n\tbObj, err := svc.ListBuckets(&s3.ListBucketsInput{})\n\tif err != nil {\n\t\tlogCountErr(err, \"listBuckets failed\"+acct)\n\t\treturn \"\", err\n\t}\n\treturn parseBucketList(bObj)\n\n}", "func (cs *CachingAuthClient) GetDomainName() (string, error) {\n\tcs.try(func() error {\n\t\tdn, err := cs.ap.GetDomainName()\n\t\tif err == nil {\n\t\t\tcs.Lock()\n\t\t\tdefer cs.Unlock()\n\t\t\tcs.domainName = dn\n\t\t}\n\t\treturn err\n\t})\n\tcs.RLock()\n\tdefer cs.RUnlock()\n\treturn cs.domainName, nil\n}", "func (db *cdb) SelectDomain(\n\tctx context.Context,\n\tdomainID *string,\n\tdomainName *string,\n) (*nosqlplugin.DomainRow, error) {\n\tif domainID != nil && domainName != nil {\n\t\treturn nil, fmt.Errorf(\"GetDomain operation failed. Both ID and Name specified in request\")\n\t} else if domainID == nil && domainName == nil {\n\t\treturn nil, fmt.Errorf(\"GetDomain operation failed. Both ID and Name are empty\")\n\t}\n\n\tvar query gocql.Query\n\tvar err error\n\tif domainID != nil {\n\t\tquery = db.session.Query(templateGetDomainQuery, domainID).WithContext(ctx)\n\t\terr = query.Scan(&domainName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tinfo := &p.DomainInfo{}\n\tconfig := &nosqlplugin.NoSQLInternalDomainConfig{}\n\treplicationConfig := &p.DomainReplicationConfig{}\n\n\t// because of encoding/types, we can't directly read from config struct\n\tvar badBinariesData []byte\n\tvar badBinariesDataEncoding string\n\tvar replicationClusters []map[string]interface{}\n\n\tvar failoverNotificationVersion int64\n\tvar notificationVersion int64\n\tvar failoverVersion int64\n\tvar previousFailoverVersion int64\n\tvar failoverEndTime int64\n\tvar lastUpdatedTime int64\n\tvar configVersion int64\n\tvar isGlobalDomain bool\n\tvar retentionDays int32\n\n\tquery = db.session.Query(templateGetDomainByNameQueryV2, constDomainPartition, domainName).WithContext(ctx)\n\terr = query.Scan(\n\t\t&info.ID,\n\t\t&info.Name,\n\t\t&info.Status,\n\t\t&info.Description,\n\t\t&info.OwnerEmail,\n\t\t&info.Data,\n\t\t&retentionDays,\n\t\t&config.EmitMetric,\n\t\t&config.ArchivalBucket,\n\t\t&config.ArchivalStatus,\n\t\t&config.HistoryArchivalStatus,\n\t\t&config.HistoryArchivalURI,\n\t\t&config.VisibilityArchivalStatus,\n\t\t&config.VisibilityArchivalURI,\n\t\t&badBinariesData,\n\t\t&badBinariesDataEncoding,\n\t\t&replicationConfig.ActiveClusterName,\n\t\t&replicationClusters,\n\t\t&isGlobalDomain,\n\t\t&configVersion,\n\t\t&failoverVersion,\n\t\t&failoverNotificationVersion,\n\t\t&previousFailoverVersion,\n\t\t&failoverEndTime,\n\t\t&lastUpdatedTime,\n\t\t&notificationVersion,\n\t)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig.BadBinaries = p.NewDataBlob(badBinariesData, common.EncodingType(badBinariesDataEncoding))\n\tconfig.Retention = common.DaysToDuration(retentionDays)\n\treplicationConfig.Clusters = p.DeserializeClusterConfigs(replicationClusters)\n\n\tdr := &nosqlplugin.DomainRow{\n\t\tInfo: info,\n\t\tConfig: config,\n\t\tReplicationConfig: replicationConfig,\n\t\tConfigVersion: configVersion,\n\t\tFailoverVersion: failoverVersion,\n\t\tFailoverNotificationVersion: failoverNotificationVersion,\n\t\tPreviousFailoverVersion: previousFailoverVersion,\n\t\tNotificationVersion: notificationVersion,\n\t\tLastUpdatedTime: time.Unix(0, lastUpdatedTime),\n\t\tIsGlobalDomain: isGlobalDomain,\n\t}\n\tif failoverEndTime > emptyFailoverEndTime {\n\t\tdr.FailoverEndTime = common.TimePtr(time.Unix(0, failoverEndTime))\n\t}\n\n\treturn dr, nil\n}", "func (m *Metadata) DNSInstanceCRN(ctx context.Context) (string, error) {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tvar err error\n\tif m.client == nil {\n\t\tclient, err := NewClient()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tm.client = client\n\t}\n\n\tif m.dnsInstanceCRN == \"\" {\n\t\tm.dnsInstanceCRN, err = m.client.GetInstanceCRNByName(ctx, m.BaseDomain, types.InternalPublishingStrategy)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\treturn m.dnsInstanceCRN, nil\n}", "func (k *Keystone) GetProjectIDByName(\n\tctx context.Context, id, password, projectName string, domain *keystone.Domain) (string, error) {\n\t// Fetch unscoped token\n\tresp, err := k.obtainUnscopedToken(ctx, id, password, domain)\n\tif err != nil {\n\t\treturn \"\", errorFromResponse(err, resp)\n\t}\n\ttoken := resp.Header.Get(\"X-Subject-Token\")\n\t// Get project list with unscoped token\n\trequest, err := http.NewRequest(echo.GET, k.getURL(\"/auth/projects\"), nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"creating HTTP request failed\")\n\t}\n\trequest = auth.SetXClusterIDInHeader(ctx, request.WithContext(ctx))\n\trequest.Header.Set(\"X-Auth-Token\", token)\n\tvar output *projectListResponse\n\tresp, err = k.HTTPClient.Do(request)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"issuing HTTP request failed\")\n\t}\n\tdefer resp.Body.Close() // nolint: errcheck\n\n\tif err = checkStatusCode([]int{http.StatusOK}, resp.StatusCode); err != nil {\n\t\treturn \"\", errorFromResponse(err, resp)\n\t}\n\n\tif err = json.NewDecoder(resp.Body).Decode(&output); err != nil {\n\t\treturn \"\", errors.Wrapf(errorFromResponse(err, resp), \"decoding response body failed\")\n\t}\n\n\tfor _, project := range output.Projects {\n\t\tif project.Name == projectName {\n\t\t\treturn project.ID, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"'%s' not a valid project name\", projectName)\n}", "func (c *Client) GetDomainByName(name string) (*DNSDomain, error) {\n\tname = dns01.UnFqdn(name)\n\n\t// Try to find the most specific domain\n\t// starts with the FQDN, then remove each left label until we have a match\n\tfor {\n\t\ti := strings.Index(name, \".\")\n\t\tif i == -1 {\n\t\t\tbreak\n\t\t}\n\n\t\tdomain, err := c.getDomainByName(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif domain != nil {\n\t\t\treturn domain, nil\n\t\t}\n\n\t\tlog.Infof(\"domain %q not found, trying with %q\", name, name[i+1:])\n\n\t\tname = name[i+1:]\n\t}\n\n\treturn nil, fmt.Errorf(\"domain not found %s\", name)\n}", "func (o RegisteredDomainOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RegisteredDomain) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (k *Client) GetProjectIDByName(\n\tctx context.Context, id, password, projectName string, domain *Domain) (string, error) {\n\t// Fetch unscoped token\n\ttoken, err := k.obtainUnscopedToken(ctx, id, password, domain)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Get project list with unscoped token\n\trequest, err := http.NewRequest(http.MethodGet, k.getURL(\"/auth/projects\"), nil)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"creating HTTP request failed\")\n\t}\n\trequest = request.WithContext(ctx) // TODO(mblotniak): use http.NewRequestWithContext after go 1.13 upgrade\n\thttputil.SetContextHeaders(request)\n\trequest.Header.Set(xAuthTokenHeader, token)\n\n\tvar output *projectListResponse\n\tresp, err := k.HTTPDoer.Do(request)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"issuing HTTP request failed\")\n\t}\n\tdefer resp.Body.Close() // nolint: errcheck\n\n\tif err = httputil.CheckStatusCode([]int{http.StatusOK}, resp.StatusCode); err != nil {\n\t\treturn \"\", httputil.ErrorFromResponse(err, resp)\n\t}\n\n\tif err = json.NewDecoder(resp.Body).Decode(&output); err != nil {\n\t\treturn \"\", errors.Wrapf(httputil.ErrorFromResponse(err, resp), \"decoding response body failed\")\n\t}\n\n\tfor _, project := range output.Projects {\n\t\tif project.Name == projectName {\n\t\t\treturn project.ID, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"'%s' not a valid project name\", projectName)\n}", "func CompositeDomainName(domainName, domainId string) string {\n\tif domainId != \"\" {\n\t\treturn domainName + \":\" + domainId\n\t}\n\treturn domainName\n}", "func (client IdentityClient) getDomain(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodGet, \"/domains/{domainId}\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response GetDomainResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func (fkdns *Holder) GetDomainFromFakeDNS(ip net.Address) string {\n\tif !ip.Family().IsIP() || !fkdns.ipRange.Contains(ip.IP()) {\n\t\treturn \"\"\n\t}\n\tif k, ok := fkdns.domainToIP.GetKeyFromValue(ip); ok {\n\t\treturn k.(string)\n\t}\n\treturn \"\"\n}", "func (a *AccessPointRule) GetDCID() (value int) {\n\tif a == nil {\n\t\treturn\n\t}\n\treturn a.DCID\n}", "func (o *VlanVlanDataData) GetDomainClassName() string {\n\tif o == nil || o.DomainClassName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.DomainClassName\n}", "func (d TFDomainData) FindDatacenterResourceName(id int) (string, error) {\n\tfor _, dc := range d.Datacenters {\n\t\tif dc.ID == id {\n\t\t\treturn normalizeResourceName(dc.Nickname), nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"cannot find datacenter resource with ID: %d\", id)\n}", "func (us *UserStorage) IDByName(name string) (string, error) {\n\ts := us.db.Session(UsersCollection)\n\tdefer s.Close()\n\n\tvar u userData\n\tstrictPattern := \"^\" + name + \"$\"\n\tq := bson.M{\"$regex\": bson.RegEx{Pattern: strictPattern, Options: \"i\"}}\n\tif err := s.C.Find(bson.M{\"username\": q}).One(&u); err != nil {\n\t\treturn \"\", model.ErrorNotFound\n\t}\n\n\tuser := &User{userData: u}\n\n\tif !user.Active() {\n\t\treturn \"\", ErrorInactiveUser\n\t}\n\n\treturn user.ID(), nil\n}", "func (us *UserStorage) IDByName(name string) (string, error) {\n\ts := us.db.Session(UsersCollection)\n\tdefer s.Close()\n\n\tvar u userData\n\tstrictPattern := \"^\" + name + \"$\"\n\tq := bson.M{\"$regex\": bson.RegEx{Pattern: strictPattern, Options: \"i\"}}\n\tif err := s.C.Find(bson.M{\"name\": q}).One(&u); err != nil {\n\t\treturn \"\", model.ErrorNotFound\n\t}\n\n\tuser := &User{userData: u}\n\n\tif !user.Active() {\n\t\treturn \"\", ErrorInactiveUser\n\t}\n\n\treturn user.ID(), nil\n}", "func LookupDomainKey(selector string, parentDomain string) ([]byte, error) {\n\tselector = strings.ToLower(selector)\n\tnonce := dnsNonce(nonceStdSize)\n\tdomain := fmt.Sprintf(\"_%s.%s.%s.%s\", nonce, selector, domainKeyMsg, parentDomain)\n\n\ttxt, err := dnsLookup(domain)\n\tif err != nil {\n\t\t// {{if .Debug}}\n\t\tlog.Printf(\"Error fetching server certificate %v\", err)\n\t\t// {{end}}\n\t\treturn nil, err\n\t}\n\tcertPEM, err := base64.RawStdEncoding.DecodeString(txt)\n\tif err != nil {\n\t\t// {{if .Debug}}\n\t\tlog.Printf(\"Error decoding certificate %v\", err)\n\t\t// {{end}}\n\t\treturn nil, err\n\t}\n\treturn certPEM, nil\n}", "func GetDomain(err error) Domain { return domains.GetDomain(err) }", "func GetDomain(err error) Domain { return domains.GetDomain(err) }", "func (us *UserStorage) IDByName(name string) (string, error) {\n\treturn randomdata.StringNumber(2, \"-\"), nil\n}", "func Get_domain(ipaddress string) IP2Locationrecord {\n\treturn handleError(defaultDB.query(ipaddress, domain))\n}", "func prnGetID(prn string) string {\n\tidx := strings.Index(prn, \"/\")\n\treturn prn[idx+1:]\n}", "func GetClusterDNSDomain() (string, error) {\n\n\t// get configmap from openshift-node namespace\n\n\t// pull out node-config.yaml\n\n\t// pull out dnsDomain value\n\n\t// return it\n\treturn \"cluster.local\", nil\n}", "func (o DomainNameOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DomainName) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (r *Distribution) DomainName() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"domainName\"])\n}", "func (c *Client) GetDNSZoneIDByName(ctx context.Context, name string) (string, error) {\n\n\tzones, err := c.GetDNSZones(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, z := range zones {\n\t\tif z.Name == name {\n\t\t\treturn z.ID, nil\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"DNS zone %q not found\", name)\n}", "func (s *Server) Domain(domainName string) (Domain, error) {\n\tdomain := Domain{}\n\n\tdomainExists, err := s.domainExists(domainName)\n\tif err != nil {\n\t\treturn domain, err\n\t}\n\tif !domainExists {\n\t\treturn domain, fmt.Errorf(\"Domain %s doesn't exist\", domainName)\n\t}\n\n\tdomaines, err := s.domainQuery(domainQueryByDomain, domainName)\n\tif err != nil {\n\t\treturn domain, err\n\t}\n\n\tif len(domaines) == 0 {\n\t\treturn domain, fmt.Errorf(\"Domain not found\")\n\t}\n\n\treturn domaines[0], nil\n}", "func (o DomainOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Domain) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func (o DomainOutput) Cname() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Domain) pulumi.StringOutput { return v.Cname }).(pulumi.StringOutput)\n}", "func (jid JID) Domain() JID {\n\ts := 0\n\n\tif i := strings.Index(string(jid), \"@\"); i != -1 {\n\t\ts = i + 1\n\t}\n\n\te := len(jid)\n\n\tif i := strings.Index(string(jid), \"/\"); i != -1 {\n\t\te = i\n\t}\n\n\treturn jid[s:e]\n}", "func fetchAlicloudInstanceIDByNodeName(nodeName string) (string, error) {\n\ttypeName, err := getTargetType()\n\tcheckError(err)\n\tClient, err = clientToTarget(typeName)\n\tcheckError(err)\n\n\tnodes, err := Client.CoreV1().Nodes().List(metav1.ListOptions{})\n\tcheckError(err)\n\tfor _, node := range nodes.Items {\n\t\tif nodeName == node.Name {\n\t\t\tif node.Spec.ProviderID != \"\" {\n\t\t\t\treturn strings.Split(node.Spec.ProviderID, \".\")[1], nil\n\t\t\t}\n\t\t}\n\t}\n\n\t//Fallback: Normally, node id is izbp1c11iq8wz8p58ve2mhz, instance id looks like: i-bp1c11iq8wz8p58ve2mh\n\tinstanceID := strings.TrimRight(nodeName, \"z\")\n\tinstanceID = strings.Replace(instanceID, \"z\", \"-\", 1)\n\n\treturn instanceID, nil\n}", "func getXMLID(cdnID int64, hostRegex string, tx *sql.Tx) (string, bool, error) {\n\tq := `\nSELECT ds.xml_id from deliveryservice ds\nJOIN deliveryservice_regex dr on ds.id = dr.deliveryservice AND ds.cdn_id = $1\nJOIN regex r on r.id = dr.regex\nWHERE r.pattern = $2\n`\n\txmlID := \"\"\n\tif err := tx.QueryRow(q, cdnID, hostRegex).Scan(&xmlID); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", false, nil\n\t\t}\n\t\treturn \"\", false, errors.New(\"querying xml id: \" + err.Error())\n\t}\n\treturn xmlID, true, nil\n}", "func (l *Libvirt) DomainLookupByName(name string) (*Domain, error) {\n\treq := libvirt.RemoteDomainLookupByNameReq{Name: name}\n\tres := libvirt.RemoteDomainLookupByNameRes{}\n\n\tbuf, err := encode(&req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := l.send(libvirt.RemoteProcDomainLookupByName, 0, libvirt.MessageTypeCall, libvirt.RemoteProgram, libvirt.MessageStatusOK, &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := <-resp\n\tif r.Header.Status != libvirt.MessageStatusOK {\n\t\treturn nil, decodeError(r.Payload)\n\t}\n\n\tdec := xdr.NewDecoder(bytes.NewReader(r.Payload))\n\n\t_, err = dec.Decode(&res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Domain{RemoteDomain: res.Domain, l: l}, nil\n}", "func (s *Store) PsychologistID(clientID string) (string, error) {\n\n\tif strings.TrimSpace(clientID) == \"\" {\n\t\treturn \"\", errors.New(\"clientID is empty\")\n\t}\n\n\tvar cID string\n\n\terr := s.db.SQL.Get(&cID, `\n\tselect psychologist_public_id from client c\n\twhere client_public_id = $1`, clientID)\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"an error occurred while searching psychologistID from client\")\n\t}\n\treturn cID, nil\n}", "func (k Keeper) GetLocalDNSID(ctx sdk.Context, name string) (*types.LocalDNSID, error) {\n\tc, err := k.ForwardLookupDomain(ctx, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &types.LocalDNSID{SourcePort: c.Channel.SourcePort, SourceChannel: c.Channel.SourceChannel}, nil\n}", "func (o AccessPointOutput) DomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AccessPoint) pulumi.StringOutput { return v.DomainName }).(pulumi.StringOutput)\n}", "func idFromName(name string) string {\n\ts := strings.Split(strings.ToLower(strings.TrimSpace(name)), \" \")\n\tns := strings.Join(s, \"-\")\n\ts = strings.Split(ns, \".\")\n\treturn strings.Join(s, \"-\")\n}", "func getStackName(input *commands.BucketInput) string {\n\treturn strings.Replace(input.FullDomainName, \".\", \"-\", -1) + \"-cdn\"\n}", "func cidConnIdentifier() func([]byte) (string, bool) {\n\treturn func(packet []byte) (string, bool) {\n\t\tpkts, err := recordlayer.UnpackDatagram(packet)\n\t\tif err != nil || len(pkts) < 1 {\n\t\t\treturn \"\", false\n\t\t}\n\t\tvar h recordlayer.Header\n\t\tif hErr := h.Unmarshal(pkts[0]); hErr != nil {\n\t\t\treturn \"\", false\n\t\t}\n\t\tif h.ContentType != protocol.ContentTypeHandshake {\n\t\t\treturn \"\", false\n\t\t}\n\t\tvar hh handshake.Header\n\t\tvar sh handshake.MessageServerHello\n\t\tfor _, pkt := range pkts {\n\t\t\tif hhErr := hh.Unmarshal(pkt[recordlayer.FixedHeaderSize:]); hhErr != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = sh.Unmarshal(pkt[recordlayer.FixedHeaderSize+handshake.HeaderLength:]); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", false\n\t\t}\n\t\tfor _, ext := range sh.Extensions {\n\t\t\tif e, ok := ext.(*extension.ConnectionID); ok {\n\t\t\t\treturn string(e.CID), true\n\t\t\t}\n\t\t}\n\t\treturn \"\", false\n\t}\n}", "func (s *Sdns) FindDomainFromName(name string) (domain *Domain, found bool) {\n\tvar (\n\t\tstrippedDomain string\n\t\tdomainFound interface{}\n\t)\n\n\tif name == \"\" {\n\t\treturn\n\t}\n\n\tdomainFound, found = s.exactDomains[name]\n\tif !found {\n\t\tlastDomainNdx := strings.IndexByte(name, '.')\n\t\tif lastDomainNdx < 0 {\n\t\t\treturn\n\t\t}\n\n\t\tstrippedDomain = name[lastDomainNdx:]\n\t\tdomainFound, found = s.wildcardDomains[strippedDomain]\n\t}\n\n\tif domainFound != nil {\n\t\tdomain = domainFound.(*Domain)\n\t}\n\n\treturn\n}", "func getRepoDomain(name string) string {\n\trepoPath, _ := GetSpecificRepoPath(name)\n\trepo, _ := gitutil.GetRepoFromLocalDir(*repoPath)\n\trepoURL, _ := gitutil.GetURLForRepo(*repo)\n\n\treturn strings.Split(*repoURL, \"/\")[2]\n}", "func (crowdin *Crowdin) LookupDirId(CrowdinDirName string) (id int, name string, err error) {\r\n\r\n\tcrowdin.log(fmt.Sprintf(\"LookupDirId()\\n\"))\r\n\r\n\t// Lookup directoryId in Crowdin\r\n\tdirId := 0\r\n\tcrowdinDirs := strings.Split(CrowdinDirName, \"/\")\r\n\r\n\tcrowdin.log(fmt.Sprintf(\" len=%d\\n\", len(crowdinDirs)))\r\n\tcrowdin.log(fmt.Sprintf(\" crowdinDir %v\\n\", crowdinDirs))\r\n\t// crowdin.log(fmt.Sprintf(\" crowdinDirs[1] %s\\n\", crowdinDirs[1] ))\r\n\r\n\tswitch l := len(crowdinDirs); l {\r\n\tcase 0:\r\n\t\treturn 0, \"\", errors.New(\"LookupDirId() - Crowdin directory name should not be null.\")\r\n\t// case 1: // no directory so dirId is 0 - value is like \"a_file_name\"\r\n\t// case 2: // no directory so dirId is 0 - value is like \"/a_file_name\"\r\n\tdefault: // l >= 1\r\n\t\t// Lookup end directoryId\r\n\t\t// Get a list of all the project's directories\r\n\t\tlistDirs, err := crowdin.ListAllDirectories(&ListDirectoriesOptions{})\r\n\t\tif err != nil {\r\n\t\t\treturn 0, \"\", errors.New(\"LookupDirId() - Error listing project directories.\")\r\n\t\t}\r\n\t\t\r\n\t\tif len(listDirs.Data) > 0 {\r\n\t\t\t// Lookup last directory's Id\r\n\t\t\tdirId = 0\r\n\t\t\tfor i, dirName := range crowdinDirs { // Go down the directory branch\r\n\t\t\t\tcrowdin.log(fmt.Sprintf(\" idx %d dirName %s len %d dirId %d\", i, dirName, len(crowdinDirs), dirId))\r\n\t\t\t\tfound := false\r\n\t\t\t\tif i > 0 && i < len(crowdinDirs) { // 1st entry is empty and we're done once we reach the last directory name.\r\n\t\t\t\t\tfor _, crwdPrjctDirName := range listDirs.Data { // Look up in list of project dirs the right one\r\n\t\t\t\t\t\tcrowdin.log(fmt.Sprintf(\" check -> crwdPrjctDirName.Data.DirectoryId %d crwdPrjctDirName.Data.Name |%s|\", crwdPrjctDirName.Data.DirectoryId, crwdPrjctDirName.Data.Name))\r\n\t\t\t\t\t\tif crwdPrjctDirName.Data.DirectoryId == dirId && crwdPrjctDirName.Data.Name == dirName {\r\n\t\t\t\t\t\t\tdirId = crwdPrjctDirName.Data.Id // Bingo get that Id\r\n\t\t\t\t\t\t\tname = dirName\r\n\t\t\t\t\t\t\tfound = true\r\n\t\t\t\t\t\t\tcrowdin.log(fmt.Sprintf(\" BINGO dirId=%d Crowdin dir name %s\", dirId, crwdPrjctDirName.Data.Name))\r\n\t\t\t\t\t\t\tbreak // Done for that one\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif !found {\r\n\t\t\t\t\t\treturn 0, \"\", errors.New(fmt.Sprintf(\"LookupDirId() - Error: can't match directory names with Crowdin path.\"))\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn 0, \"\", errors.New(\"LookupDirId() - Error: mismatch between # of folder found and # of folder expected.\")\r\n\t\t}\r\n\t}\r\n\r\n\treturn dirId, name, nil\r\n}", "func (a *accessPoint) GetDomainName() (string, error) {\n\tclusterName, err := a.GetClusterName()\n\tif err != nil && !trace.IsNotFound(err) {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\t// Return an empty domain name rather than an error b/c this method is\n\t// called by Teleport's auth middleware which does not handle not found\n\t// errors currently.\n\tif trace.IsNotFound(err) {\n\t\treturn \"\", nil\n\t}\n\treturn clusterName.GetClusterName(), nil\n}", "func (o LookupDomainNameResultOutput) CloudfrontDomainName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDomainNameResult) string { return v.CloudfrontDomainName }).(pulumi.StringOutput)\n}", "func (r Dns_Secondary) GetByDomainName(name *string) (resp []datatypes.Dns_Secondary, err error) {\n\tparams := []interface{}{\n\t\tname,\n\t}\n\terr = r.Session.DoRequest(\"SoftLayer_Dns_Secondary\", \"getByDomainName\", params, &r.Options, &resp)\n\treturn\n}", "func (l *Libvirt) DomainLookupByID(ID int32) (rDom Domain, err error) {\n\tvar buf []byte\n\n\targs := DomainLookupByIDArgs {\n\t\tID: ID,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(22, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Dom: Domain\n\t_, err = dec.Decode(&rDom)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func DNSName(hostport string) (string, error) {\n\thost, err := Host(hostport)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\tif ip := net.ParseIP(host); len(ip) != 0 {\n\t\treturn \"\", trace.BadParameter(\"%v is an IP address\", host)\n\t}\n\treturn host, nil\n}", "func (l *Libvirt) DomainGetHostname(Dom Domain, Flags DomainGetHostnameFlags) (rHostname string, err error) {\n\tvar buf []byte\n\n\targs := DomainGetHostnameArgs {\n\t\tDom: Dom,\n\t\tFlags: Flags,\n\t}\n\n\tbuf, err = encode(&args)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar r response\n\tr, err = l.requestStream(277, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Return value unmarshaling\n\ttpd := typedParamDecoder{}\n\tct := map[string]xdr.TypeDecoder{\"libvirt.TypedParam\": tpd}\n\trdr := bytes.NewReader(r.Payload)\n\tdec := xdr.NewDecoderCustomTypes(rdr, 0, ct)\n\t// Hostname: string\n\t_, err = dec.Decode(&rHostname)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *client) getCloudID(cloudRef string) string {\n\tparts := strings.Split(cloudRef, \"/\")\n\treturn parts[len(parts)-1]\n}", "func (g *Gandi) GetDomain(fqdn string) (domain Domain, err error) {\n\t_, err = g.askGandi(mGET, \"domains/\"+fqdn, nil, &domain)\n\treturn\n}", "func (lc *LibvirtConnect) GetDomainByUUIDString(uuid string) (*LibvirtDomain, error) {\n\treturn nil, fmt.Errorf(\"not supported\")\n}" ]
[ "0.6280613", "0.59721607", "0.5955924", "0.59257716", "0.5804063", "0.5770586", "0.57447374", "0.5641713", "0.5604987", "0.5594733", "0.5567953", "0.5559334", "0.5520176", "0.5501989", "0.54701555", "0.5468714", "0.5436906", "0.5434725", "0.5403778", "0.5378927", "0.53753287", "0.53753287", "0.53702915", "0.5354093", "0.5325375", "0.5296344", "0.5289409", "0.52744544", "0.52720857", "0.52689093", "0.526159", "0.5243816", "0.5235758", "0.5215685", "0.5202474", "0.51827323", "0.5177941", "0.5168529", "0.51529145", "0.51396", "0.5138758", "0.51282275", "0.51262873", "0.51250225", "0.51235616", "0.5099171", "0.5099018", "0.50943756", "0.50855523", "0.5085542", "0.5084166", "0.50723684", "0.50617677", "0.5059983", "0.5056114", "0.5053028", "0.5044955", "0.504166", "0.5037522", "0.50293505", "0.50266016", "0.50141966", "0.5013158", "0.500643", "0.50045335", "0.50006336", "0.4998432", "0.4998432", "0.49960363", "0.49879935", "0.4986811", "0.49863642", "0.49808854", "0.49790487", "0.49788725", "0.49726805", "0.49695376", "0.49684587", "0.49665767", "0.49508965", "0.49408174", "0.49395466", "0.49361032", "0.49298412", "0.49297228", "0.49283102", "0.4927071", "0.4925143", "0.492033", "0.49158335", "0.4915153", "0.49131548", "0.49123526", "0.49116495", "0.49108055", "0.49089652", "0.49004695", "0.49003023", "0.48859748", "0.48831317" ]
0.82583183
0
returns a delivery service xmlId for a cdn by host regex.
func getXMLID(cdnID int64, hostRegex string, tx *sql.Tx) (string, bool, error) { q := ` SELECT ds.xml_id from deliveryservice ds JOIN deliveryservice_regex dr on ds.id = dr.deliveryservice AND ds.cdn_id = $1 JOIN regex r on r.id = dr.regex WHERE r.pattern = $2 ` xmlID := "" if err := tx.QueryRow(q, cdnID, hostRegex).Scan(&xmlID); err != nil { if err == sql.ErrNoRows { return "", false, nil } return "", false, errors.New("querying xml id: " + err.Error()) } return xmlID, true, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (resolver nameResolver) ExtractServiceId(host string) string {\n\tresourceName := strings.Split(host, \".\")[0]\n\treturn strings.TrimPrefix(resourceName, resolver.resourceNamePrefix)\n}", "func (i SourceInfo) ExternalServiceID() int64 {\n\tps := strings.SplitN(i.ID, \":\", 3)\n\tif len(ps) != 3 {\n\t\treturn -1\n\t}\n\n\tid, err := strconv.ParseInt(ps[2], 10, 64)\n\tif err != nil {\n\t\treturn -1\n\t}\n\n\treturn id\n}", "func GetHostID() string {\n\tif cachedHostID != \"\" {\n\t\treturn cachedHostID\n\t}\n\n\tecsMetadataURI := os.Getenv(\"ECS_CONTAINER_METADATA_URI_V4\")\n\tif ecsMetadataURI != \"\" {\n\t\thostID, err := getHostIDFromECS(ecsMetadataURI + \"/task\")\n\t\tif err == nil {\n\t\t\tcachedHostID = hostID\n\t\t\treturn cachedHostID\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"Failed to get task ARN from ECS metadata v4 endpoint: %v\\n\", err)\n\t}\n\n\tecsMetadataURI = os.Getenv(\"ECS_CONTAINER_METADATA_URI\")\n\tif ecsMetadataURI != \"\" {\n\t\thostID, err := getHostIDFromECS(ecsMetadataURI + \"/task\")\n\t\tif err == nil {\n\t\t\tcachedHostID = hostID\n\t\t\treturn cachedHostID\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"Failed to get task ARN from ECS metadata v3 endpoint: %v\\n\", err)\n\t}\n\n\thostID, errECS := getHostIDFromECS(\"http://169.254.170.2/v2/metadata\")\n\tif errECS == nil {\n\t\tcachedHostID = hostID\n\t\treturn cachedHostID\n\t}\n\n\thostID, errEC2 := getHostIDFromEC2()\n\tif errEC2 == nil {\n\t\tcachedHostID = hostID\n\t\treturn cachedHostID\n\t}\n\n\thostID, errIF := getHostIDFromInterfaces()\n\tif errIF == nil {\n\t\tcachedHostID = hostID\n\t\treturn cachedHostID\n\t}\n\n\thostID, errRand := getRandomHostID()\n\tif errRand == nil {\n\t\tcachedHostID = hostID\n\t\treturn cachedHostID\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"Failed to get task ARN from ECS metadata v2 endpoint: %v\\n\", errECS)\n\tfmt.Fprintf(os.Stderr, \"Failed to get instance ID from EC2 metadata endpoint: %v\\n\", errEC2)\n\tfmt.Fprintf(os.Stderr, \"Failed to get IP address from network interface: %v\\n\", errIF)\n\tfmt.Fprintf(os.Stderr, \"Failed to get random host ID: %v\\n\", errRand)\n\tpanic(\"Unable to obtain a valid host ID\")\n}", "func HostToService(host string, externalApex string) (string, error) {\n\t// First, prepend a \".\" to root domain\n\texternalApex = \".\" + strings.ToLower(externalApex)\n\n\t// For safety, set host to lowercase\n\thost = strings.ToLower(host)\n\n\t// Host may contain a port, so chop it off\n\tcolonIndex := strings.Index(host, \":\")\n\tif colonIndex > -1 {\n\t\thost = host[:colonIndex]\n\t}\n\n\t// Check that host ends with subdomain\n\tif len(host) <= len(externalApex) {\n\t\treturn \"\", fmt.Errorf(\"Host is less than root domain length\")\n\t}\n\n\tsubdomainLength := len(host) - len(externalApex)\n\tif host[subdomainLength:] != externalApex {\n\t\treturn \"\", fmt.Errorf(\"Does not contain root domain\")\n\t}\n\n\t// Return subdomain\n\treturn host[:subdomainLength], nil\n}", "func getHostId() (uint64, error) {\n\ta := getLocalIP()\n\tip := (uint64(a[0]) << 24) + (uint64(a[1]) << 16) + (uint64(a[2]) << 8) + uint64(a[3])\n\treturn ip % MaxHostId, nil\n}", "func (o *NetworkLicenseFile) GetHostId() string {\n\tif o == nil || o.HostId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.HostId\n}", "func ServiceInDcByTag(tag, name, dc string) (Address, error) {\n\tsrvs, err := srv(tag, name, dc)\n\tif err != nil {\n\t\treturn Address{}, err\n\t}\n\tsrv := srvs[rand.Intn(len(srvs))]\n\treturn srv, nil\n}", "func HostID(nomad *NomadServer, hostname *string) (*Host, error) {\n\thosts, _, err := Hosts(nomad)\n\tif err != nil {\n\t\treturn &Host{}, err\n\t}\n\tfor _, host := range hosts {\n\t\tif *hostname == host.Name {\n\t\t\treturn &host, nil\n\t\t}\n\t}\n\tbuf := log(\"event\", \"node_not_found\", \"hostname\", hostname)\n\treturn &Host{}, errors.New(buf.String())\n\n}", "func GetHostUUID(nbmaster string, httpClient *http.Client, jwt string, host string) string {\r\n fmt.Printf(\"\\nGet the UUID of host %s...\\n\", host)\r\n\r\n uri := \"https://\" + nbmaster + \":\" + port + \"/netbackup/config/hosts\";\r\n\r\n request, _ := http.NewRequest(http.MethodGet, uri, nil)\r\n query := request.URL.Query()\r\n query.Add(\"filter\", \"hostName eq '\" + host + \"'\")\r\n request.URL.RawQuery = query.Encode()\r\n\r\n request.Header.Add(\"Authorization\", jwt);\r\n request.Header.Add(\"Accept\", contentTypeV3);\r\n\r\n response, err := httpClient.Do(request)\r\n\r\n hostUuid := \"\"\r\n if err != nil {\r\n fmt.Printf(\"The HTTP request failed with error: %s\\n\", err)\r\n panic(\"Unable to get the host UUID\")\r\n } else {\r\n if response.StatusCode == 200 {\r\n data, _ := ioutil.ReadAll(response.Body)\r\n var obj interface{}\r\n json.Unmarshal(data, &obj)\r\n response := obj.(map[string]interface{})\r\n hosts := response[\"hosts\"].([]interface{})\r\n hostUuid = ((hosts[0].(map[string]interface{}))[\"uuid\"]).(string)\r\n fmt.Printf(\"Host UUID: %s\\n\", hostUuid);\r\n } else {\r\n printErrorResponse(response)\r\n }\r\n }\r\n\r\n return hostUuid\r\n}", "func ExtractHostID(m Node) string {\n\thostNodeID, _ := m.Latest.Lookup(HostNodeID)\n\thostID, _, _ := ParseNodeID(hostNodeID)\n\treturn hostID\n}", "func GetSSLKeysByHostName(w http.ResponseWriter, r *http.Request) {\n\tinf, userErr, sysErr, errCode := api.NewInfo(r, []string{\"hostname\"}, nil)\n\tif userErr != nil || sysErr != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, errCode, userErr, sysErr)\n\t\treturn\n\t}\n\tdefer inf.Close()\n\n\tif inf.Config.RiakEnabled == false {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusServiceUnavailable, errors.New(\"the Riak service is unavailable\"), errors.New(\"getting SSL keys from Riak by host name: Riak is not configured\"))\n\t\treturn\n\t}\n\n\thostName := inf.Params[\"hostname\"]\n\tdomainName := \"\"\n\thostRegex := \"\"\n\tstrArr := strings.Split(hostName, \".\")\n\tln := len(strArr)\n\tif ln > 1 {\n\t\tfor i := 2; i < ln-1; i++ {\n\t\t\tdomainName += strArr[i] + \".\"\n\t\t}\n\t\tdomainName += strArr[ln-1]\n\t\thostRegex = `.*\\.` + strArr[1] + `\\..*`\n\t}\n\n\t// lookup the cdnID\n\tcdnID, ok, err := getCDNIDByDomainname(domainName, inf.Tx.Tx)\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"getting cdn id by domain name: \"+err.Error()))\n\t\treturn\n\t}\n\tif !ok {\n\t\tapi.WriteRespAlert(w, r, tc.InfoLevel, \" - a cdn does not exist for the domain: \"+domainName+\" parsed from hostname: \"+hostName)\n\t\treturn\n\t}\n\t// now lookup the deliveryservice xmlID\n\txmlID, ok, err := getXMLID(cdnID, hostRegex, inf.Tx.Tx)\n\tif err != nil {\n\t\tapi.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, errors.New(\"getting xml id: \"+err.Error()))\n\t\treturn\n\t}\n\tif !ok {\n\t\tapi.WriteRespAlert(w, r, tc.InfoLevel, \" - a delivery service does not exist for a host with hostname of \"+hostName)\n\t\treturn\n\t}\n\n\tgetSSLKeysByXMLIDHelper(xmlID, inf, w, r)\n}", "func getHostedZoneIDByNameLookup(svc *route53.Route53, hostedZoneName string) (string, error) {\n\n\tlistParams := &route53.ListHostedZonesByNameInput{\n\t\tDNSName: aws.String(hostedZoneName), // Required\n\t\tMaxItems: aws.String(\"1\"),\n\t}\n\thzOut, err := svc.ListHostedZonesByName(listParams)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tzones := hzOut.HostedZones\n\n\tif len(zones) < 1 {\n\t\tfmt.Printf(\"No zone found for %s\\n\", hostedZoneName)\n\t\treturn \"\", err\n\t}\n\n\tzoneID := *zones[0].Id\n\tzoneName := *zones[0].Name\n\n\t// Safety check because sometimes the first row is not the same hosted zone you are looking for,\n\t// but rather the first zone that is found and if the zones does not exist, it will return\n\t// the nearest zone which is not what you are looking for\n\tif zoneName != hostedZoneName {\n\t\tlog.Fatalf(\"Hosted zones names do not match, quiting: [%s] - [%s]\", hostedZoneName, zoneName)\n\t}\n\n\t// remove the /hostedzone/ path if it's there\n\tif strings.HasPrefix(zoneID, \"/hostedzone/\") {\n\t\tzoneID = strings.TrimPrefix(zoneID, \"/hostedzone/\")\n\t}\n\n\treturn zoneID, nil\n}", "func (r *RegisterMonitor) serviceID() string {\n\tid := fmt.Sprintf(\"%s-proxy\", r.Service)\n\tif r.IDSuffix != \"\" {\n\t\tid += \"-\" + r.IDSuffix\n\t}\n\n\treturn id\n}", "func (daemon *DaemonListening) getHostRegexFormat() (string, error) {\n\t// Return wildcard if no hosts were specified by the user\n\tif len(daemon.Hosts) == 0 {\n\t\treturn \".*\", nil\n\t}\n\t// Get all hosts in a regex-ready format\n\tvar hostsFormat bytes.Buffer\n\tfor i, h := range daemon.Hosts {\n\t\tif i != 0 {\n\t\t\thostsFormat.WriteString(\"|\")\n\t\t}\n\n\t\thostHex, err := network.GetPackedReprFromIP(h)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tdaemon.contextLogger.Tracef(\"Scanning host [%s] with HEX [%s]\", h, hostHex)\n\t\thostsFormat.WriteString(fmt.Sprintf(\"(%s)\", hostHex))\n\t}\n\treturn hostsFormat.String(), nil\n}", "func getHostFromUUID(id string) (*model.Host, error) {\n\thosts, err := driver.GetHosts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, host := range *hosts {\n\t\tif host.UUID == id {\n\t\t\t// Host Matches\n\t\t\tlog.Tracef(\"current host matches with id=%s\", id)\n\t\t\treturn host, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"no host found with id %s\", id)\n}", "func hostnameForService(svc string) string {\n\n\tparts := strings.Split(svc, \"/\")\n\tif len(parts) < 2 {\n\t\treturn parts[0]\n\t}\n\tif len(parts) > 2 {\n\t\tlog.Printf(\"Malformated service identifier [%s] - Hostname will be truncated\", svc)\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", parts[1], parts[0])\n\n}", "func getCDNIDByDomainname(domainName string, tx *sql.Tx) (int64, bool, error) {\n\tcdnID := int64(0)\n\tif err := tx.QueryRow(`SELECT id from cdn WHERE domain_name = $1`, domainName).Scan(&cdnID); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn 0, false, nil\n\t\t}\n\t\treturn 0, false, err\n\t}\n\treturn cdnID, true, nil\n}", "func extractTenantID(addr uint64, nc NetConfig) uint64 {\n\tendpointBits := nc.EndpointBits()\n\tsegmentBits := nc.SegmentBits()\n\ttenantBits := nc.TenantBits()\n\ttid := (addr >> (endpointBits + segmentBits)) & ((1 << tenantBits) - 1)\n\treturn tid\n}", "func generateClientID(groupID string) string {\n\thostName, err := os.Hostname()\n\tif err != nil || len(hostName) == 0 {\n\t\tnow := time.Now().UnixNano()\n\t\thostName = strconv.FormatInt(now, 10)\n\t}\n\treturn fmt.Sprintf(\"%s-%s\", groupID, hostName)\n}", "func NewGetByIDHostContext(ctx context.Context, r *http.Request, service *goa.Service) (*GetByIDHostContext, error) {\n\tvar err error\n\tresp := goa.ContextResponse(ctx)\n\tresp.Service = service\n\treq := goa.ContextRequest(ctx)\n\treq.Request = r\n\trctx := GetByIDHostContext{Context: ctx, ResponseData: resp, RequestData: req}\n\tparamHostID := req.Params[\"hostID\"]\n\tif len(paramHostID) > 0 {\n\t\trawHostID := paramHostID[0]\n\t\trctx.HostID = rawHostID\n\t}\n\treturn &rctx, err\n}", "func getPxEndpointVersionFromUrl(specGenUrl string) (string, error) {\n\tu, err := url.Parse(specGenUrl)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to parse URL [%s], Err: %v\", specGenUrl, err)\n\t}\n\treturn strings.Trim(u.Path, \"/\"), nil\n}", "func (s *Service) rcmmndHost(mid int64) (host string) {\n\t// if mid=0, let host is 1: base recommend\n\tyu := mid % 20\n\tg := s.rcmmndGroup[yu]\n\tif hosts, ok := s.rcmmndHosts[g]; ok {\n\t\tif len(hosts) == 1 {\n\t\t\thost = hosts[0]\n\t\t} else {\n\t\t\thost = hosts[rand.Intn(len(hosts))]\n\t\t}\n\t}\n\treturn\n}", "func getInstance(entry *mdns.ServiceEntry) (string, error) {\n\tif entry.AddrV4 != nil {\n\t\tinstance := fmt.Sprintf(\"%s:%d\", entry.AddrV4.String(), entry.Port)\n\t\treturn instance, nil\n\t} else if entry.AddrV6 != nil {\n\t\tinstance := fmt.Sprintf(\"%s:%d\", entry.AddrV6.String(), entry.Port)\n\t\treturn instance, nil\n\t} else {\n\t\terr := fmt.Errorf(\"invalid mdns entry: %v\", entry)\n\t\treturn \"\", err\n\t}\n}", "func serviceHostname(name string) string {\n\t// TODO include datacenter in Hostname?\n\t// consul DNS uses \"redis.service.us-east-1.consul\" -> \"[<optional_tag>].<svc>.service.[<optional_datacenter>].consul\"\n\treturn fmt.Sprintf(\"%s.service.consul\", name)\n}", "func parseServiceURL(path string) (provider, resource string) {\n\tvar (\n\t\tservicePattern *regexp.Regexp = regexp.MustCompile(`(?i)subscriptions/.+/providers/(.+?)/(.+?)$`)\n\t\tmatch []string = servicePattern.FindStringSubmatch(path)\n\t)\n\n\tprovider = \"unknown\"\n\tresource = \"unknown\"\n\n\tif len(match) > 0 {\n\t\tprovider = strings.ReplaceAll(strings.ToLower(match[1]), \"microsoft.\", \"\")\n\t\tresource = strings.ToLower(match[2])\n\t} else if _, err := regexp.Match(`(?i)subscriptions/.+/resourcegroups/?[^/]*$`, []byte(path)); err == nil {\n\t\tprovider = \"resources\"\n\t\tresource = \"groups\"\n\t}\n\n\treturn provider, resource\n}", "func extractIDFromPath(url string) (string, error) {\n result := reExtractFileID.FindStringSubmatch(url)\n if len(result) != 2 {\n return \"\", tusd.ErrNotFound\n }\n return result[1], nil\n}", "func ResourceToHostID(res pcommon.Resource) (HostID, bool) {\n\tvar cloudAccount, hostID, provider string\n\n\tattrs := res.Attributes()\n\n\tif attrs.Len() == 0 {\n\t\treturn HostID{}, false\n\t}\n\n\tif attr, ok := attrs.Get(conventions.AttributeCloudAccountID); ok {\n\t\tcloudAccount = attr.Str()\n\t}\n\n\tif attr, ok := attrs.Get(conventions.AttributeHostID); ok {\n\t\thostID = attr.Str()\n\t}\n\n\tif attr, ok := attrs.Get(conventions.AttributeCloudProvider); ok {\n\t\tprovider = attr.Str()\n\t}\n\n\tswitch provider {\n\tcase conventions.AttributeCloudProviderAWS:\n\t\tvar region string\n\t\tif attr, ok := attrs.Get(conventions.AttributeCloudRegion); ok {\n\t\t\tregion = attr.Str()\n\t\t}\n\t\tif hostID == \"\" || region == \"\" || cloudAccount == \"\" {\n\t\t\tbreak\n\t\t}\n\t\treturn HostID{\n\t\t\tKey: HostIDKeyAWS,\n\t\t\tID: fmt.Sprintf(\"%s_%s_%s\", hostID, region, cloudAccount),\n\t\t}, true\n\tcase conventions.AttributeCloudProviderGCP:\n\t\tif cloudAccount == \"\" || hostID == \"\" {\n\t\t\tbreak\n\t\t}\n\t\treturn HostID{\n\t\t\tKey: HostIDKeyGCP,\n\t\t\tID: fmt.Sprintf(\"%s_%s\", cloudAccount, hostID),\n\t\t}, true\n\tcase conventions.AttributeCloudProviderAzure:\n\t\tif cloudAccount == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tid := azureID(attrs, cloudAccount)\n\t\tif id == \"\" {\n\t\t\tbreak\n\t\t}\n\t\treturn HostID{\n\t\t\tKey: HostIDKeyAzure,\n\t\t\tID: id,\n\t\t}, true\n\t}\n\n\tif attr, ok := attrs.Get(conventions.AttributeHostName); ok {\n\t\treturn HostID{\n\t\t\tKey: HostIDKeyHost,\n\t\t\tID: attr.Str(),\n\t\t}, true\n\t}\n\n\treturn HostID{}, false\n}", "func getTransferId(xmlMessage string) string {\n var transferId string\n\n // Create an parsed XML document\n doc, err := xmlquery.Parse(strings.NewReader(xmlMessage))\n if err != nil {\n panic(err)\n }\n\n // Get required elements\n transaction := xmlquery.FindOne(doc, \"//transaction\")\n if transaction != nil {\n transferId = transaction.SelectAttr(\"ID\")\n }\n return transferId\n}", "func generateCID(namestring string) cid.Cid {\n\t// Hash the service content ID with SHA256\n\thash := sha256.Sum256([]byte(namestring))\n\t// Append the hash with the hashing codec ID for SHA2-256 (0x12),\n\t// the digest size (0x20) and the hash of the service content ID\n\tfinalhash := append([]byte{0x12, 0x20}, hash[:]...)\n\t// Encode the fullhash to Base58\n\tb58string := base58.Encode(finalhash)\n\n\t// Generate a Multihash from the base58 string\n\tmulhash, err := multihash.FromB58String(string(b58string))\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalln(\"Failed to Generate Service CID!\")\n\t}\n\n\t// Generate a CID from the Multihash\n\tcidvalue := cid.NewCidV1(12, mulhash)\n\t// Return the CID\n\treturn cidvalue\n}", "func id_generate_4(ip string, port string) string {\n\tips := strings.Split(ip, \".\")\n\n\tif len(ips) != 4 {\n\t\tfmt.Println(DHT_PREFIX+\"Malformed IPv4\")\n\t\treturn \"0\"\n\t}\n\n\tid := \"\"\n\n\t// fill 0's if not an three digits number in each part of IPs\n\tfor _,v := range ips {\n\t\tid = id + strings.Repeat(\"0\", 3-len(v)) + v\n\t}\n\n\treturn id+port\n}", "func ExfiltratedHostname(domain, server string) *Tsk {\n\tt := newTsk(\"exfiltrated.com\")\n\tresp, err := http.Get(fmt.Sprintf(\"http://exfiltrated.com/queryhostname.php?hostname=%s\", domain))\n\tif err != nil {\n\t\tt.SetErr(err)\n\t\treturn t\n\t}\n\tdoc, err := goquery.NewDocumentFromResponse(resp)\n\tif err != nil {\n\t\tt.SetErr(err)\n\t\treturn t\n\t}\n\n\twg := sync.WaitGroup{}\n\tmutex := sync.Mutex{}\n\n\tdoc.Selection.Find(\"td:nth-child(1)\").Each(func(_ int, s *goquery.Selection) {\n\t\twg.Add(1)\n\t\tgo func(hostname string) {\n\t\t\tdefer wg.Done()\n\t\t\tips, err := LookupName(hostname, server)\n\t\t\tif err != nil || len(ips) == 0 {\n\t\t\t\tcfqdn, err := LookupCname(hostname, server)\n\t\t\t\tif err != nil || cfqdn == \"\" {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tips, err = LookupName(cfqdn, server)\n\t\t\t\tif err != nil || len(ips) == 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tmutex.Lock()\n\t\t\tfor _, ip := range ips {\n\t\t\t\tt.AddResult(ip, hostname)\n\t\t\t}\n\t\t\tmutex.Unlock()\n\t\t}(s.Text())\n\t})\n\twg.Wait()\n\treturn t\n}", "func getIDFromURL(url string) int {\n\tprojURLSlices := strings.Split(url, \"/\")\n\tif len(projURLSlices) != 0 {\n\t\ti, _ := strconv.ParseInt(projURLSlices[len(projURLSlices)-1], 10, 32)\n\t\treturn int(i)\n\t}\n\treturn -1\n}", "func getRandomServiceID(c *C) string {\n\tserviceID, err := utils.NewUUID()\n\tif err != nil {\n\t\tc.Fatalf(\"Failed to generate random service ID: %s\", err)\n\t}\n\treturn serviceID\n}", "func hosten(dom string) string {\n\tdom = strings.TrimSpace(dom)\n\tvar domain string\n\tif strings.HasPrefix(dom, \"http:\") ||\n\t\tstrings.HasPrefix(dom, \"https:\") {\n\t\tdmt, err := url.Parse(dom)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdomain = dmt.Host\n\t} else {\n\t\tdomain = dom\n\t}\n\treturn domain\n}", "func defaultHostId(p peer.ID, prefix string) string {\n\tif os.Getenv(\"HOST_ID\") == \"\" {\n\t\treturn fmt.Sprintf(\"%s-%s\", prefix, shortID(p))\n\t}\n\treturn fmt.Sprintf(\"%s-%s-%s\", prefix, os.Getenv(\"HOST_ID\"), shortID(p))\n}", "func hostFunc(ctx *TemplateContext) func(...string) (interface{}, error) {\n\treturn func(s ...string) (result interface{}, err error) {\n\t\tresult, err = ctx.GetHost(s...)\n\t\tif _, ok := err.(NotFoundError); ok {\n\t\t\tlog.Debug(err)\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn\n\t}\n}", "func getHost(host_url string) (host string, err error) {\n\tu, err := url.Parse(host_url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Split(u.Host, \":\")[0], nil\n}", "func (c Config) ServiceID() string {\n\treturn c.ID\n}", "func getWorkflowNameFromHost(host string) string {\n\tmatches := re.FindAllString(host, -1)\n\tif matches[0] != \"\" {\n\t\treturn matches[0]\n\t}\n\treturn \"\"\n}", "func getDockerID() (string){\n\tid, _ := os.Hostname()\n\treturn id\n}", "func getSvcID(k8sAPI *k8s.API, clusterIP string, log *logging.Entry) (*watcher.ServiceID, error) {\n\tobjs, err := k8sAPI.Svc().Informer().GetIndexer().ByIndex(watcher.PodIPIndex, clusterIP)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, err.Error())\n\t}\n\tservices := make([]*corev1.Service, 0)\n\tfor _, obj := range objs {\n\t\tservice := obj.(*corev1.Service)\n\t\tservices = append(services, service)\n\t}\n\tif len(services) > 1 {\n\t\tconflictingServices := []string{}\n\t\tfor _, service := range services {\n\t\t\tconflictingServices = append(conflictingServices, fmt.Sprintf(\"%s:%s\", service.Namespace, service.Name))\n\t\t}\n\t\tlog.Warnf(\"found conflicting %s cluster IP: %s\", clusterIP, strings.Join(conflictingServices, \",\"))\n\t\treturn nil, status.Errorf(codes.FailedPrecondition, \"found %d services with conflicting cluster IP %s\", len(services), clusterIP)\n\t}\n\tif len(services) == 0 {\n\t\treturn nil, nil\n\t}\n\tservice := &watcher.ServiceID{\n\t\tNamespace: services[0].Namespace,\n\t\tName: services[0].Name,\n\t}\n\treturn service, nil\n}", "func IDFromName(client *eclcloud.ServiceClient, name string) (string, error) {\n\tcount := 0\n\tid := \"\"\n\n\tlistOpts := ListOpts{\n\t\tName: name,\n\t}\n\n\tpages, err := List(client, listOpts).AllPages()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tall, err := ExtractCommonFunctionGateways(pages)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, s := range all {\n\t\tif s.Name == name {\n\t\t\tcount++\n\t\t\tid = s.ID\n\t\t}\n\t}\n\n\tswitch count {\n\tcase 0:\n\t\treturn \"\", eclcloud.ErrResourceNotFound{Name: name, ResourceType: \"common_function_gateway\"}\n\tcase 1:\n\t\treturn id, nil\n\tdefault:\n\t\treturn \"\", eclcloud.ErrMultipleResourcesFound{Name: name, Count: count, ResourceType: \"common_function_gateway\"}\n\t}\n}", "func getInstanceID(providerID string) string {\n\tproviderTokens := strings.Split(providerID, \"/\")\n\treturn providerTokens[len(providerTokens)-1]\n}", "func getInstanceID(providerID string) string {\n\tproviderTokens := strings.Split(providerID, \"/\")\n\treturn providerTokens[len(providerTokens)-1]\n}", "func (scs *StorageContractSet) GetContractIDByHostID(hostID enode.ID) storage.ContractID {\n\tscs.lock.Lock()\n\tdefer scs.lock.Unlock()\n\treturn scs.hostToContractID[hostID]\n}", "func URL(url string) string {\n\tscheme, host, _, path, query := unpackURL(url)\n\t// log.S(\"url\", url).S(\"host\", host).Debug(fmt.Sprintf(\"should discover: %v\", shouldDiscoverHost(host)))\n\tif !shouldDiscoverHost(host) {\n\t\treturn url\n\t}\n\tsrvs, err := Services(host)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn url\n\t}\n\t// log.I(\"len_srvs\", len(srvs)).Debug(\"service entries\")\n\tif len(srvs) == 0 {\n\t\treturn url\n\t}\n\tsrv := srvs[rand.Intn(len(srvs))]\n\treturn packURL(scheme, srv.String(), \"\", path, query)\n}", "func (p *protocol) DiscoveryID(chanID int) string {\n\treturn fmt.Sprintf(\"/pcp/%d/%d\", p.TimeSlotStart().UnixNano(), chanID)\n}", "func (st *ServiceType) id() int {\n\tid, _ := strconv.Atoi(st.ID)\n\treturn id\n}", "func serviceMaintCheckID(serviceID string) types.CheckID {\n\treturn types.CheckID(structs.ServiceMaintPrefix + serviceID)\n}", "func (c *Config) GetService(host string) *Service {\n\tdomainPattern := regexp.MustCompile(`(\\w*\\:\\/\\/)?(.+)` + c.Domain)\n\tparts := domainPattern.FindAllString(host, -1)\n\t//we must lock the access as the configuration can be dynamically loaded\n\tselect {\n\tcase srv := <-configChan:\n\t\tc.Services = srv\n\tdefault:\n\t}\n\tfor _, s := range c.Services {\n\t\tif len(parts) > 0 && s.Name+c.Domain == parts[0] {\n\t\t\treturn &s\n\t\t}\n\t}\n\n\treturn nil\n}", "func (fe *BaseFrontEnd) GetId(p string) (id string, err error) {\n\t// Given an absolute path, make it relative to project\n\tif path.IsAbs(p) {\n\t\tp, err = filepath.Rel(fe.ProjectDir, p)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\tp = strings.Replace(p, string(os.PathSeparator), \"-\", -1)\n\n\t// Remove extention\n\tid = strings.TrimSuffix(p, filepath.Ext(p))\n\n\treturn id, nil\n}", "func extractHost(cfg *config.Config, r *http.Request) string {\n\tif cfg.Host != \"\" {\n\t\treturn cfg.Host\n\t}\n\n\treturn fmt.Sprintf(\"http://%s\", r.Host)\n}", "func NewGetDogsByHostIDHostContext(ctx context.Context, r *http.Request, service *goa.Service) (*GetDogsByHostIDHostContext, error) {\n\tvar err error\n\tresp := goa.ContextResponse(ctx)\n\tresp.Service = service\n\treq := goa.ContextRequest(ctx)\n\treq.Request = r\n\trctx := GetDogsByHostIDHostContext{Context: ctx, ResponseData: resp, RequestData: req}\n\tparamHostID := req.Params[\"hostID\"]\n\tif len(paramHostID) > 0 {\n\t\trawHostID := paramHostID[0]\n\t\trctx.HostID = rawHostID\n\t}\n\treturn &rctx, err\n}", "func id(s string) string {\n\treturn uuid.NewV5(namespaceUUID, s).String()\n}", "func getSearchID() (string, error) {\n\t// Unfortunately there isn't a GET smartgroup by name endpoint, so we\n\t// need to enumerate them all to find the one we want.\n\tvar ret string\n\n\t// Fetch all of the smart groups.\n\turl, err := client.GetURL(sgURI)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\treq, err := client.BuildReq(nil, url, http.MethodGet, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tbody, err := client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tvar b types.NodesSmartgroupResponse\n\terr = json.Unmarshal(body, &b)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t// Now we need to find the smartgroupID, and from that the query.\n\tvar query string\n\tfor _, sg := range b.Smartgroups {\n\t\tif strings.Compare(sg.Name, smartgroup) == 0 {\n\t\t\tquery = sg.Query\n\t\t}\n\t}\n\tif query == \"\" {\n\t\treturn ret, nil\n\t}\n\n\t// Finally we can get a searchID.\n\tparam := client.Parameters{\n\t\tName: \"json\",\n\t\tValue: query,\n\t}\n\turl, err = client.GetURL(searchURI, param)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\treq, err = client.BuildReq(nil, url, http.MethodGet, true)\n\trawResp, err = client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tbody, err = client.ParseReq(rawResp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar bsearch types.SearchResponse\n\terr = json.Unmarshal(body, &bsearch)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tret = bsearch.SearchIDs.ID\n\n\treturn ret, nil\n}", "func extractUuid(input string) string {\n\treGetID := regexp.MustCompile(`([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})`)\n\tmatchListId := reGetID.FindAllStringSubmatch(input, -1)\n\tif len(matchListId) > 0 && len(matchListId[0]) > 0 {\n\t\treturn matchListId[len(matchListId)-1][1]\n\t}\n\treturn \"\"\n}", "func getDependencyIdForBuildInfo(dependencyAssetId string) string {\n\treturn strings.Replace(dependencyAssetId, \"/\", \":\", 1)\n}", "func CidFromString(t *testing.T, input string) cid.Cid {\n\tprefix := cid.V1Builder{Codec: cid.DagCBOR, MhType: DefaultHashFunction}\n\tcid, err := prefix.Sum([]byte(input))\n\trequire.NoError(t, err)\n\treturn cid\n}", "func (m *postgresDBRepo) GetHostServiceByHostIdServiceID(hostID, serviceID int) (models.HostService, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `\n\t\tselect hs.id, hs.host_id, hs.service_id, hs.active, hs.schedule_number, hs.schedule_unit, \n\t\t\ths.last_check, hs.status, hs.created_at, hs.updated_at, \n\t\t\ts.id, s.service_name, s.active, s.icon, s.created_at, s.updated_at, h.host_name\n\t\tfrom\n\t\t\thost_services hs \n\t\t\tleft join services s on (hs.service_id = s.id)\n\t\t\tleft join hosts h on (hs.host_id = h.id)\n\t\twhere\n\t\t\ths.host_id = $1 and hs.service_id = $2\n\t`\n\n\tvar hs models.HostService\n\n\trow := m.DB.QueryRowContext(ctx, query, hostID, serviceID)\n\n\terr := row.Scan(\n\t\t&hs.ID,\n\t\t&hs.HostID,\n\t\t&hs.ServiceID,\n\t\t&hs.Active,\n\t\t&hs.ScheduleNumber,\n\t\t&hs.ScheduleUnit,\n\t\t&hs.LastCheck,\n\t\t&hs.Status,\n\t\t&hs.CreatedAt,\n\t\t&hs.UpdatedAt,\n\t\t&hs.Service.ID,\n\t\t&hs.Service.ServiceName,\n\t\t&hs.Service.Active,\n\t\t&hs.Service.Icon,\n\t\t&hs.Service.CreatedAt,\n\t\t&hs.Service.UpdatedAt,\n\t\t&hs.HostName,\n\t)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn hs, err\n\t}\n\n\treturn hs, nil\n}", "func prnGetID(prn string) string {\n\tidx := strings.Index(prn, \"/\")\n\treturn prn[idx+1:]\n}", "func GetByRegnum(r string) (shId string) {\n\t/* select substring(regnum,1,1) as sh_id,substring(regnum,2,10) as inn, customer,substring(regnum,12,2) as Year, substring(regnum,14) from contracts_12_2015; */\n\tshId = r[:1]\n\treturn\n}", "func (c *service) Host() string {\n\treturn c.host\n}", "func (v *Libravatar) baseURL(email *mail.Address, openid *url.URL) (string, error) {\n\tvar service, protocol, domain string\n\n\tif v.useHTTPS {\n\t\tprotocol = \"https://\"\n\t\tservice = v.secureServiceBase\n\t\tdomain = v.secureFallbackHost\n\n\t} else {\n\t\tprotocol = \"http://\"\n\t\tservice = v.serviceBase\n\t\tdomain = v.fallbackHost\n\t}\n\n\thost := v.getDomain(email, openid)\n\tkey := cacheKey{service, host}\n\tnow := time.Now()\n\tv.nameCacheMutex.Lock()\n\tval, found := v.nameCache[key]\n\tv.nameCacheMutex.Unlock()\n\tif found && now.Sub(val.checkedAt) <= v.nameCacheDuration {\n\t\treturn protocol + val.target, nil\n\t}\n\n\t_, addrs, err := net.LookupSRV(service, \"tcp\", host)\n\tif err != nil && err.(*net.DNSError).IsTimeout {\n\t\treturn \"\", err\n\t}\n\n\tif len(addrs) == 1 {\n\t\t// select only record, if only one is available\n\t\tdomain = strings.TrimSuffix(addrs[0].Target, \".\")\n\t} else if len(addrs) > 1 {\n\t\t// Select first record according to RFC2782 weight\n\t\t// ordering algorithm (page 3)\n\n\t\ttype record struct {\n\t\t\tsrv *net.SRV\n\t\t\tweight uint16\n\t\t}\n\n\t\tvar (\n\t\t\ttotalWeight uint16\n\t\t\trecords []record\n\t\t\ttopPriority = addrs[0].Priority\n\t\t\ttopRecord *net.SRV\n\t\t)\n\n\t\tfor _, rr := range addrs {\n\t\t\tif rr.Priority > topPriority {\n\t\t\t\tcontinue\n\t\t\t} else if rr.Priority < topPriority {\n\t\t\t\t// won't happen, because net sorts\n\t\t\t\t// by priority, but just in case\n\t\t\t\ttotalWeight = 0\n\t\t\t\trecords = nil\n\t\t\t\ttopPriority = rr.Priority\n\t\t\t}\n\n\t\t\ttotalWeight += rr.Weight\n\n\t\t\tif rr.Weight > 0 {\n\t\t\t\trecords = append(records, record{rr, totalWeight})\n\t\t\t} else if rr.Weight == 0 {\n\t\t\t\trecords = append([]record{record{srv: rr, weight: totalWeight}}, records...)\n\t\t\t}\n\t\t}\n\n\t\tif len(records) == 1 {\n\t\t\ttopRecord = records[0].srv\n\t\t} else {\n\t\t\trandnum := uint16(rand.Intn(int(totalWeight)))\n\n\t\t\tfor _, rr := range records {\n\t\t\t\tif rr.weight >= randnum {\n\t\t\t\t\ttopRecord = rr.srv\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdomain = fmt.Sprintf(\"%s:%d\", topRecord.Target, topRecord.Port)\n\t}\n\n\tv.nameCacheMutex.Lock()\n\tv.nameCache[key] = cacheValue{checkedAt: now, target: domain}\n\tv.nameCacheMutex.Unlock()\n\treturn protocol + domain, nil\n}", "func (c *client) getCloudID(cloudRef string) string {\n\tparts := strings.Split(cloudRef, \"/\")\n\treturn parts[len(parts)-1]\n}", "func (d Config) ServiceID() string {\n\treturn d.ID\n}", "func GetPackageID(cc api.UserCC) string {\n\treturn cc.Name() + \":\" + cc.Version()\n}", "func extractServiceName(tag string) string {\n\tserviceName := strings.Replace(tag, watchedRegistry, \"\", 1)\n\tserviceName = strings.Replace(serviceName, \":\", \"-\", 1)\n\tserviceName = strings.Replace(serviceName, \"/\", \"\", -1)\n\treturn serviceName\n}", "func makeServiceName(msURL string, msOrg string, msVersion string) string {\n\n\turl := \"\"\n\tpieces := strings.SplitN(msURL, \"/\", 3)\n\tif len(pieces) >= 3 {\n\t\turl = strings.TrimSuffix(pieces[2], \"/\")\n\t\turl = strings.Replace(url, \"/\", \"-\", -1)\n\t}\n\n\tversion := \"\"\n\tvExp, err := policy.Version_Expression_Factory(msVersion)\n\tif err == nil {\n\t\tversion = fmt.Sprintf(\"%v-%v\", vExp.Get_start_version(), vExp.Get_end_version())\n\t}\n\n\treturn fmt.Sprintf(\"%v_%v_%v\", url, msOrg, version)\n\n}", "func cidConnIdentifier() func([]byte) (string, bool) {\n\treturn func(packet []byte) (string, bool) {\n\t\tpkts, err := recordlayer.UnpackDatagram(packet)\n\t\tif err != nil || len(pkts) < 1 {\n\t\t\treturn \"\", false\n\t\t}\n\t\tvar h recordlayer.Header\n\t\tif hErr := h.Unmarshal(pkts[0]); hErr != nil {\n\t\t\treturn \"\", false\n\t\t}\n\t\tif h.ContentType != protocol.ContentTypeHandshake {\n\t\t\treturn \"\", false\n\t\t}\n\t\tvar hh handshake.Header\n\t\tvar sh handshake.MessageServerHello\n\t\tfor _, pkt := range pkts {\n\t\t\tif hhErr := hh.Unmarshal(pkt[recordlayer.FixedHeaderSize:]); hhErr != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = sh.Unmarshal(pkt[recordlayer.FixedHeaderSize+handshake.HeaderLength:]); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn \"\", false\n\t\t}\n\t\tfor _, ext := range sh.Extensions {\n\t\t\tif e, ok := ext.(*extension.ConnectionID); ok {\n\t\t\t\treturn string(e.CID), true\n\t\t\t}\n\t\t}\n\t\treturn \"\", false\n\t}\n}", "func getCidFromPath(s string) string {\n\tss := strings.Split(s, \"/\")\n\treturn ss[len(ss)-1]\n\n}", "func hostSNIRegexp(tree *matchersTree, templates ...string) error {\n\ttemplate := templates[0]\n\n\tif !isASCII(template) {\n\t\treturn fmt.Errorf(\"invalid value for HostSNIRegexp matcher, %q is not a valid hostname\", template)\n\t}\n\n\tre, err := regexp.Compile(template)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"compiling HostSNIRegexp matcher: %w\", err)\n\t}\n\n\ttree.matcher = func(meta ConnData) bool {\n\t\treturn re.MatchString(meta.serverName)\n\t}\n\n\treturn nil\n}", "func getkey(selector string, domain string) string {\n\n\tvar pubkey string\n\tvar tag string\n\tvar value string\n\n\tselectors, err := net.LookupTXT(selector + \"._domainkey.\" + domain)\n\tif err != nil {\n\t\tfmt.Println(\"Signature key not found: \", err)\n\t\treturn \"\"\n\t}\n\n\t//Just looking at the first TXT record. Multiple TXT records are not a good idea.\n\tfor i := 0; i >= 0; {\n\t\ttag, value, i = nexttag(selectors[0], i)\n\n\t\tswitch tag {\n\t\tcase \"v\": //Check version if present\n\t\t\tif value != \"DKIM1\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\tcase \"p\": //extract key\n\t\t\tpubkey = value\n\t\tcase \"k\": //Check key type\n\t\t\tif value != \"rsa\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\tcase \"h\": //Check allowed hashes\n\t\t\t// Should handle a list here\n\t\t\tif value != \"sha256\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\tcase \"s\": //service type\n\t\t\t// Should potentially handle a service list here\n\t\t\tif value != \"*\" && value != \"notif\" {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t}\n\t}\n\treturn pubkey\n}", "func (b *Bing) extractDomain(url string) string {\n\t// NOTE(remy): we add the / for the regexp\n\t// NOTE(remy): we take only the first match, this is why\n\t// I don't use FindAllStringSubmatch\n\tstr := rxDomain.FindStringSubmatch(strings.ToLower(url) + \"/\")\n\tif len(str) == 2 {\n\t\treturn str[1]\n\t}\n\treturn \"\"\n}", "func init() {\n\n\t// whosonfirst-data-venue-us-ca-1533149830.tar.bz2\n\t// whosonfirst-data-venue-us-ny-latest.db.bz2\n\n\tre_distname = regexp.MustCompile(`([a-z\\-0-9]+)\\-(\\d+|latest)\\.(.*)$`)\n\n\t// this needs to be moved in to go-whosonfirst-dist\n\n\tre_disttype = regexp.MustCompile(`x\\-urn\\:([^\\:]+)\\:([^\\:]+)\\:([^\\#]+)(?:\\#(.*))?`)\n}", "func (sc *serviceCache) GetTenantID(serviceID string, getServiceFunc GetServiceDetails) (string, error) {\n\tif cachedSvc, found := sc.lookUpService(serviceID); found {\n\t\treturn cachedSvc.tenantID, nil\n\t}\n\n\tcachedSvc, err := sc.updateCache(serviceID, getServiceFunc)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn cachedSvc.tenantID, nil\n}", "func cdnHostsToNetAddrs(hosts []*config.CDN) (map[string]*supervisor.PeerHost, []dfnet.NetAddr) {\n\tcdnHostMap := make(map[string]*supervisor.PeerHost, len(hosts))\n\tnetAddrs := make([]dfnet.NetAddr, 0, len(hosts))\n\tfor _, host := range hosts {\n\t\thostID := idgen.CDNUUID(host.HostName, host.Port)\n\t\tif host.LoadLimit == 0 {\n\t\t\thost.LoadLimit = 100\n\t\t}\n\t\tcdnHostMap[hostID] = supervisor.NewCDNPeerHost(hostID, host.IP, host.HostName, host.Port, host.DownloadPort, host.SecurityGroup, host.Location,\n\t\t\thost.IDC, host.NetTopology, host.LoadLimit)\n\t\tnetAddrs = append(netAddrs, dfnet.NetAddr{\n\t\t\tType: dfnet.TCP,\n\t\t\tAddr: fmt.Sprintf(\"%s:%d\", host.IP, host.Port),\n\t\t})\n\t}\n\treturn cdnHostMap, netAddrs\n}", "func hostToResource(host string) string {\n\t// path style, I guess\n\tif host == \"s3.amazonaws.com\" {\n\t\treturn \"\"\n\t}\n\n\t// virtual hosted-style request\n\t// remove s3 aws if present\n\tsuffix := \".s3.amazonaws.com\"\n\tif strings.HasSuffix(host, suffix) {\n\t\thost = host[:len(host)-len(suffix)]\n\t} else {\n\t\t// remove :port\n\t\thost = strings.Split(host, \":\")[0]\n\t}\n\t// return custom host thing? I don't see where this is documented\n\t// for now matching example\n\treturn \"/\" + host\n}", "func (reader *ServiceReader) getServiceID(name string) string {\n\t// hash returns a base64 encoded sha256 hash that is truncated to 10 chars.\n\thash := func(v string) string {\n\t\tsum := sha256.Sum256([]byte(v))\n\t\tbase64Hash := base64.RawURLEncoding.EncodeToString(sum[:])\n\t\treturn base64Hash[:10]\n\t}\n\n\tid, found := reader.ids[name]\n\tif !found {\n\t\tid = hash(reader.guid + name)\n\t\treader.ids[name] = id\n\t}\n\n\treturn id\n}", "func getIndexerHost(cinfo *common.ClusterInfoCache, nid common.NodeId) (string, error) {\n\n\taddr, err := cinfo.GetServiceAddress(nid, \"mgmt\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thost, port, err := net.SplitHostPort(addr)\n\tif err == nil {\n\t\tif host == \"localhost\" {\n\t\t\taddr = net.JoinHostPort(\"127.0.0.1\", port)\n\t\t}\n\t}\n\n\treturn addr, nil\n}", "func callboxHostName(dut *dut.DUT) (string, error) {\n\tdutHost := dut.HostName()\n\tif host, _, err := net.SplitHostPort(dutHost); err == nil {\n\t\tdutHost = host\n\t}\n\n\tdutHost = strings.TrimSuffix(dutHost, \".cros\")\n\tif dutHost == \"localhost\" {\n\t\treturn \"\", errors.Errorf(\"unable to parse hostname from: %q, localhost not supported\", dutHost)\n\t}\n\n\tif ip := net.ParseIP(dutHost); ip != nil {\n\t\treturn \"\", errors.Errorf(\"unable to parse hostname from: %q, ip:port format not supported\", dutHost)\n\t}\n\n\thostname := strings.Split(dutHost, \"-\")\n\tif len(hostname) < 2 {\n\t\treturn \"\", errors.Errorf(\"unable to parse hostname from: %q, unknown name format\", dutHost)\n\t}\n\n\t// CallboxManager expects callbox hostnames to end in .cros\n\thostname = hostname[0 : len(hostname)-1]\n\treturn fmt.Sprintf(\"%s.cros\", strings.Join(hostname, \"-\")), nil\n}", "func (r RegistryPath) Host() string {\n\thost := string(r)\n\n\tif r.Tag() != \"\" {\n\t\thost = strings.ReplaceAll(host, \":\"+r.Tag(), \"\")\n\t}\n\n\tif !strings.Contains(host, \".\") {\n\t\treturn \"\"\n\t}\n\n\thostTokens := strings.Split(string(r), \"/\")\n\treturn hostTokens[0]\n}", "func getConfigsForHost(hostname host.Name, configs []model.Config) []model.Config {\n\tsvcConfigs := make([]model.Config, 0)\n\tfor index := range configs {\n\t\tvirtualService := configs[index].Spec.(*v1alpha3.VirtualService)\n\t\tfor _, vsHost := range virtualService.Hosts {\n\t\t\tif host.Name(vsHost).Matches(hostname) {\n\t\t\t\tsvcConfigs = append(svcConfigs, configs[index])\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn svcConfigs\n}", "func (a AppConfig) ServiceConfigID(id ServiceID) string {\n\treturn fmt.Sprintf(\"0x%x\", id)\n}", "func (h *httpCloud) ExternalID(instance string) (string, error) {\n\treturn instance, nil\n}", "func (c MockDockerClient) HostID(ctx context.Context) string {\n\tif c.HostIDFn != nil {\n\t\tfmt.Println(\"[MockDockerClient] In \", utils.CurrentFunctionName())\n\t\treturn c.HostIDFn(ctx)\n\t}\n\tpanic(fmt.Sprintf(\"No function defined for: %s\", utils.CurrentFunctionName()))\n}", "func newClientID() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tip, err := getIP()\n\t\tif err != nil {\n\t\t\tbuffer := make([]byte, 8)\n\t\t\t_, _ = rand.Read(buffer)\n\t\t\thostname = fmt.Sprintf(\"%X\", buffer)\n\n\t\t} else {\n\t\t\thostname = ip.String()\n\t\t}\n\t}\n\ttimestamp := time.Now().UTC().Format(time.RFC3339)\n\t// sarama validation regexp for the client ID doesn't allow ':' characters\n\ttimestamp = strings.Replace(timestamp, \":\", \".\", -1)\n\treturn fmt.Sprintf(\"pixy_%s_%s_%d\", hostname, timestamp, os.Getpid())\n}", "func addDomainsWithHost(domains map[string]*lazyloadv1alpha1.Destinations, sf *lazyloadv1alpha1.ServiceFence, nsSvcCache *NsSvcCache,\n\trules []*domainAliasRule,\n) {\n\tcheckStatus := func(now int64, strategy *lazyloadv1alpha1.RecyclingStrategy) lazyloadv1alpha1.Destinations_Status {\n\t\tswitch {\n\t\tcase strategy.Stable != nil:\n\t\t\t// ...\n\t\tcase strategy.Deadline != nil:\n\t\t\tif now > strategy.Deadline.Expire.Seconds {\n\t\t\t\treturn lazyloadv1alpha1.Destinations_EXPIRE\n\t\t\t}\n\t\tcase strategy.Auto != nil:\n\t\t\tif strategy.RecentlyCalled != nil {\n\t\t\t\tif now-strategy.RecentlyCalled.Seconds > strategy.Auto.Duration.Seconds {\n\t\t\t\t\treturn lazyloadv1alpha1.Destinations_EXPIRE\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn lazyloadv1alpha1.Destinations_ACTIVE\n\t}\n\n\tfor h, strategy := range sf.Spec.Host {\n\t\tif strings.HasSuffix(h, \"/*\") {\n\t\t\t// handle namespace level host, like 'default/*'\n\t\t\thandleNsHost(h, domains, nsSvcCache, rules)\n\t\t} else {\n\t\t\t// handle service level host, like 'a.default.svc.cluster.local' or 'www.netease.com'\n\t\t\thandleSvcHost(h, strategy, checkStatus, domains, sf, rules)\n\t\t}\n\t}\n}", "func cdnsToHosts(cdns []*config.CDN) map[string]*Host {\n\thosts := map[string]*Host{}\n\tfor _, cdn := range cdns {\n\t\tvar options []HostOption\n\t\tif config, ok := cdn.GetCDNClusterConfig(); ok {\n\t\t\toptions = []HostOption{\n\t\t\t\tWithNetTopology(config.NetTopology),\n\t\t\t\tWithTotalUploadLoad(int32(config.LoadLimit)),\n\t\t\t}\n\t\t}\n\n\t\tid := idgen.CDN(cdn.HostName, cdn.Port)\n\t\thosts[id] = NewCDNHost(id, cdn.IP, cdn.HostName, cdn.Port, cdn.DownloadPort, cdn.SecurityGroup, cdn.Location, cdn.IDC, options...)\n\t}\n\n\treturn hosts\n}", "func extractSegmentID(addr uint64, nc NetConfig) uint64 {\n\tendpointBits := nc.EndpointBits()\n\tsegmentBits := nc.SegmentBits()\n\tsid := (addr >> endpointBits) & ((1 << segmentBits) - 1)\n\treturn sid\n}", "func GetClusterIdByHostIp(hostIp string) (string, error) {\n\tif EmptyString == hostIp {\n\t\tlog.Logger.Warnf(\"host ip is empty\")\n\t\treturn \"\", errors.New(\"invalid host ip\")\n\t}\n\ttempIp := hostIp\n\ttempIp = strings.ReplaceAll(tempIp, \"-\", \".\")\n\n\turl := fmt.Sprintf(\"%s/%s?hostIp=%s\", rmApiUrl, \"getClusterId\", tempIp)\n\tcontent, err := rest.HttpGet(url, DefaultTimeout)\n\tif err != nil {\n\t\tlog.Logger.Warnf(\"get clusterId by hostIp =%s, error=%s\", tempIp, err.Error())\n\t\treturn \"\", err\n\t}\n\n\tcluseterInfo := &model.RmClusterData{}\n\tif err = jsoniter.Unmarshal(content, cluseterInfo); err != nil {\n\t\tlog.Logger.Warnf(\"unmarshal err, hostIp=%s, err %s\", tempIp, err.Error())\n\t\treturn \"\", err\n\t}\n\tif cluseterInfo.Code != 0 {\n\t\terr = errors.Errorf(\"code = %d,get cluster info by hostIp=%s\",\n\t\t\tcluseterInfo.Code, tempIp)\n\t\tlog.Logger.Warnf(err.Error())\n\t\treturn \"\", err\n\t}\n\treturn cluseterInfo.Data.ClusterID, nil\n}", "func (cfg *Config) ServiceID() string {\n\treturn os.Getenv(\"SERVICE_ID\")\n}", "func DomainNameAndId(compositeDomainName string) (string, string) {\n\tif parts := strings.Split(compositeDomainName, \":\"); len(parts) == 2 {\n\t\treturn parts[0], parts[1]\n\t}\n\treturn compositeDomainName, \"\"\n}", "func (d *DNSProviderPublic) getHostedZoneID(ctx context.Context, fqdn string) (string, error) {\n\tif zone := env.GetOrFile(EnvZoneName); zone != \"\" {\n\t\treturn zone, nil\n\t}\n\n\tauthZone, err := dns01.FindZoneByFqdn(fqdn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tzone, err := d.zoneClient.Get(ctx, d.config.ResourceGroup, dns01.UnFqdn(authZone), nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// zone.Name shouldn't have a trailing dot(.)\n\treturn dns01.UnFqdn(deref(zone.Name)), nil\n}", "func GetCurrencyID(hostURL string, hostPort int) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\treturn makePostRequest(hostURL, hostPort, \"getcurrencyid\", params)\n}", "func (s *service) getEndpointIfID(serviceName string) string {\n\tif _, ok := s.endpointIfID[serviceName]; !ok {\n\t\ts.endpointIfID[serviceName] = 0\n\t} else {\n\t\ts.endpointIfID[serviceName]++\n\t}\n\n\treturn \"/\" + strconv.Itoa(s.endpointIfID[serviceName])\n}", "func (m *CalendarGroup) GetClassId()(*i561e97a8befe7661a44c8f54600992b4207a3a0cf6770e5559949bc276de2e22.UUID) {\n val, err := m.GetBackingStore().Get(\"classId\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i561e97a8befe7661a44c8f54600992b4207a3a0cf6770e5559949bc276de2e22.UUID)\n }\n return nil\n}", "func getCDNRouterFQDNs(tx *sql.Tx, requiredCDN *string) (map[tc.CDNName][]string, error) {\n\tquery := `\nSELECT s.host_name, s.domain_name, max(pa.value) as port, c.name as cdn\nFROM server as s\nJOIN type as t ON s.type = t.id\nJOIN status as st ON st.id = s.status\nJOIN cdn as c ON c.id = s.cdn_id\nJOIN profile as pr ON s.profile = pr.id\nJOIN profile_parameter as pp ON pp.profile = pr.id\nLEFT JOIN parameter as pa ON (pp.parameter = pa.id AND pa.name = 'api.port' AND pa.config_file = 'server.xml')\nWHERE t.name = '` + tc.RouterTypeName + `'\nAND st.name = '` + RouterOnlineStatus + `'\n`\n\tif requiredCDN != nil {\n\t\tquery += `AND c.name = $1`\n\t}\n\tquery += `\nGROUP BY s.host_name, s.domain_name, c.name\n`\n\tvar rows *sql.Rows\n\tvar err error\n\tif requiredCDN != nil {\n\t\trows, err = tx.Query(query, *requiredCDN)\n\t} else {\n\t\trows, err = tx.Query(query)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.New(\"querying routers: \" + err.Error())\n\t}\n\tdefer rows.Close()\n\trouters := map[tc.CDNName][]string{}\n\tfor rows.Next() {\n\t\thost := \"\"\n\t\tdomain := \"\"\n\t\tport := sql.NullInt64{}\n\t\tcdn := \"\"\n\t\tif err := rows.Scan(&host, &domain, &port, &cdn); err != nil {\n\t\t\treturn nil, errors.New(\"scanning routers: \" + err.Error())\n\t\t}\n\t\tfqdn := host + \".\" + domain\n\t\tif port.Valid {\n\t\t\tfqdn += \":\" + strconv.FormatInt(port.Int64, 10)\n\t\t}\n\t\tif requiredCDN != nil && *requiredCDN != cdn {\n\t\t\tcontinue\n\t\t}\n\t\trouters[tc.CDNName(cdn)] = append(routers[tc.CDNName(cdn)], fqdn)\n\t}\n\treturn routers, nil\n}", "func getUUIDRegex(version *int32) (string, error) {\n\tif version == nil {\n\t\treturn \"\", nil\n\t} else if *version < 0 || *version > 5 {\n\t\treturn \"\", fmt.Errorf(\"UUID version should be between 0-5, Got %d\", *version)\n\t} else if *version == 0 {\n\t\treturn fmt.Sprintf(uuidPattern, \"1-5\"), nil\n\t} else {\n\t\treturn fmt.Sprintf(uuidPattern, strconv.Itoa(int(*version))), nil\n\t}\n}", "func FindNodeIdFromServiceName(deployment *apis.Deployment, serviceName string) (int, error) {\n\t// if a service name contains a number (e.g: benchmark-agent-2), we assume\n\t// it's the second benchmark agent from the mapping. Since we should be sorting\n\t// the node ids when we deploy them, we should always assign the same service name\n\t// for the same app running on the same node.\n\tparts := strings.Split(serviceName, \"-\")\n\tcount := 1\n\trealServiceName := serviceName\n\tif len(parts) > 0 {\n\t\tif nth, err := strconv.Atoi(parts[len(parts)-1]); err == nil {\n\t\t\tcount = nth\n\t\t\trealServiceName = strings.Join(parts[:len(parts)-1], \"-\")\n\t\t}\n\t}\n\tsort.Sort(deployment.NodeMapping)\n\tcurrent := 0\n\tfor _, mapping := range deployment.NodeMapping {\n\t\tif mapping.Task == realServiceName {\n\t\t\tcurrent += 1\n\t\t\tif current == count {\n\t\t\t\treturn mapping.Id, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0, errors.New(\"Unable to find service in mappings\")\n}", "func Dns(host string) *net.IP {\n\tfor _, dnsServer := range appConfig.Dnsservers {\n\t\tIP := dnss(host, dnsServer+\":53\")\n\t\tif IP != nil {\n\t\t\treturn IP\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.5841075", "0.4965493", "0.48057923", "0.47056535", "0.46926", "0.46767744", "0.46705613", "0.46302775", "0.46255037", "0.45803738", "0.4568915", "0.4561361", "0.4536049", "0.4521004", "0.44993153", "0.44881353", "0.44595507", "0.4455809", "0.44513792", "0.44446835", "0.44199005", "0.44179907", "0.4412158", "0.44095916", "0.44042438", "0.43913165", "0.4384667", "0.43699658", "0.4364287", "0.4354093", "0.4336384", "0.43361577", "0.43322173", "0.4330213", "0.43212065", "0.43211764", "0.43119362", "0.43033028", "0.42994988", "0.42793337", "0.4272518", "0.42543817", "0.4252593", "0.4252593", "0.42367762", "0.42314744", "0.4227629", "0.42263734", "0.4223956", "0.42222014", "0.42114976", "0.42057487", "0.4199668", "0.41964257", "0.4191537", "0.41887105", "0.41840798", "0.41821104", "0.41758075", "0.41641667", "0.4159724", "0.41583794", "0.41540816", "0.4148279", "0.41446558", "0.4139198", "0.41388482", "0.41360933", "0.4130946", "0.4130047", "0.4125802", "0.41158915", "0.41118494", "0.41024512", "0.40987164", "0.40955997", "0.4088519", "0.40879387", "0.40841883", "0.40799394", "0.40777656", "0.40776762", "0.40595442", "0.40546268", "0.40480426", "0.4043817", "0.40436026", "0.40381926", "0.40323395", "0.4032098", "0.4031173", "0.4028949", "0.40268382", "0.40265182", "0.40198725", "0.4018428", "0.40142548", "0.40135303", "0.4011495", "0.40035775" ]
0.69668454
0
matchPattern matches regex against entity's path to find project name.
func matchPattern(fp string, patterns []MapPattern) (string, bool, error) { fp, err := realpath.Realpath(fp) if err != nil { return "", false, Err(fmt.Errorf("failed to get the real path: %w", err).Error()) } for _, pattern := range patterns { if pattern.Regex.MatchString(fp) { matches := pattern.Regex.FindStringSubmatch(fp) if len(matches) > 0 { params := make([]interface{}, len(matches[1:])) for i, v := range matches[1:] { params[i] = v } result, err := pyfmt.Fmt(pattern.Name, params...) if err != nil { log.Errorf("error formatting %q: %s", pattern.Name, err) continue } return result, true, nil } } } return "", false, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func ProjectRegexp() *regexp.Regexp {\n\treturn regexp.MustCompile(\"^projects/\" + NameRegex + \"$\")\n}", "func getDesiredPattern(pattern string) string {\n\twant := []string{}\n\tfor _, token := range strings.Split(pattern, \"/\") {\n\t\tif strings.HasPrefix(token, \"{\") && strings.HasSuffix(token, \"}\") {\n\t\t\tvarname := token[1 : len(token)-1]\n\t\t\twant = append(want, fmt.Sprintf(\"{%s}\", strings.TrimSuffix(strcase.SnakeCase(varname), \"_id\")))\n\t\t} else {\n\t\t\twant = append(want, strcase.LowerCamelCase(token))\n\t\t}\n\t}\n\treturn strings.Join(want, \"/\")\n}", "func nameMatch(path, pattern string) (bool, error) {\n\tbase := filepath.Base(path)\n\n\treturn filepath.Match(pattern, base)\n}", "func (r Repo) ImportPathPattern() string {\n\treturn r.Root + \"/...\"\n}", "func (p *pathPattern) Match(name string) bool {\n\tif strings.HasPrefix(name, p.prefix) || strings.HasSuffix(name, p.suffix) || strings.Contains(name, p.inner) {\n\t\treturn true\n\t}\n\tmatched, _ := filepath.Match(p.rawPattern, name)\n\treturn matched\n}", "func parsePattern(path string, stash Stash) string {\n\t// Standard placeholders\n\t// XXX: Add relaxed and wildcard placeholders\n\t// XXX: Add restricted placeholders\n\tpathPattern := \"\"\n\tlastIndex := 0\n\tfor _, v := range stdPlaceholder.FindAllStringSubmatchIndex(path, -1) {\n\t\t// v is an array of pairs of ints. Each pair is start and end\n\t\t// indexes of the match in the string. The first pair is the\n\t\t// entire match, and other pairs are the corresponding\n\t\t// submatches\n\t\tgap := path[lastIndex:v[0]]\n\t\tlastIndex = v[1]\n\n\t\tstart := path[v[2]:v[3]]\n\t\tif start != \"/\" {\n\t\t\tstart = \"\"\n\t\t}\n\n\t\t//placeType := path[v[4]:v[5]]\n\t\tplaceName := path[v[6]:v[7]]\n\t\t//end := path[v[8]:v[9]] // unused\n\n\t\tmatchType := \"+\" // required\n\t\tif _, ok := stash[placeName]; ok {\n\t\t\tmatchType = \"*\" // optional\n\t\t\tif start == \"/\" {\n\t\t\t\tstart += \"?\"\n\t\t\t}\n\t\t}\n\n\t\tpathPattern += gap + fmt.Sprintf(\"%s(?P<%s>[^/.]%s)\", start, placeName, matchType)\n\t}\n\n\t// If we never matched, there were no placeholders\n\tif pathPattern == \"\" {\n\t\treturn path\n\t}\n\n\treturn pathPattern\n}", "func fileMatchPattern(filePath string, matchPattern string,\n\tnumExpectedMatches int) error {\n\tcontent, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open file %s\", filePath)\n\t}\n\t// need to normalize since Windows has different EOL character\n\tnormalizedContent := strings.Replace(string(content), \"\\r\\n\", \"\\n\", -1)\n\n\tmatcher := regexp.MustCompile(matchPattern)\n\tmatches := matcher.FindAllString(normalizedContent, -1)\n\tif len(matches) != numExpectedMatches {\n\t\treturn fmt.Errorf(\"failed pattern match: %s matched %d times instead of %d\",\n\t\t\tmatchPattern, len(matches), numExpectedMatches)\n\t}\n\n\treturn nil\n}", "func matchPattern(pattern string) func(name string) bool {\n\tre := regexp.QuoteMeta(pattern)\n\tre = strings.Replace(re, `\\.\\.\\.`, `.*`, -1)\n\t// Special case: foo/... matches foo too.\n\tif strings.HasSuffix(re, `/.*`) {\n\t\tre = re[:len(re)-len(`/.*`)] + `(/.*)?`\n\t}\n\treg := regexp.MustCompile(`^` + re + `$`)\n\treturn func(name string) bool {\n\t\treturn reg.MatchString(name)\n\t}\n}", "func matchPattern(pattern string) func(name string) bool {\n\tre := regexp.QuoteMeta(pattern)\n\tre = strings.Replace(re, `\\.\\.\\.`, `.*`, -1)\n\t// Special case: foo/... matches foo too.\n\tif strings.HasSuffix(re, `/.*`) {\n\t\tre = re[:len(re)-len(`/.*`)] + `(/.*)?`\n\t}\n\treg := regexp.MustCompile(`^` + re + `$`)\n\treturn func(name string) bool {\n\t\treturn reg.MatchString(name)\n\t}\n}", "func pathPattern(pattern *regexp.Regexp) *regexp.Regexp {\n\treturn suffixPattern(regexp.MustCompile(\"(^|/)\" + pattern.String()))\n}", "func matchPattern(pattern string) func(name string) bool {\n\tre := regexp.QuoteMeta(pattern)\n\tre = strings.Replace(re, `\\.\\.\\.`, `.*`, -1)\n\n\t// Special case: string ending in /\n\tif strings.HasSuffix(pattern, \"/\") {\n\t\tre = strings.TrimSuffix(re, `/`)\n\t}\n\n\t// Special case: foo/... matches foo too.\n\tif strings.HasSuffix(re, `/.*`) {\n\t\tre = re[:len(re)-len(`/.*`)] + `(/.*)?`\n\t}\n\n\treg := regexp.MustCompile(`^` + re + `$`)\n\treturn func(name string) bool {\n\t\treturn reg.MatchString(name)\n\t}\n}", "func (m *modulePat) match(file string) bool {\n\tif m.literal {\n\t\treturn file == m.pattern\n\t}\n\tmatch, _ := filepath.Match(m.pattern, file)\n\treturn match\n}", "func (c Provider) Match(query string) string {\n\tsm := SearchRegex.FindStringSubmatch(query)\n\tif len(sm) == 0 {\n\t\treturn \"\"\n\t}\n\tsms := strings.Split(sm[1], \"/\")\n\tfilename := sms[len(sms)-1]\n\tpieces := strings.Split(filename, \"-\")\n\tif len(pieces) > 2 {\n\t\treturn strings.Join(pieces[0:len(pieces)-1], \"-\")\n\t}\n\treturn pieces[0]\n}", "func (obj *match) Pattern() string {\n\treturn obj.pattern\n}", "func Match(projectName string) bool {\n\treturn reGithubProject.MatchString(projectName)\n}", "func match(requestStr string, patterns []string) (ok bool, prefixStr, suffixStr string) {\n\tvar str, last string\n\tvar err error\n\tln := len(patterns)\n\tfor j := 0; j < ln && !ok; j++ {\n\t\tpattern := patterns[j]\n\t\tstr = requestStr\n\t\tlast = \"\"\n\t\tfor last != str && !ok && err == nil {\n\t\t\tok, err = path.Match(pattern, str)\n\t\t\tif err == nil {\n\t\t\t\tif ok {\n\t\t\t\t\tprefixStr = str\n\t\t\t\t\tsuffixStr = requestStr[len(str):]\n\t\t\t\t} else {\n\t\t\t\t\tlast = str\n\t\t\t\t\tstr = filepath.Dir(str)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (p *pathPrefixPattern) Match(name string) bool {\n\tif name == p.relative || strings.HasPrefix(name, p.prefix) {\n\t\treturn true\n\t}\n\tmatched, _ := filepath.Match(p.rawPattern, name)\n\treturn matched\n}", "func generatePatternForRegexp(pattern string) (string, error) {\n\tpattern = patternRegexp.ReplaceAllStringFunc(pattern, func(subMatch string) string {\n\t\t// The sub match string conforms the parameter pattern: `{parameter-name:regexp-expression}`.\n\t\tfoos := strings.SplitN(subMatch, \":\", 2)\n\t\tif len(foos) < 2 {\n\t\t\treturn `([^/]+)`\n\t\t} else {\n\t\t\treturn \"(\" + foos[1][0:len(foos[1])-1] + \")\"\n\t\t}\n\t})\n\t// Checking for abnormal patterns.\n\t_, err := regexp.Compile(pattern)\n\treturn pattern, err\n}", "func matches(re *regexp.Regexp, filename, template string) (match bool, origin string) {\n\tbase := filepath.Base(filename)\n\n\tmatches := re.FindStringSubmatchIndex(base)\n\tif matches == nil {\n\t\treturn false, \"\"\n\t}\n\n\tby := re.ExpandString(nil, template, base, matches)\n\tif by == nil {\n\t\treturn false, \"\"\n\t}\n\n\torigin = dns.Fqdn(string(by))\n\n\treturn true, origin\n}", "func fileMatchRegexp(logRoot, fileMatch string) *regexp.Regexp {\n\tif !os.IsPathSeparator(logRoot[len(logRoot)-1]) && !os.IsPathSeparator(fileMatch[0]) {\n\t\tlogRoot += string(os.PathSeparator)\n\t}\n\treturn regexp.MustCompile(\"^\" + regexp.QuoteMeta(logRoot) + fileMatch)\n}", "func (fpp *FoPoPattern) Match(serviceName string) bool {\n\tvar pattern string\n\tvar matched bool\n\tfor _, pattern = range fpp.ServicePatterns {\n\t\tmatched, _ = filepath.Match(pattern, serviceName)\n\t\tif matched {\n\t\t\treturn matched\n\t\t}\n\t}\n\treturn false\n}", "func (r *Project) matcher(c *Client) func([]byte) bool {\n\treturn func(b []byte) bool {\n\t\tcr, err := unmarshalProject(b, c)\n\t\tif err != nil {\n\t\t\tc.Config.Logger.Warning(\"failed to unmarshal provided resource in matcher.\")\n\t\t\treturn false\n\t\t}\n\t\tnr := r.urlNormalized()\n\t\tncr := cr.urlNormalized()\n\t\tc.Config.Logger.Infof(\"looking for %v\\nin %v\", nr, ncr)\n\n\t\tif nr.Name == nil && ncr.Name == nil {\n\t\t\tc.Config.Logger.Info(\"Both Name fields null - considering equal.\")\n\t\t} else if nr.Name == nil || ncr.Name == nil {\n\t\t\tc.Config.Logger.Info(\"Only one Name field is null - considering unequal.\")\n\t\t\treturn false\n\t\t} else if *nr.Name != *ncr.Name {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n}", "func GlobMatch(patterns ...string) MatcherFunc { return GlobMatches(patterns) }", "func (mg *MultiGlob) FindPattern(input string) (string, bool) {\n\tresults, ok := match(mg.node, input, false)\n\tif !ok || len(results) < 1 {\n\t\treturn \"\", false\n\t}\n\treturn results[0], true\n}", "func TestPatternMatches(t *testing.T) {\n\tmatch, _ := Matches(\"fileutils.go\", []string{\"*.go\"})\n\tif match != true {\n\t\tt.Errorf(\"failed to get a match, got %v\", match)\n\t}\n}", "func ProjectsRegexp() *regexp.Regexp {\n\treturn regexp.MustCompile(\"^projects$\")\n}", "func regexMatch(path, pattern string) (bool, error) {\n\treturn regexp.MatchString(pattern, path)\n}", "func regexmatch(regex string) *v2.RouteMatch {\n\treturn &v2.RouteMatch{\n\t\tPathSpecifier: &v2.RouteMatch_Regex{\n\t\t\tRegex: regex,\n\t\t},\n\t}\n}", "func (util copyHandlerUtil) matchBlobNameAgainstPattern(pattern string, blobName string, recursive bool) bool {\n\tif recursive {\n\t\treturn util.blobNameMatchesThePattern(pattern, blobName)\n\t}\n\treturn util.blobNameMatchesThePatternComponentWise(pattern, blobName)\n}", "func pathMatch(pattern, path string) bool {\n\tn := len(pattern)\n\tif n > 1 && pattern[n-1] == '/' {\n\t\treturn len(path) >= n && path[0:n] == pattern\n\t} else {\n\t\treturn pattern == path\n\t}\n}", "func matchPattern(pattern, name string) (matched bool) {\n\tif pattern == \"\" {\n\t\treturn name == pattern\n\t}\n\tif pattern == \"*\" {\n\t\treturn true\n\t}\n\trName, rPattern := make([]rune, 0, len(name)), make([]rune, 0, len(pattern))\n\tfor _, r := range name {\n\t\trName = append(rName, r)\n\t}\n\tfor _, r := range pattern {\n\t\trPattern = append(rPattern, r)\n\t}\n\treturn deepMatchRune(rName, rPattern, false)\n}", "func pathMatch(pattern, path string) bool {\n\tif len(pattern) == 0 {\n\t\t// should not happen\n\t\treturn false\n\t}\n\tn := len(pattern)\n\tif pattern[n-1] != '/' {\n\t\tmatch, _ := regexp.MatchString(pattern, path)\n\t\treturn match\n\t}\n\tfullMatch, _ := regexp.MatchString(pattern, string(path[0:n]))\n\treturn len(path) >= n && fullMatch\n}", "func (pattern targetPattern) Match(object *metav1.ObjectMeta) bool {\n\treturn object.Name == pattern.name && pattern.namespace.MatchString(object.Namespace)\n}", "func (c Provider) Match(query string) string {\n\tsm := SourceRegex.FindStringSubmatch(query)\n\tif len(sm) != 2 {\n\t\treturn \"\"\n\t}\n\treturn sm[1]\n}", "func treeCanMatchPattern(pattern string) func(name string) bool {\n\twildCard := false\n\tif i := strings.Index(pattern, \"...\"); i >= 0 {\n\t\twildCard = true\n\t\tpattern = pattern[:i]\n\t}\n\treturn func(name string) bool {\n\t\treturn len(name) <= len(pattern) && hasPathPrefix(pattern, name) ||\n\t\t\twildCard && strings.HasPrefix(name, pattern)\n\t}\n}", "func treeCanMatchPattern(pattern string) func(name string) bool {\n\twildCard := false\n\tif i := strings.Index(pattern, \"...\"); i >= 0 {\n\t\twildCard = true\n\t\tpattern = pattern[:i]\n\t}\n\treturn func(name string) bool {\n\t\treturn len(name) <= len(pattern) && hasPathPrefix(pattern, name) ||\n\t\t\twildCard && strings.HasPrefix(name, pattern)\n\t}\n}", "func (p *Path) Match(path string) *Match {\n\tvar match = &Match{\n\t\tValues: make(map[string]string),\n\t}\n\n\tfor _, part := range p.parts {\n\t\tif len(path) < 1 {\n\t\t\treturn nil\n\t\t}\n\n\t\tif path[0] != '/' {\n\t\t\treturn nil\n\t\t}\n\t\t// prefix /\n\t\tpath = path[1:]\n\n\t\tmatched, key, value, length := part.match(path)\n\n\t\t//log.Printf(\"%#v == %v (%d) %s\", part, matched, length, value)\n\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\n\t\tif key != \"\" {\n\t\t\tmatch.Values[key] = value\n\t\t}\n\t\tpath = path[length:]\n\t}\n\n\tif len(path) > 0 && path != \"/\" {\n\t\treturn nil\n\t}\n\n\treturn match\n}", "func NewMatcher(pattern string) (Matcher, error) {\n\n\tif len(pattern) == 0 || pattern[0] != '/' {\n\t\treturn nil, errors.New(\"Pattern must start with '/'\")\n\t}\n\n\tparts := strings.Split(pattern, \"/\")\n\n\tpat := \"\"\n\n\tfor i, part := range parts {\n\t\tif i > 0 {\n\t\t\tpat += \"/\"\n\t\t}\n\t\tif len(part) > 0 {\n\t\t\tif part[0] == ':' {\n\t\t\t\tptn := fmt.Sprintf(\"(?P<%s>[^/]*)\", regexp.QuoteMeta(part[1:]))\n\t\t\t\tpat += ptn\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpat += regexp.QuoteMeta(part)\n\t\t}\n\n\t}\n\n\texp, err := regexp.Compile(\"^\" + pat + \"$\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn func(path string) map[string]string {\n\t\tm := exp.FindStringSubmatch(path)\n\t\tn1 := exp.SubexpNames()\n\n\t\tif m == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tresult := map[string]string{}\n\n\t\tfor i, v := range m {\n\t\t\tif i > 0 {\n\t\t\t\tresult[n1[i]] = v\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}, nil\n\n}", "func regExp(context interface{}, value string) (bson.RegEx, error) {\n\tidx := strings.IndexByte(value[1:], '/')\n\tif value[0] != '/' || idx == -1 {\n\t\terr := fmt.Errorf(\"Parameter %q is not a regular expression\", value)\n\t\tlog.Error(context, \"varLookup\", err, \"Regex parsing\")\n\t\treturn bson.RegEx{}, err\n\t}\n\n\tpattern := value[1 : idx+1]\n\tl := len(pattern) + 2\n\n\tvar options string\n\tif l < len(value) {\n\t\toptions = value[l:]\n\t}\n\n\treturn bson.RegEx{Pattern: pattern, Options: options}, nil\n}", "func (p *pathlessWildcardPattern) Match(name string) bool {\n\tmatched, _ := filepath.Match(p.rawPattern, name)\n\t// Match the whole of the base name but allow matching in folders if no path\n\treturn matched || p.wildcardRE.MatchString(filepath.Base(name))\n}", "func (hs *HostStats) FindPathMatch(findPath string) string {\n\n\t// TODO: need to make sure we take into account dynamicAddPathDepth\n\t// e.g., do not return \"/v2\" if calling with \"/v2/app\" even if /v2\n\t// is registered and /v2/apps is not -- we should return:\n\t//\t\t empty match? or \"/v2/apps\" even though its not in list?\n\n\tfor _, path := range hs.routeIndex {\n\t\tif strings.HasPrefix(findPath, path) {\n\t\t\tpathLen := len(path)\n\t\t\tif len(findPath) == pathLen {\n\t\t\t\treturn path\n\t\t\t}\n\t\t\tif findPath[pathLen] == '/' {\n\t\t\t\treturn path\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}", "func Match(project string) bool {\n\t_, ok := data[project]\n\treturn ok\n}", "func (mux *ServeMux) match(path string) (h Handler, pattern string) {\n\t// Check for exact match first.\n\tv, ok := mux.m[path]\n\tif ok {\n\t\treturn v.h, v.pattern\n\t}\n\n\t// Check for longest valid match. mux.es contains all patterns\n\t// that end in / sorted from longest to shortest.\n\tfor _, e := range mux.es {\n\t\tif strings.HasPrefix(path, e.pattern) {\n\t\t\treturn e.h, e.pattern\n\t\t}\n\t}\n\treturn nil, \"\"\n}", "func getPattern(pattern string) []byte {\n\tpatternFileName := pattern + \".json\"\n\tif _, ok := patternMap[patternFileName]; ok {\n\t\treturn patternMap[patternFileName]\n\t}\n\treturn nil\n}", "func lookupProjPath(protoAbs string) (result string) {\n\tlastIndex := len(protoAbs)\n\tcurPath := protoAbs\n\n\tfor lastIndex > 0 {\n\t\tif fileExist(curPath+\"/cmd\") && fileExist(curPath+\"/api\") {\n\t\t\tresult = curPath\n\t\t\treturn\n\t\t}\n\t\tlastIndex = strings.LastIndex(curPath, string(os.PathSeparator))\n\t\tcurPath = protoAbs[:lastIndex]\n\t}\n\tresult = \"\"\n\treturn\n}", "func GetFileForPatternMatch(ap *PagePattern, pm *PatternMatch) (*File, error) {\n\tif ap == nil {\n\t\treturn nil, errors.New(\"page pattern object cannot be nil\")\n\t}\n\n\tif pm == nil {\n\t\treturn nil, errors.New(\"pattern match cannot be nil\")\n\t}\n\n\tfile := File{}\n\tfile.EditOnGithub = ap.EditOnGithub\n\tfile.AddToMenu = ap.AddToMenu\n\tfile.MenuGroup = ap.MenuGroup\n\tfile.Template = ap.Template\n\tfile.SourceFile = pm.Path\n\n\tvar err error\n\n\tif file.Name, err = stringFromTemplate(ap.Name, pm); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse name template: \\n\\t%s\", err.Error())\n\t} else if file.Path, err = stringFromTemplate(ap.Path, pm); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse path template: \\n\\t%s\", err.Error())\n\t}\n\n\treturn &file, nil\n}", "func MatchPattern(logger logr.Logger, resource, pattern interface{}) error {\n\t// newAnchorMap - to check anchor key has values\n\tac := anchor.NewAnchorMap()\n\telemPath, err := validateResourceElement(logger, resource, pattern, pattern, \"/\", ac)\n\tif err != nil {\n\t\tif skip(err) {\n\t\t\tlogger.V(2).Info(\"resource skipped\", \"reason\", ac.AnchorError.Error())\n\t\t\treturn &PatternError{err, \"\", true}\n\t\t}\n\n\t\tif fail(err) {\n\t\t\tlogger.V(2).Info(\"failed to apply rule on resource\", \"msg\", ac.AnchorError.Error())\n\t\t\treturn &PatternError{err, elemPath, false}\n\t\t}\n\n\t\t// check if an anchor defined in the policy rule is missing in the resource\n\t\tif ac.KeysAreMissing() {\n\t\t\tlogger.V(3).Info(\"missing anchor in resource\")\n\t\t\treturn &PatternError{err, \"\", false}\n\t\t}\n\n\t\treturn &PatternError{err, elemPath, false}\n\t}\n\n\treturn nil\n}", "func makePathPattern(Route *Route) {\n\tregistedPath := Route.path\n\tif registedPath != MatchEverything {\n\t\tregexpRoute := registedPath\n\n\t\trouteWithoutParenthesis := regexp.MustCompile(RegexParenthesisAndContent).ReplaceAllString(registedPath, \"\")\n\n\t\tpattern := regexp.MustCompile(RegexRouteNamedParameter)\n\n\t\t//find only :keys without parenthesis if any\n\t\tkeys := pattern.FindAllString(routeWithoutParenthesis, -1)\n\n\t\tfor keyIndex, key := range keys {\n\t\t\tbackupKey := key // the full :name we will need it for the replace.\n\t\t\tkey = key[1:len(key)]\n\t\t\tkeys[keyIndex] = key // :name is name now.\n\n\t\t\ta1 := strings.Index(registedPath, key) + len(key)\n\n\t\t\tif len(registedPath) > a1 && string(registedPath[a1]) == ParameterPatternStart {\n\t\t\t\t//check if first character, of the ending of the key from the original full registedPath, is parenthesis\n\n\t\t\t\tkeyPattern1 := registedPath[a1:] //here we take all string after a1, which maybe be follow up with other paths, we will substring it in the next line\n\t\t\t\tlastParIndex := strings.Index(keyPattern1, ParameterPatternEnd) //find last parenthesis index of the keyPattern1\n\t\t\t\tkeyPattern1 = keyPattern1[0 : lastParIndex+1] // find contents and it's parenthesis, we will need it for replace\n\t\t\t\tkeyPatternReg := keyPattern1[1 : len(keyPattern1)-1] //find the contents between parenthesis\n\t\t\t\tif isSupportedType(keyPatternReg) {\n\t\t\t\t\t//if it is (string) or (int) inside contents\n\t\t\t\t\tkeyPatternReg = toPattern(keyPatternReg)\n\t\t\t\t}\n\t\t\t\t//replace the whole :key+(pattern) with just the converted pattern from int,string or the contents of the parenthesis which is a custom user's regex pattern\n\t\t\t\tregexpRoute = strings.Replace(regexpRoute, backupKey+keyPattern1, keyPatternReg, -1)\n\n\t\t\t} else {\n\t\t\t\tregexpRoute = strings.Replace(regexpRoute, backupKey, \"\\\\w+\", -1)\n\t\t\t}\n\n\t\t}\n\t\tregexpRoute = strings.Replace(regexpRoute, \"/\", \"\\\\/\", -1) + \"$\" ///escape / character for regex and finish it with $, if route/:name and req url is route/:name:/somethingelse then it will not be matched\n\t\troutePattern := regexp.MustCompile(regexpRoute)\n\t\tRoute.Pattern = routePattern\n\n\t\tRoute.ParamKeys = keys\n\t}\n}", "func (i Ignorer) Match(in string) bool {\n\tfor _, p := range i.patterns {\n\t\t// http://golang-jp.org/pkg/path/filepath/#Match\n\t\tif matched, _ := filepath.Match(p, in); matched {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func ProjectNameFromPlanfile(workspace string, filename string) (string, error) {\n\tr, err := regexp.Compile(fmt.Sprintf(`(.*?)-%s\\.tfplan`, workspace))\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"compiling project name regex, this is a bug\")\n\t}\n\tprojMatch := r.FindAllStringSubmatch(filename, 1)\n\tif projMatch == nil {\n\t\treturn \"\", nil\n\t}\n\trawProjName := projMatch[0][1]\n\treturn strings.Replace(rawProjName, planfileSlashReplace, \"/\", -1), nil\n}", "func (t UrnTargets) getMatcher(glob string) *regexp.Regexp {\n\tif r := t.globs[glob]; r != nil {\n\t\treturn r\n\t}\n\tsegmentGlob := strings.Split(glob, \"**\")\n\tfor i, v := range segmentGlob {\n\t\tpart := strings.Split(v, \"*\")\n\t\tfor i, v := range part {\n\t\t\tpart[i] = regexp.QuoteMeta(v)\n\t\t}\n\t\tsegmentGlob[i] = strings.Join(part, \"[^:]*\")\n\t}\n\n\t// Because we have quoted all input, this is safe to compile.\n\tr := regexp.MustCompile(\"^\" + strings.Join(segmentGlob, \".*\") + \"$\")\n\n\t// We cache and return the matcher\n\tt.globs[glob] = r\n\treturn r\n}", "func MatchPatterns(p Pattern, v string) error {\n\tswitch {\n\tcase p == \"\": // No pattern is specified.\n\t\treturn nil\n\n\tcase strings.HasPrefix(string(p), \"const:\"):\n\t\tw := string(p[len(\"const:\"):])\n\t\tif w != v {\n\t\t\treturn fmt.Errorf(\"const not matched: %q %q\", p, v)\n\t\t}\n\t\treturn nil\n\n\tcase strings.HasPrefix(string(p), \"pattern:\"):\n\t\tw := string(p[len(\"pattern:\"):])\n\t\tif matchSuffix(w, v) != nil {\n\t\t\treturn fmt.Errorf(\"pattern not matched: %q %q\", p, v)\n\t\t}\n\t\treturn nil\n\n\tcase strings.HasPrefix(string(p), \"split_pattern:\"):\n\t\tws := strings.Split(string(p[len(\"split_pattern:\"):]), \";\")\n\t\tfor _, w := range ws {\n\t\t\tif matchSuffix(w, v) == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"split_pattern not matched: %q %q\", p, v)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unkown pattern\")\n\t}\n}", "func (me *Mux) match(path string) (interface{}, string) {\n\tv, ok := me.table[path]\n\tif ok {\n\t\treturn v.handler, v.pattern\n\t}\n\n\t// Check for longest valid match. me.array contains all patterns\n\t// that end in / sorted from longest to shortest.\n\tfor _, e := range me.array {\n\t\tif strings.HasPrefix(path, e.pattern) {\n\t\t\treturn e.handler, e.pattern\n\t\t}\n\t}\n\n\treturn nil, \"\"\n}", "func (o BlobReferenceInputDataSourceOutput) PathPattern() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BlobReferenceInputDataSource) *string { return v.PathPattern }).(pulumi.StringPtrOutput)\n}", "func (pf *PathFilter) Match(contentPath string) bool {\n\treturn pf.re.MatchString(contentPath)\n}", "func (pattern targetPattern) MatchString(target string) bool {\n\tparts := strings.SplitN(target, \"/\", 2)\n\treturn len(parts) == 2 && parts[1] == pattern.name && pattern.namespace.MatchString(parts[0])\n}", "func match(path, pattern string, vars ...interface{}) bool {\n\tregex := mustCompileCached(pattern)\n\tmatches := regex.FindStringSubmatch(path)\n\tif len(matches) <= 0 {\n\t\treturn false\n\t}\n\tfor i, match := range matches[1:] {\n\t\tswitch p := vars[i].(type) {\n\t\tcase *string:\n\t\t\t*p = match\n\t\tcase *int:\n\t\t\tn, err := strconv.Atoi(match)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t*p = n\n\t\tdefault:\n\t\t\tpanic(\"vars must be *string or *int\")\n\t\t}\n\t}\n\treturn true\n}", "func (m *matcher) match(path string) (results, error) {\n\tif m.root == nil {\n\t\treturn nil, ErrNotFound\n\t}\n\treturn m.root.match(path, false, m.mp)\n}", "func pathToRouteMatch(p v1beta1.HTTPIngressPath) *v2.RouteMatch {\n\tif p.Path == \"\" {\n\t\t// If the Path is empty, the k8s spec says\n\t\t// \"If unspecified, the path defaults to a catch all sending\n\t\t// traffic to the backend.\"\n\t\t// We map this it a catch all prefix route.\n\t\treturn prefixmatch(\"/\") // match all\n\t}\n\t// TODO(dfc) handle the case where p.Path does not start with \"/\"\n\tif strings.IndexAny(p.Path, `[(*\\`) == -1 {\n\t\t// Envoy requires that regex matches match completely, wheres the\n\t\t// HTTPIngressPath.Path regex only requires a partial match. eg,\n\t\t// \"/foo\" matches \"/\" according to k8s rules, but does not match\n\t\t// according to Envoy.\n\t\t// To deal with this we handle the simple case, a Path without regex\n\t\t// characters as a Envoy prefix route.\n\t\treturn prefixmatch(p.Path)\n\t}\n\t// At this point the path is a regex, which we hope is the same between k8s\n\t// IEEE 1003.1 POSIX regex, and Envoys Javascript regex.\n\treturn regexmatch(p.Path)\n}", "func resolvePath(path string) (*regexp.Regexp, []RouteSegment, error) {\n\tvar segments []RouteSegment\n\tregexpSegment := regexp.MustCompile(\"({[^}]+})\")\n\n\t/*\n\t\tThis pattern: {([a-zA-z_][a-zA-Z_0-9]+)(\\??)(?(?=:):(.*)|())}\n\t\tGet all parts of params in the following way:\n\t\t[0] Full match\n\t\t[1] Name\n\t\t[2] Required(\"?\"=optional || \"\"=required)\n\t\t[3] Format([0-9], string, int,...)\n\n\t\tPHP support the conditions in Regex expressions But Golang still not support it. I made the comment because in the future would can support it.\n\t\tI uploaded an example of this pattern here: https://regex101.com/r/F9PlVb/1\n\t*/\n\tmatches := regexpSegment.FindAllString(path, -1)\n\n\tif len(matches) > 0 {\n\t\tfor _, match := range matches {\n\t\t\tvar name, _type string\n\t\t\tvar required bool\n\t\t\t_tmp := strings.TrimLeft(match, \"{\")\n\t\t\t_tmp = strings.TrimRight(_tmp, \"}\")\n\n\t\t\tutils.List(strings.Split(_tmp, \":\"), &_tmp, &_type)\n\n\t\t\t// when we make split if the length is == 1 it means that not contains \"?\", so is required.\n\t\t\tresult := strings.Split(_tmp, \"?\")\n\t\t\tname = result[0]\n\t\t\trequired = len(result) == 1\n\n\t\t\tsegment := NewRouteSegment(name, _type, required)\n\t\t\tsegments = append(segments, segment)\n\t\t\tpath = strings.Replace(path, match, segment.Expression, -1)\n\t\t\t//fmt.Println(\"Pattern segments: \" + match)\n\t\t}\n\t}\n\n\tpath = \"^/\" + strings.Trim(path, \"/\") + \"$\"\n\n\t// fmt.Println(\"Pattern: \" + path)\n\n\tpathCompiled, err := regexp.Compile(path)\n\n\tif err != nil {\n\t\treturn nil, segments, err\n\t}\n\n\treturn pathCompiled, segments, nil\n}", "func buildPatternPath(pattern []quad.Quad, ns *voc.Namespaces) *path.Path {\n\tentities, referenced := groupEntities(pattern, ns)\n\tp := path.StartMorphism()\n\n\tfor entity := range entities {\n\t\t// Apply only on entities which are not referenced as values\n\t\tif _, ok := referenced[entity]; !ok {\n\t\t\tp = p.Follow(entityPropertiesToPath(entity, entities))\n\t\t}\n\t}\n\n\treturn p\n}", "func parsePattern(pattern string) []string{\n\tvs := strings.Split(pattern, \"/\")\n\tparts := make([]string, 0)\n\tfor _, item := range vs{\n\t\tif item != \"\"{\n\t\t\tparts = append(parts, item)\n\t\t\tif item[0] == '*'{\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn parts\n}", "func (pat *patternGrouping) match(ctx *context) error {\n\tif !ctx.justReturned() {\n\t\treturn ctx.call(pat.pat)\n\t}\n\n\tret := ctx.ret\n\tif !ret.ok {\n\t\treturn ctx.predicates(false)\n\t}\n\tctx.consume(ret.n)\n\tctx.group(pat.grpname)\n\treturn ctx.commit()\n}", "func (o HostRuleOutput) PathMatcher() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HostRule) *string { return v.PathMatcher }).(pulumi.StringPtrOutput)\n}", "func parseProjectLine(projectLine, path string) (projectName, projFilePath string, err error) {\n\tparsedLine := strings.Split(projectLine, \"=\")\n\tif len(parsedLine) <= 1 {\n\t\treturn \"\", \"\", errors.New(\"Unexpected project line format: \" + projectLine)\n\t}\n\n\tprojectInfo := strings.Split(parsedLine[1], \",\")\n\tif len(projectInfo) < 2 {\n\t\treturn \"\", \"\", errors.New(\"Unexpected project information format: \" + parsedLine[1])\n\t}\n\tprojectName = removeQuotes(projectInfo[0])\n\t// In case we are running on a non-Windows OS, the solution root path and the relative path to proj file might used different path separators.\n\t// We want to make sure we will get a valid path after we join both parts, so we will replace the proj separators.\n\tif utils.IsWindows() {\n\t\tprojectInfo[1] = utils.UnixToWinPathSeparator(projectInfo[1])\n\t} else {\n\t\tprojectInfo[1] = utils.WinToUnixPathSeparator(projectInfo[1])\n\t}\n\tprojFilePath = filepath.Join(path, filepath.FromSlash(removeQuotes(projectInfo[1])))\n\treturn\n}", "func makePath(urlPattern string) (regex *regexp.Regexp, pathParams []string, err error) {\n\tpathParams = make([]string, 0)\n\t//patternPeices = make([]string)\n\tparts := strings.Split(urlPattern, \"/\")\n\tfor i, p := range parts {\n\t\tl := len(p)\n\t\tif l > 0 && p[0] == ':' {\n\t\t\tif l < 2 {\n\t\t\t\t//unnamed param\n\t\t\t\terr = NewRouterError(\"Cannot have unnamed path params in route: \", urlPattern)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpathParams = append(pathParams, p[1:l])\n\t\t\tparts[i] = \"([A-Za-z0-9]+)\" //just support simple strings not url encoded or anything for now\n\t\t}\n\t}\n\n\tregexString := \"^\" + strings.Join(parts, \"/\") + \"$\"\n\tregex, err = regexp.Compile(regexString)\n\n\treturn\n}", "func Detect(entity string, patterns []MapPattern) (project, branch string) {\n\tvar configPlugins []Detecter = []Detecter{\n\t\tFile{\n\t\t\tFilepath: entity,\n\t\t},\n\t\tMap{\n\t\t\tFilepath: entity,\n\t\t\tPatterns: patterns,\n\t\t},\n\t}\n\n\tfor _, p := range configPlugins {\n\t\tresult, detected, err := p.Detect()\n\t\tif err != nil {\n\t\t\tjww.ERROR.Printf(\"unexpected error occurred at %q: %s\", p.String(), err)\n\t\t\tcontinue\n\t\t} else if detected {\n\t\t\treturn result.Project, result.Branch\n\t\t}\n\t}\n\n\treturn \"\", \"\"\n}", "func getStartDir(pattern string) string {\n\tvar dir string\n\n\ti := strings.Index(pattern, \"...\")\n\tif i != -1 {\n\t\tdir, _ = path.Split(pattern[:i])\n\t} else {\n\t\tdir = pattern\n\t}\n\n\treturn dir\n}", "func parsePattern(pattern string) []string {\n\tvs := strings.Split(pattern, \"/\")\n\n\tparts := make([]string, 0)\n\tfor _, item := range vs {\n\t\tif item != \"\" {\n\t\t\tparts = append(parts, item)\n\t\t\tif item[0] == '*' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn parts\n}", "func matcher(text, pat string, leadingPercent bool) (res string, match bool) {\n\tif !leadingPercent {\n\t\tres = strings.TrimPrefix(text, pat)\n\t\tif len(text) == len(res) {\n\t\t\treturn \"\", false\n\t\t}\n\t} else {\n\t\tparts := strings.SplitN(text, pat, 2)\n\t\tif len(parts) == 1 {\n\t\t\treturn \"\", false\n\t\t}\n\t\tres = parts[1]\n\t}\n\treturn res, true\n}", "func pathMatch(pattern, path string) bool {\n\tif len(pattern) == 0 {\n\t\t// should not happen\n\t\treturn false\n\t}\n\tn := len(pattern)\n\tif pattern[n-1] != '/' {\n\t\treturn pattern == path\n\t}\n\treturn len(path) >= n && path[0:n] == pattern\n}", "func pathMatch(pattern, path string) bool {\n\tif len(pattern) == 0 {\n\t\t// should not happen\n\t\treturn false\n\t}\n\tn := len(pattern)\n\tif pattern[n-1] != '/' {\n\t\treturn pattern == path\n\t}\n\treturn len(path) >= n && path[0:n] == pattern\n}", "func pathMatch(path, pattern string) bool {\n\treturn wildcard.Match(pattern, path)\n}", "func pathMatch(matches []string, path string) bool {\n\tfor _, v := range matches {\n\t\tmatched, _ := regexp.MatchString(v, path)\n\t\tif matched {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (p *doubleWildcardPattern) Match(name string) bool {\n\tmatched, _ := filepath.Match(p.rawPattern, name)\n\t// Match the whole of the base name but allow matching in folders if no path\n\treturn matched || p.wildcardRE.MatchString(name)\n}", "func walkMatch(root, pattern string) ([]string, []string, error) {\r\n\tvar matches []string\r\n\tvar matchesRaw []string\r\n\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\tif info.IsDir() {\r\n\t\t\treturn nil\r\n\t\t}\r\n\t\tif matched, err := filepath.Match(pattern, filepath.Base(path)); err != nil {\r\n\t\t\treturn err\r\n\t\t} else if matched {\r\n\t\t\tmatches = append(matches, path)\r\n\t\t\tmatchesRaw = append(matchesRaw, filepath.Base(path))\r\n\t\t}\r\n\t\treturn nil\r\n\t})\r\n\tif err != nil {\r\n\t\treturn nil, nil, err\r\n\t}\r\n\treturn matches, matchesRaw, nil\r\n}", "func emailTemplateFilenameRegexp(c context.Context) (*regexp.Regexp, error) {\n\tappID, err := common.GetAppID(c)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to get app ID\").Err()\n\t}\n\n\treturn regexp.MustCompile(fmt.Sprintf(\n\t\t`^%s+/email-templates/([a-z][a-z0-9_]*)%s$`,\n\t\tregexp.QuoteMeta(appID),\n\t\tregexp.QuoteMeta(mailtmpl.FileExt),\n\t)), nil\n}", "func (o BlobReferenceInputDataSourceResponseOutput) PathPattern() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BlobReferenceInputDataSourceResponse) *string { return v.PathPattern }).(pulumi.StringPtrOutput)\n}", "func PatternMatch(matchrules []rule, text string) (r *pb.Matches, err error) {\n\tfor _, mrule := range matchrules {\n\n\t\tvar tempRuleArray []*pb.Pattern\n\n\t\tfor _, pat := range mrule.patterns {\n\t\t\tpatpb := &pb.Pattern{Key: pat.key, Value: pat.value}\n\t\t\ttempRuleArray = append(tempRuleArray, patpb)\n\t\t}\n\t\trulepb := &pb.Rule{Id: mrule.id, Patterns: tempRuleArray}\n\n\t\tarctx, arcancle := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer arcancle()\n\n\t\tarresp, arerror := grpcClient.AddRule(arctx, rulepb)\n\n\t\tif arerror != nil {\n\t\t\tlog.Printf(\"Add rule error: %v\", arerror.Error())\n\t\t} else {\n\t\t\tlog.Printf(\"%v\", arresp.GetMessage())\n\t\t}\n\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tr, err = grpcClient.GetMatches(ctx, &pb.TextRequest{Text: text})\n\n\trsctx, rscancel := context.WithTimeout(context.Background(), time.Second)\n\n\tresetresp, _ := grpcClient.ResetMatcher(rsctx, &pb.TextRequest{Text: \"\"})\n\tdefer rscancel()\n\n\tif resetresp != nil {\n\t\tlog.Printf(\"%v\", resetresp.GetMessage())\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n\n}", "func ApplyPattern(patterns []Pattern, depth int, value string) (result Match, newValue string) {\n\tif depth >= len(patterns) {\n\t\treturn NoPattern, value\n\t}\n\tpattern := patterns[depth]\n\tif pattern.Expression == nil {\n\t\tif pattern.Subtitution != \"\" {\n\t\t\tpanic(\"unexpected substitution with nil pattern expression\")\n\t\t}\n\t\treturn Matched, value\n\t}\n\tif pattern.Expression.MatchString(value) {\n\t\tif pattern.Subtitution == \"\" {\n\t\t\treturn Matched, value\n\t\t}\n\t\treturn Matched, pattern.Expression.ReplaceAllString(value, pattern.Subtitution)\n\t}\n\treturn NotMatched, value\n}", "func MatchPath(subPaths ...string) MatcherFunc { return MatchPaths(subPaths) }", "func (mux *XMux) match(path string) (h *UriHandler, pattern string) {\n\tvar n = 0\n\tfor k, v := range mux.m {\n\t\tif !pathMatch(k, path) {\n\t\t\tcontinue\n\t\t}\n\t\tif h == nil || len(k) > n {\n\t\t\tn = len(k)\n\t\t\th = v.h\n\t\t\tpattern = v.pattern\n\t\t}\n\t}\n\n\treturn\n}", "func newPattern(pattern string) *Pattern {\n\treturn &Pattern{*newPath(pattern)}\n\n}", "func (m *Match) printMatch() {\n\tfmt.Printf(\"%s%s%s%s:%s:%s%s%s%s%s%s\\n\",\n\t\tcolors.Purple,\n\t\tm.Path,\n\t\tcolors.Restore,\n\t\tcolors.Green,\n\t\tstrconv.Itoa(m.LineNumber),\n\t\tcolors.Restore,\n\t\tstring(m.Line[:m.Match[0]]),\n\t\tcolors.LightRed,\n\t\tstring(m.Line[m.Match[0]:m.Match[1]]),\n\t\tcolors.Restore,\n\t\tstring(m.Line[m.Match[1]:]),\n\t)\n}", "func (o BucketLifecycleRuleItemConditionResponseOutput) MatchesPattern() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketLifecycleRuleItemConditionResponse) string { return v.MatchesPattern }).(pulumi.StringOutput)\n}", "func (pat *patternInjector) match(ctx *context) error {\n\tif !ctx.justReturned() {\n\t\treturn ctx.call(pat.pat)\n\t}\n\n\tret := ctx.ret\n\tif ret.ok {\n\t\tif n, ok := pat.inject(ctx.next(ret.n)); ok {\n\t\t\tctx.consume(n)\n\t\t\treturn ctx.commit()\n\t\t}\n\t}\n\treturn ctx.predicates(false)\n}", "func (self *Glob) Match(haystack string) *Match {\n\treturn self.match(haystack, true)\n}", "func getProjectPrefix(entity ProjectEntity) string {\n\treturn entity.Context().ECSParams.ComposeProjectNamePrefix\n}", "func (o HostRuleResponseOutput) PathMatcher() pulumi.StringOutput {\n\treturn o.ApplyT(func(v HostRuleResponse) string { return v.PathMatcher }).(pulumi.StringOutput)\n}", "func parsePattern(pattern string) []string {\n\t// Split the pattern eg /p/test => \"\",\"p\",\"test\"\n\tvs := strings.Split(pattern, \"/\")\n\tparts := make([]string, 0)\n\tfor _, item := range vs {\n\t\t// Exclude the first item\n\t\tif item != \"\" {\n\t\t\tparts = append(parts, item)\n\t\t\t// Omit path after *\n\t\t\tif item[0] == '*' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn parts\n}", "func matchPatterns(patterns []string, rows ...[]string) (hits []string, err error) {\n\tif len(patterns) == 0 {\n\t\tpatterns = []string{`*`}\n\t}\n\tsort.Slice(rows, func(i, j int) bool {\n\t\treturn rows[i][0] < rows[j][0]\n\t})\n\tadded := make(map[string]struct{}, len(rows))\n\thits = make([]string, 0, len(rows))\n\tfor _, pattern := range patterns {\n\t\tused := false\n\t\tfor _, row := range rows {\n\t\t\tname := row[0]\n\t\t\tfor _, item := range row {\n\t\t\t\tif match, err := path.Match(pattern, item); err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(`%v while parsing pattern %q`, err, pattern)\n\t\t\t\t} else if !match {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tused = true\n\t\t\t\tif _, dup := added[name]; dup {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tadded[name] = struct{}{}\n\t\t\t\thits = append(hits, name)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !used {\n\t\t\treturn nil, fmt.Errorf(`%q did not match anything`, pattern)\n\t\t}\n\t}\n\treturn\n}", "func (p *Project) TargetNamesMatch(pattern string) (names []string, err error) {\n\tnames, err = p.Targets.CompleteName(pattern)\n\tif err == nil {\n\t\tsort.Strings(names)\n\t}\n\treturn\n}", "func pathPrefixMatch(mpath, targ string) (rel string, match bool) {\n\tif len(mpath) == len(targ) && mpath == targ {\n\t\treturn \".\", true\n\t}\n\tbl := len(mpath)\n\ttl := len(targ)\n\tvar b0, bi, t0, ti int\n\tfor {\n\t\tfor bi < bl && mpath[bi] != filepath.Separator {\n\t\t\tbi++\n\t\t}\n\t\tfor ti < tl && targ[ti] != filepath.Separator {\n\t\t\tti++\n\t\t}\n\t\tif targ[t0:ti] != mpath[b0:bi] {\n\t\t\tbreak\n\t\t}\n\t\tif bi < bl {\n\t\t\tbi++\n\t\t}\n\t\tif ti < tl {\n\t\t\tti++\n\t\t}\n\t\tb0 = bi\n\t\tt0 = ti\n\t}\n\tif b0 != bl {\n\t\treturn \"\", false\n\t}\n\treturn targ[t0:], true\n}", "func segmentPattern(pattern *regexp.Regexp) *regexp.Regexp {\n\treturn regexp.MustCompile(\"(^|/)\" + pattern.String() + \"($|/)\")\n}", "func (*HttpDomainRegexs) GetPath() string { return \"/api/objects/http/domain_regex/\" }", "func (o HttpRouteRuleMatchOutput) FullPathMatch() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v HttpRouteRuleMatch) *string { return v.FullPathMatch }).(pulumi.StringPtrOutput)\n}", "func (ps *Segment) Match(s string) (name string, capture bool, wildcard bool, matches bool) {\n\tif ps.IsWildcard {\n\t\twildcard = true\n\t\tmatches = true\n\t\treturn\n\t}\n\tif ps.IsVariable {\n\t\tname = ps.Name\n\t\tcapture = true\n\t\tmatches = true\n\t\treturn\n\t}\n\tif strings.EqualFold(s, ps.Name) {\n\t\tmatches = true\n\t\treturn\n\t}\n\treturn\n}", "func (p *fsPath) TryPattern() (*Pattern, bool) {\n\tpattern := &Pattern{*p}\n\t_, err := p.Match(pattern)\n\treturn &Pattern{*p}, (err == nil)\n}", "func (n *Namer) CreateNameWithPattern(tmpl Exeutable) string {\n\ts, err := n.ExecuteWithTemplate(n.Words, tmpl)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn s\n}", "func (o BlobOutputDataSourceOutput) PathPattern() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BlobOutputDataSource) *string { return v.PathPattern }).(pulumi.StringPtrOutput)\n}" ]
[ "0.5743209", "0.5709654", "0.5678647", "0.56146234", "0.55893093", "0.5514387", "0.53998846", "0.5398883", "0.5398883", "0.5346574", "0.5334595", "0.5325938", "0.524541", "0.5237653", "0.52365726", "0.5223555", "0.52056265", "0.5200951", "0.51546204", "0.5128055", "0.51171446", "0.5058351", "0.5023421", "0.5006046", "0.5003685", "0.49925342", "0.49598992", "0.49438703", "0.49438372", "0.4938953", "0.49335936", "0.49180695", "0.48948976", "0.48932654", "0.48928994", "0.48928994", "0.48809153", "0.4871465", "0.48593962", "0.48585692", "0.48282826", "0.4827284", "0.4821034", "0.48110452", "0.4798963", "0.47979727", "0.47950912", "0.47937524", "0.47893724", "0.477564", "0.47693428", "0.47627008", "0.47464475", "0.4737396", "0.4734534", "0.47300988", "0.47211415", "0.47191823", "0.471645", "0.47054", "0.47023252", "0.47019184", "0.4692348", "0.46908274", "0.46844104", "0.46809945", "0.46772933", "0.46697024", "0.46695492", "0.46688038", "0.46634164", "0.46634164", "0.46532533", "0.4637318", "0.46335825", "0.46226504", "0.46198475", "0.4615514", "0.46148318", "0.4608886", "0.4599688", "0.45976093", "0.4587866", "0.45612413", "0.4556968", "0.455551", "0.4555326", "0.45440015", "0.4539888", "0.45350018", "0.4533833", "0.4521793", "0.45189747", "0.45147622", "0.45123154", "0.450217", "0.44931084", "0.44923642", "0.44889683", "0.44809654" ]
0.5454481
6
String returns its name.
func (m Map) String() string { return "project-map-detector" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n name) String() string {\n\treturn fmt.Sprintf(n.Name)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (n Name) String() string {\n\treturn string(n)\n}", "func (n Named) String() string {\n\tif n.Path == \"\" {\n\t\treturn n.Name\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", n.Path, n.Name)\n}", "func (g Name) String() string {\n\treturn string(g)\n}", "func (n Name) String() string {\n\treturn smbtype.String([]byte(n))\n}", "func (n *Name) String() string {\n\tif n == nil {\n\t\treturn \"\"\n\t}\n\treturn n.Value\n}", "func (n *Nameserver) String() string {\n\treturn n.Name\n}", "func (t *Struct) String() string { return t.Name }", "func (b Basic) String() string {\n\treturn b.Name\n}", "func (String) Name() compiler.String {\n\treturn compiler.String{\n\t\tcompiler.English: `string`,\n\t}\n}", "func (n NamespacedName) String() string {\n\treturn fmt.Sprintf(\"%s%c%s\", n.Namespace, Separator, n.Name)\n}", "func (b *Basic) String() string {\n\tb.mux.RLock()\n\tdefer b.mux.RUnlock()\n\n\tif b.name != \"\" {\n\t\treturn b.name\n\t}\n\treturn fmt.Sprintf(\"%T\", b.target)\n}", "func (c causer) String() string {\n\treturn c.Name\n}", "func (n *Name) String() string {\n\tif n.Middle == \"\" {\n\t\treturn fmt.Sprintf(\"%s %s\", n.First, n.Last)\n\t}\n\treturn fmt.Sprintf(\"%s %s %s\", n.First, n.Middle, n.Last)\n}", "func (r *Idea) String() string {\n\treturn r.Name\n}", "func (p ByName) Name() string { return p.name }", "func (name PeerName) String() string {\n\treturn string(name)\n}", "func (m *Module) String() string {\n\treturn m.name\n}", "func (i ID) String() string {\n\treturn names[i]\n}", "func Name() string {\n\treturn strings.Replace(nameMaker.Generate(), \"-\", \"\", 1)\n}", "func (e BaseType) String() string {\n\treturn namesBaseType[e]\n}", "func (p Packet) Name() (name string) {\n\t// todo: think of ways to make this not a compiled in hack\n\t// todo: collectd 4 uses different patterns for some plugins\n\t// https://collectd.org/wiki/index.php/V4_to_v5_migration_guide\n\tswitch p.Plugin {\n\tcase \"df\":\n\t\tname = fmt.Sprintf(\"df_%s_%s\", p.PluginInstance, p.TypeInstance)\n\tcase \"interface\":\n\t\tname = fmt.Sprintf(\"%s_%s\", p.Type, p.PluginInstance)\n\tcase \"load\":\n\t\tname = \"load\"\n\tcase \"memory\":\n\t\tname = fmt.Sprintf(\"memory_%s\", p.TypeInstance)\n\tdefault:\n\t\tname = fmt.Sprintf(\"%s_%s_%s_%s\", p.Plugin, p.PluginInstance, p.Type, p.TypeInstance)\n\t}\n\treturn name\n}", "func (f *NamedFunction) NameString() string {\n\treturn f.Name.String()\n}", "func (mc *MeetingCanhui) String() string {\n\treturn mc.Name\n}", "func (n *Node) String() string {\n\treturn n.Name\n}", "func (e *EDNS) Name() string { return name }", "func (frame *Frame) NameString() string {\n\treturn strings.TrimRight(string(frame.Header.Name[:]), \"\\x00\")\n}", "func (n *piName) Name() string {\n\treturn n.name\n}", "func (e Enclosure) String() string {\n\treturn e.Name\n}", "func (this *Name) String() string {\n\tif this.DoubleValue != nil {\n\t\treturn this.Before.String() + strconv.FormatFloat(this.GetDoubleValue(), 'f', -1, 64)\n\t}\n\tif this.IntValue != nil {\n\t\treturn this.Before.String() + strconv.FormatInt(this.GetIntValue(), 10)\n\t}\n\tif this.UintValue != nil {\n\t\treturn this.Before.String() + \"uint(\" + strconv.FormatUint(this.GetUintValue(), 10) + \")\"\n\t}\n\tif this.BoolValue != nil {\n\t\treturn this.Before.String() + strconv.FormatBool(this.GetBoolValue())\n\t}\n\tif this.StringValue != nil {\n\t\tif isId(this.GetStringValue()) {\n\t\t\treturn this.Before.String() + this.GetStringValue()\n\t\t}\n\t\treturn this.Before.String() + strconv.Quote(this.GetStringValue())\n\t}\n\tif this.BytesValue != nil {\n\t\treturn this.Before.String() + fmt.Sprintf(\"%#v\", this.GetBytesValue())\n\t}\n\tpanic(\"unreachable\")\n}", "func (i *identifier) string() string {\n\tif i.parent != \"\" {\n\t\treturn fmt.Sprintf(\"\\\"%s\\\".%s.%s\", i.pkg, i.parent, i.name)\n\t}\n\treturn fmt.Sprintf(\"\\\"%s\\\".%s\", i.pkg, i.name)\n}", "func (bas *BaseService) String() string {\n\treturn bas.name\n}", "func (s stressng) String() string {\n\treturn s.name\n}", "func String(name string) *string {\n\treturn &name\n}", "func (cmd *CLI) Name() string {\n\tvar name string\n\tif cmd.parent != nil {\n\t\tname = strings.Join([]string{cmd.parent.Name(), cmd.name}, \" \")\n\t} else {\n\t\tname = cmd.name\n\t}\n\treturn name\n}", "func (i *in) String() string {\n\treturn i.name\n}", "func (i *in) String() string {\n\treturn i.name\n}", "func (suite Suite) String() string {\n\tnames := []string{\"Spade\", \"Clubs\", \"Hearts\", \"Diamond\"}\n\treturn names[suite]\n}", "func (e Server) String() string {\n\treturn e.Name\n}", "func (l *DirName) String() string {\n\tl.Lock()\n\tdefer l.Unlock()\n\treturn l.name\n}", "func (d Distribution) Name() string {\n\treturn strings.Replace(d.ID, \"-\", \"::\", -1)\n}", "func (t *Type) String() string {\n\treturn TypeNames[*t]\n}", "func (b *Being) String() string {\n\treturn strings.Trim(b.Name.GetDisplay(), \" \")\n}", "func (i *Variable) String() string {\n\treturn i.Name\n}", "func (s *SharingKey) Name() string {\n\treturn string(s.name)\n}", "func (key KeyCode) String() string {\n\treturn key.Name()\n}", "func String(name string) string {\n\treturn rootFileGroup.String(name)\n}", "func (eventName EventName) String() string {\n\tswitch eventName {\n\tcase ObjectCreatedPut:\n\t\treturn \"s3:ObjectCreated:Put\"\n\tcase ObjectCreatedPost:\n\t\treturn \"s3:ObjectCreated:Post\"\n\tcase ObjectCreatedCopy:\n\t\treturn \"s3:ObjectCreated:Copy\"\n\tcase ObjectCreatedCompleteMultipartUpload:\n\t\treturn \"s3:ObjectCreated:CompleteMultipartUpload\"\n\tcase ObjectRemovedDelete:\n\t\treturn \"s3:ObjectRemoved:Delete\"\n\tcase ObjectAccessedGet:\n\t\treturn \"s3:ObjectAccessed:Get\"\n\tcase ObjectAccessedHead:\n\t\treturn \"s3:ObjectAccessed:Head\"\n\tdefault:\n\t\treturn \"s3:Unknown\"\n\t}\n}", "func (sh SubdirectoryHeader) Name() string {\n\treturn string(sh.SubdirectoryName[0 : sh.TypeAndNameLength&0xf])\n}", "func (i *ID) Name() string {\n\t_, name, _ := internal.ParseID((*string)(i))\n\treturn *name\n}", "func (c client) Name() string {\n\t_, l4Type := c.name.GetLookupAndType()\n\treq := NameRequest{Type: l4Type}\n\tresp := NameResponse{}\n\n\tc.client.Call(\"L4.Name\", req, &resp)\n\treturn resp.Name\n}", "func (t *Link) GetNameString(index int) (v string) {\n\treturn *t.name[index].stringName\n\n}", "func (Tellurium) GetName() string {\n\treturn \"Tellurium\"\n}", "func (b *Base) getName() string {\n\treturn b.name\n}", "func (this *AnyName) String() string {\n\treturn this.Underscore.String()\n}", "func (d *Device) Name() string {\n\treturn string(d.Data.name[:])\n}", "func (os OsType) String() string {\n\treturn os.Name\n}", "func (m Server) String() string {\n\treturn m.Name\n}", "func (cmd *Command) Name() string {\n\treturn strings.SplitN(cmd.Names, \",\", 2)[0]\n}", "func (r *Template) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (o LienOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Lien) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (at AttributeType) Name() string {\n\tswitch at {\n\tcase AttributeTypeStandardInformation:\n\t\treturn \"$STANDARD_INFORMATION\"\n\tcase AttributeTypeAttributeList:\n\t\treturn \"$ATTRIBUTE_LIST\"\n\tcase AttributeTypeFileName:\n\t\treturn \"$FILE_NAME\"\n\tcase AttributeTypeObjectId:\n\t\treturn \"$OBJECT_ID\"\n\tcase AttributeTypeSecurityDescriptor:\n\t\treturn \"$SECURITY_DESCRIPTOR\"\n\tcase AttributeTypeVolumeName:\n\t\treturn \"$VOLUME_NAME\"\n\tcase AttributeTypeVolumeInformation:\n\t\treturn \"$VOLUME_INFORMATION\"\n\tcase AttributeTypeData:\n\t\treturn \"$DATA\"\n\tcase AttributeTypeIndexRoot:\n\t\treturn \"$INDEX_ROOT\"\n\tcase AttributeTypeIndexAllocation:\n\t\treturn \"$INDEX_ALLOCATION\"\n\tcase AttributeTypeBitmap:\n\t\treturn \"$BITMAP\"\n\tcase AttributeTypeReparsePoint:\n\t\treturn \"$REPARSE_POINT\"\n\tcase AttributeTypeEAInformation:\n\t\treturn \"$EA_INFORMATION\"\n\tcase AttributeTypeEA:\n\t\treturn \"$EA\"\n\tcase AttributeTypePropertySet:\n\t\treturn \"$PROPERTY_SET\"\n\tcase AttributeTypeLoggedUtilityStream:\n\t\treturn \"$LOGGED_UTILITY_STREAM\"\n\t}\n\treturn \"unknown\"\n}", "func (a Container) String() string {\n\treturn a.Name.String()\n}", "func (this *NameExpr) String() string {\n\tv := this.GetValue()\n\treturn v.(interface {\n\t\tString() string\n\t}).String()\n}", "func (f Facility) String() string {\n\tname, present := facilityNames[f]\n\tif present {\n\t\treturn name\n\t}\n\treturn \"INVALID\"\n}", "func (e *Definition) Name() string {\n\tstr := e.json.Get(\"name\").Value()\n\tif str == nil {\n\t\treturn \"\"\n\t}\n\treturn str.(string)\n}", "func (e *EntryBase) Name() string {\n\treturn e.name()\n}", "func (d *Document) Name() string {\n\treturn fmt.Sprintf(\"%s-%s\", d.AccountId, d.InstanceId)\n}", "func (t AXPropertyName) String() string {\n\treturn string(t)\n}", "func (t TopicNameType) String() string {\n\treturn string(t)\n}", "func (o StudioOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (g grass) Name() string {\n\tswitch g {\n\tcase 0:\n\t\treturn \"Grass\"\n\tcase 1:\n\t\treturn \"Fern\"\n\t}\n\tpanic(\"unknown grass type\")\n}", "func (Print) Name() compiler.String {\n\treturn compiler.String{\n\t\tcompiler.English: `print`,\n\t}\n}", "func (r *Thing) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (Lawrencium) GetName() string {\n\treturn \"Lawrencium\"\n}", "func (c *cachedKind) String() string {\n\treturn c.name\n}", "func (s *SCEP) GetName() string {\n\treturn s.Name\n}", "func (s *SCEP) GetName() string {\n\treturn s.Name\n}", "func (rr *RecordingRule) String() string {\n\treturn rr.Name\n}", "func (o DicomStoreOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DicomStore) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (i *Item) Name() string {\n\treturn i.name // string(bytes.TrimRight(i.directoryEntry.Filename[:], \"\\x00\"))\n}", "func (e *DirEntry) Name() string {\n\treturn string(e.name)\n}", "func (r *Trail) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (o ReleaseOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Release) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (r OS) Name() string {\n\treturn fmt.Sprintf(\"%v %v\", r.ID, r.Version)\n}", "func (o CryptoKeyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CryptoKey) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o ElastigroupSignalOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupSignal) string { return v.Name }).(pulumi.StringOutput)\n}", "func (d *Driver) Name() string { return d.name }", "func (e *Entry) Name() string {\n\tif len(e.path) == 0 {\n\t\treturn \"\"\n\t}\n\treturn e.path[len(e.path)-1]\n}", "func (k *k8sUtil) Name() string {\n\tns, _ := k.NS()\n\treturn fmt.Sprintf(\"k8sutil @ '%s'\", ns)\n}", "func (k Kind) String() string {\n\treturn kindNames[k]\n}", "func (p Provider) String() string {\n\treturn providerNames[p]\n}", "func (e Enum) String() string {\n\treturn e.Name\n}", "func (o ExportOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Export) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (t *Type) Name() (string, error) {\n\tv := reflect.ValueOf(t.ctyType).MethodByName(\"GoString\")\n\tif !v.IsValid() {\n\t\treturn \"\", fmt.Errorf(\"Faild to find GoString(): %#v\", t)\n\t}\n\n\tnv := v.Call([]reflect.Value{})\n\tif len(nv) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Faild to call GoString(): %#v\", v)\n\t}\n\n\tgoString := nv[0].String()\n\t// drop `cty.` prefix for simplicity. (e.g. cty.String => String)\n\tname := strings.Replace(goString, \"cty.\", \"\", -1)\n\n\treturn name, nil\n}", "func (r *Document) Name() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"name\"])\n}", "func (o SkuOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v Sku) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o AttestorOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Attestor) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (p provider) Name() string {\n\treturn p.name\n}", "func Name(v interface{}) string {\n\treturn New(v).Name()\n}" ]
[ "0.76239175", "0.7596077", "0.7596077", "0.73250514", "0.73232955", "0.7240509", "0.7014141", "0.6975502", "0.69344705", "0.6914544", "0.6905238", "0.6836352", "0.6781786", "0.67532694", "0.67160845", "0.66846424", "0.66834974", "0.6683491", "0.66771424", "0.66757715", "0.6673078", "0.66726464", "0.66716605", "0.66687816", "0.6666157", "0.6663942", "0.66594654", "0.664932", "0.6643914", "0.66298187", "0.66144466", "0.65727997", "0.65706426", "0.6567492", "0.65488356", "0.6545531", "0.6531985", "0.6531985", "0.65271276", "0.65225786", "0.6519072", "0.65161794", "0.6515965", "0.65129983", "0.64959234", "0.64943445", "0.6490366", "0.6488533", "0.6477459", "0.64674425", "0.6453388", "0.64503884", "0.6443968", "0.6434942", "0.6429609", "0.6422925", "0.64199525", "0.64088196", "0.6401568", "0.63947284", "0.6394392", "0.6384408", "0.63801837", "0.6377585", "0.6377139", "0.6376724", "0.6376368", "0.63759", "0.6375698", "0.63742334", "0.6371279", "0.63662094", "0.636394", "0.6359015", "0.6354295", "0.63515824", "0.6350931", "0.6350585", "0.6350585", "0.63417274", "0.6334925", "0.63312227", "0.632659", "0.63257235", "0.63242465", "0.6321273", "0.6320559", "0.6317752", "0.63168854", "0.6316374", "0.63129526", "0.63076806", "0.6306125", "0.6304979", "0.6303685", "0.6302505", "0.63023084", "0.6301867", "0.62992907", "0.6297504", "0.6294301" ]
0.0
-1
Disrupt returns true if the correct string is provided.
func (d *DependencyDisableAutoOnline) Disrupt(s string) bool { return s == "DisableGatewayAutoOnline" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d *HostLowerDeposit) Disrupt(s string) bool {\n\treturn s == \"lowerDeposit\"\n}", "func (d *HostMDMProgramDelayedWrite) Disrupt(s string) bool {\n\treturn s == \"MDMProgramOutputDelayWrite\"\n}", "func (d *DependencyUnsyncedConsensus) Disrupt(s string) bool {\n\treturn s == \"UnsyncedConsensus\"\n}", "func (d *DependencyUnsyncedConsensus) Disrupt(s string) bool {\n\treturn s == \"UnsyncedConsensus\"\n}", "func (*dependencyShrinkNoFinalize) Disrupt(s string) bool {\n\tif s == \"incompleteShrinkStorageFolder\" {\n\t\treturn true\n\t}\n\tif s == \"cleanWALFile\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (*dependencyNoRecheck) Disrupt(s string) bool {\n\tif s == \"noRecheck\" {\n\t\treturn true\n\t}\n\treturn false\n}", "func (d *DependencyDisableAsyncUnlock) Disrupt(s string) bool {\n\treturn s == \"DisableAsyncUnlock\"\n}", "func (d *HostExpireEphemeralAccounts) Disrupt(s string) bool {\n\treturn s == \"expireEphemeralAccounts\"\n}", "func (d *dependencySleepAfterInitializeSubscribe) Disrupt(s string) bool {\n\tif d.f && s == \"SleepAfterInitializeSubscribe\" {\n\t\td.f = false\n\t\treturn true\n\t}\n\treturn false\n}", "func (*blockingPortForward) Disrupt(s string) bool {\n\t// Return an error when clearing the port.\n\tif s == \"managedClearPort return error\" {\n\t\treturn true\n\t}\n\n\t// Block during port forwarding.\n\tif s == \"managedForwardPort\" {\n\t\ttime.Sleep(time.Second * 3)\n\t}\n\treturn false\n}", "func (d *HostRejectAllSessionLocks) Disrupt(s string) bool {\n\td.mu.Lock()\n\tdefer d.mu.Unlock()\n\n\tif !d.started {\n\t\treturn false\n\t}\n\treturn s == \"loopLockNoRecordOfThatContract\"\n}", "func Valid(s string) bool { return Convert(s) == s && s != \"\" }", "func checkRecord(s string) bool {\n\n}", "func checkStr(s string) bool {\n\ts = strings.ToLower(s)\n\n\t// Ensure any embedded suffix / delimiter is removed as I'm using ReadString() function to capture.\n\t// In *nix, expect suffix '\\n', in Windows expect suffix '\\r\\n'\n\ts = strings.TrimSuffix(s, \"\\n\")\n\ts = strings.TrimSuffix(s, \"\\r\")\n\n\tif strings.HasPrefix(s, \"i\") && strings.HasSuffix(s, \"n\") && strings.Contains(s, \"a\") {\n\t\treturn true\n\t}\n\treturn false\n}", "func teststring(t *testing.T, s string) {\n\tbuf := toint8(s)\n\tr := kstat.CFieldString(buf[:])\n\tif r != s {\n\t\tt.Fatalf(\"full buf mismatch: %q vs %q\", s, r)\n\t}\n\tr = kstat.CFieldString(buf[:len(s)])\n\tif r != s {\n\t\tt.Fatalf(\"exact buf mismatch: %q vs %q\", s, r)\n\t}\n\tr = kstat.CFieldString(buf[:len(s)+1])\n\tif r != s {\n\t\tt.Fatalf(\"string + one null mismatch: %q vs %q\", s, r)\n\t}\n\tif len(s) > 1 {\n\t\tr = kstat.CFieldString(buf[:1])\n\t\tif r != s[:1] {\n\t\t\tt.Fatalf(\"first character mismatch: %q vs %q\", s[:1], r)\n\t\t}\n\t}\n}", "func (stringEntry *String) IsPersistant() bool {\n\treturn stringEntry.isPersistant\n}", "func (s StringFileInfo) Skip() bool { return (s.Type != 0 && s.Type != 1) && s.ValueLength != 0 }", "func consume(s *string, ch byte) (ok bool) {\n\tif *s == \"\" || (*s)[0] != ch {\n\t\treturn false\n\t}\n\t*s = (*s)[1:]\n\treturn true\n}", "func String(tst *testing.T, str, correct string) {\n\tif str != correct {\n\t\tPrintFail(\"error %q != %q\\n\", str, correct)\n\t\ttst.Errorf(\"string failed with: %q != %q\", str, correct)\n\t\treturn\n\t}\n\tPrintOk(\"%s == %s\", str, correct)\n}", "func TestWriteAndReadSingleStringsNotIndexed(t *testing.T) {\n\tvar ctx = context.Background()\n\tvar buf = internal.NewAnonymousFile()\n\tvar writer *Writer = NewWriter(ctx, buf)\n\tvar reader *Reader\n\tvar keys []string\n\tvar k, v string\n\tvar err error\n\n\tfor k, _ = range testdata {\n\t\tkeys = append(keys, k)\n\t}\n\n\tsort.Strings(keys)\n\n\t// Fill the sstable with some test data.\n\tfor _, k = range keys {\n\t\tv = testdata[k]\n\t\terr = writer.WriteString(ctx, k, v)\n\t\tif err != nil {\n\t\t\tt.Error(\"Error writing record \", k, \": \", err)\n\t\t}\n\t}\n\n\t// Reset position.\n\tbuf.Close(ctx)\n\n\t// Now try reading it back and comparing.\n\treader = NewReader(buf)\n\tv, err = reader.ReadString(ctx, \"mmm\")\n\tif err != nil {\n\t\tt.Error(\"Error reading record mmm: \", err)\n\t}\n\tif v != testdata[\"mmm\"] {\n\t\tt.Error(\"Mismatched data: expected \", testdata[\"mmm\"], \", got \", v)\n\t}\n\n\t// Reset position.\n\tbuf.Close(ctx)\n\n\t// Try to read a nonexistent key.\n\treader = NewReader(buf)\n\tv, err = reader.ReadString(ctx, \"nonexistent\")\n\tif err != nil {\n\t\tt.Error(\"Error reading nonexistent record: \", v)\n\t}\n\tif len(v) > 0 {\n\t\tt.Error(\"Reading nonexistent record returned \", v,\n\t\t\t\", should be nothing\")\n\t}\n\n\t// Reset position.\n\tbuf.Close(ctx)\n\n\t// Try to read a nonexistent key.\n\treader = NewReader(buf)\n\tk, v, err = reader.ReadSubsequentString(ctx, \"maa\")\n\tif err != nil {\n\t\tt.Error(\"Error reading first record after maa: \", v)\n\t}\n\tif k != \"mars\" {\n\t\tt.Error(\"Mismatched key: expected mars, got \", k)\n\t}\n\tif v != testdata[\"mars\"] {\n\t\tt.Error(\"Mismatched data: expected \", testdata[\"mars\"], \", got \", v)\n\t}\n}", "func (t TestDescription) Disruptive() TestDescription {\n\treturn t.newLabel(\"DISRUPTIVE\")\n}", "func validateSeqString(dna string, gaps bool) error {\n\treturn validateSeqBytes([]byte(dna), gaps)\n}", "func shouldKeepLooking(inputIndex, inputSize int, inputR []rune, next rune) bool {\n\treturn inputIndex < inputSize && inputR[inputIndex] != next\n}", "func checkRecord(s string) bool {\n\tvar absent bool\n\tfor i, r := range s {\n\t\tswitch r {\n\t\tcase 'L':\n\t\t\tif i < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprev := s[i-2 : i]\n\t\t\tif prev[0] == 'L' && prev[1] == 'L' {\n\t\t\t\treturn false\n\t\t\t}\n\t\tcase 'A':\n\t\t\tif absent {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tabsent = true\n\t\t}\n\t}\n\treturn true\n}", "func checkString(alph map[rune]int, input string) bool {\n\tfor _, rune := range input {\n\t\talph[rune]--\n\t\tif alph[rune] < 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func validPalindrome(s string) bool {\n return validPalindromeDeleted(s, false)\n}", "func gostringnocopy(str *byte) string", "func (e DirectoryEntry) IsString() bool { return ((e.Name & 0x80000000) >> 31) > 0 }", "func CheckStr(s string) bool {\n\treturn reverseStr(s) == s\n}", "func testEDString(t testing.TB) {\n\tvar line = \"62705320001912345 0000010500c-1 Arnold Wade DD0076401255655291\"\n\tr := NewReader(strings.NewReader(line))\n\tr.addCurrentBatch(NewBatchPPD(mockBatchPPDHeader()))\n\tr.currentBatch.SetHeader(mockBatchHeader())\n\tr.line = line\n\tif err := r.parseEntryDetail(); err != nil {\n\t\tt.Errorf(\"%T: %s\", err, err)\n\t}\n\trecord := r.currentBatch.GetEntries()[0]\n\n\tif record.String() != line {\n\t\tt.Errorf(\"Strings do not match\")\n\t}\n}", "func IsOneEditAway(str1, str2 string) bool {\n\tif len(str1) == len(str2) {\n\t\tfoundOneEdit := false\n\t\tfor i, c := range str1 {\n\t\t\tif str2[i] != byte(c) {\n\t\t\t\tif foundOneEdit {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfoundOneEdit = true\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\tif len(str1) == len(str2)+1 || len(str1)+1 == len(str2) {\n\t\tif len(str1) < len(str2) {\n\t\t\tstr1, str2 = str2, str1\n\t\t}\n\t\tfoundOneEdit := false\n\t\tshorterI, longerI := 0, 0\n\t\tfor shorterI < len(str2) && longerI < len(str1) {\n\t\t\tif str1[longerI] == str2[shorterI] {\n\t\t\t\tshorterI++\n\t\t\t} else {\n\t\t\t\tif foundOneEdit {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tfoundOneEdit = true\n\t\t\t}\n\t\t\tlongerI++\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func DiscoverCard(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\n\ts = stripNonNumeric(s)\n\n\tif len(s) != 16 {\n\t\treturn false\n\t}\n\n\tif s[0:2] != \"65\" && s[0:4] != \"6011\" {\n\t\treturn false\n\t}\n\n\treturn luhn(s)\n}", "func isRotation(s1 string, s2 string) bool {\n\n\t/* check that s1 and s2 are equal length and not empty */\n\tif len(s1) == len(s2) && len(s1) > 0 {\n\n\t\t/* concatenate s1 and s1 within new buffer */\n\t\ts1s1 := s1 + s1\n\t\treturn strings.Contains(s1s1, s2)\n\t}\n\treturn false\n}", "func containsString(slice []string, element string) bool {\n\treturn !(posString(slice, element) == -1)\n}", "func containsString(slice []string, element string) bool {\n\treturn !(posString(slice, element) == -1)\n}", "func containsString(slice []string, element string) bool {\n\treturn !(posString(slice, element) == -1)\n}", "func containsString(slice []string, element string) bool {\n\treturn !(posString(slice, element) == -1)\n}", "func containsString(slice []string, element string) bool {\n\treturn !(posString(slice, element) == -1)\n}", "func containsString(slice []string, element string) bool {\n\treturn !(posString(slice, element) == -1)\n}", "func verifyHasString(T *testing.T, s string, code string) {\n\tif strings.Index(code, s) == -1 {\n\t\tT.Errorf(\"expected to find %s in the generated code:\\n%s\\n\", s, code)\n\t}\n}", "func areEqual(b []byte, s string) bool {\n if len(b) != len(s) {\n return false\n }\n\n for i, byte := range b {\n if byte != s[i] {\n return false\n }\n }\n\n return true\n}", "func unique(s string) bool {\n\tb := []byte(s)\n\td := make([]bool, 95)\n\tfor i := range b {\t\t\n\t\tb[i] -= 33\n\t\tif b[i] >= 0 && b[i] <= 94 {\n\t\t\tif d[b[i]] {\n\t\t\t\treturn false\n\t\t\t} else {\n\t\t\t\td[b[i]] = true;\n\t\t\t}\n\t\t}\t\t\t\t\t\n\t}\n\treturn true\n}", "func (m *WZFileBlob) readDeDuplicatedWZString(uol string, possibleNeededOffset int64, addOffset bool) (result string) {\n\tkey := m.readByte()\n\tstr := \"\"\n\tswitch key {\n\tcase 0, 0x73:\n\t\tstr = m.readWZString(uol)\n\tcase 1, 0x1B:\n\t\tm.peekFor(func() {\n\t\t\ttmp := possibleNeededOffset\n\t\t\tif addOffset {\n\t\t\t\ttmp += int64(m.readUInt32())\n\t\t\t} else {\n\t\t\t\ttmp -= int64(m.readUInt32())\n\t\t\t}\n\t\t\tif m.Debug {\n\t\t\t\tm.debug(\"Reading dedup string at \", tmp)\n\t\t\t}\n\t\t\tm.seek(tmp)\n\t\t\tstr = m.readWZString(uol)\n\t\t})\n\tdefault:\n\t\tpanic(\"Unknown deduplicated wz string type: \" + strconv.Itoa(int(key)) + \" at \" + uol + \" AT \" + strconv.Itoa(int(m.pos())))\n\t}\n\n\tif m.Debug {\n\t\tm.debug(\"Dedupped string for \", uol, \": \", str)\n\t}\n\treturn str\n}", "func (me TxsdSpace) IsPreserve() bool { return me.String() == \"preserve\" }", "func palindrome(str string) bool {\n\treturn false\n}", "func oneEditAway(str1 string, str2 string) bool {\n\n\tlen1 := len(str1)\n\tlen2 := len(str2)\n\tvar smaller, bigger string\n\n\tif math.Abs(float64(len1-len2)) > 1 {\n\t\treturn false\n\t}\n\n\tif len1 < len2 {\n\t\tsmaller = str1\n\t\tbigger = str2\n\t} else {\n\t\tsmaller = str2\n\t\tbigger = str1\n\n\t}\n\n\tvar i, j int\n\tmismatchDone := false\n\n\tfor i < len(smaller) && j < len(bigger) {\n\n\t\tif smaller[i] != bigger[j] {\n\t\t\tif mismatchDone {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tmismatchDone = true\n\t\t\tif len1 == len2 {\n\t\t\t\ti++ //case of replace\n\t\t\t} // else case of replace.dont move small pointer\n\t\t} else {\n\t\t\ti++ //move short pointer if its a match, dont move it in case of first mismatch\n\t\t}\n\t\tj++ //always move long string pointer.\n\t}\n\treturn true\n}", "func confirm(stdin io.Reader, stdout io.Writer, s string, tries int) (bool, error) {\n\tr := bufio.NewReader(stdin)\n\n\tfor ; tries > 0; tries-- {\n\t\tfmt.Fprintf(stdout, \"%s [y/n]: \", s)\n\n\t\tres, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// Empty input (i.e. \"\\n\")\n\t\tif len(res) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch strings.ToLower(strings.TrimSpace(res)) {\n\t\tcase \"y\":\n\t\t\treturn true, nil\n\t\tcase \"n\":\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tfmt.Fprintf(stdout, \"Invalid input.\\n\")\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func checkRead(t *testing.T, testname string, b *Builder, s string) {\n\tbytes := b.Bytes()\n\tstr := b.String()\n\tif b.Len() != len(str) {\n\t\tt.Errorf(\"%s: b.Len() == %d, len(b.String()) == %d\", testname, b.Len(), len(str))\n\t}\n\tif string(bytes) != s {\n\t\tt.Errorf(\"%s: string(b.Bytes()) == %q, s == %q\", testname, string(bytes), s)\n\t}\n}", "func testNondedupContentExists(t *testing.T, cluster ardb.StorageCluster, vdiskID string, blockIndex int64, content []byte) {\n\tstorageKey := nonDedupedStorageKey(vdiskID)\n\tcontentReceived, err := ardb.Bytes(\n\t\tcluster.DoFor(blockIndex, ardb.Command(command.HashGet, storageKey, blockIndex)))\n\tif err != nil {\n\t\tdebug.PrintStack()\n\t\tt.Fatal(err)\n\t}\n\tif bytes.Compare(content, contentReceived) != 0 {\n\t\tdebug.PrintStack()\n\t\tt.Fatalf(\n\t\t\t\"content found (%v) does not equal content expected (%v)\",\n\t\t\tcontentReceived, content)\n\t}\n}", "func (e *ObservableEditableBuffer) Dirty() bool {\n\treturn e.seq != e.putseq\n}", "func (v *missingValue) SetString(value string) bool {\n\treturn false\n}", "func IsString(input []byte) bool {\n\treturn len(input) >= 2 && input[0] == '\"' && input[len(input)-1] == '\"'\n\n}", "func Repair(lg *zap.Logger, dirpath string) bool {\n\tif lg == nil {\n\t\tlg = zap.NewNop()\n\t}\n\tf, err := openLast(lg, dirpath)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer f.Close()\n\n\tlg.Info(\"repairing\", zap.String(\"path\", f.Name()))\n\n\trec := &walpb.Record{}\n\tdecoder := newDecoder(fileutil.NewFileReader(f.File))\n\tfor {\n\t\tlastOffset := decoder.lastOffset()\n\t\terr := decoder.decode(rec)\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\t// update crc of the decoder when necessary\n\t\t\tswitch rec.Type {\n\t\t\tcase crcType:\n\t\t\t\tcrc := decoder.crc.Sum32()\n\t\t\t\t// current crc of decoder must match the crc of the record.\n\t\t\t\t// do no need to match 0 crc, since the decoder is a new one at this case.\n\t\t\t\tif crc != 0 && rec.Validate(crc) != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tdecoder.updateCRC(rec.Crc)\n\t\t\t}\n\t\t\tcontinue\n\n\t\tcase errors.Is(err, io.EOF):\n\t\t\tlg.Info(\"repaired\", zap.String(\"path\", f.Name()), zap.Error(io.EOF))\n\t\t\treturn true\n\n\t\tcase errors.Is(err, io.ErrUnexpectedEOF):\n\t\t\tbf, bferr := os.Create(f.Name() + \".broken\")\n\t\t\tif bferr != nil {\n\t\t\t\tlg.Warn(\"failed to create backup file\", zap.String(\"path\", f.Name()+\".broken\"), zap.Error(bferr))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tdefer bf.Close()\n\n\t\t\tif _, err = f.Seek(0, io.SeekStart); err != nil {\n\t\t\t\tlg.Warn(\"failed to read file\", zap.String(\"path\", f.Name()), zap.Error(err))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif _, err = io.Copy(bf, f); err != nil {\n\t\t\t\tlg.Warn(\"failed to copy\", zap.String(\"from\", f.Name()+\".broken\"), zap.String(\"to\", f.Name()), zap.Error(err))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tif err = f.Truncate(lastOffset); err != nil {\n\t\t\t\tlg.Warn(\"failed to truncate\", zap.String(\"path\", f.Name()), zap.Error(err))\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tstart := time.Now()\n\t\t\tif err = fileutil.Fsync(f.File); err != nil {\n\t\t\t\tlg.Warn(\"failed to fsync\", zap.String(\"path\", f.Name()), zap.Error(err))\n\t\t\t\treturn false\n\t\t\t}\n\t\t\twalFsyncSec.Observe(time.Since(start).Seconds())\n\n\t\t\tlg.Info(\"repaired\", zap.String(\"path\", f.Name()), zap.Error(io.ErrUnexpectedEOF))\n\t\t\treturn true\n\n\t\tdefault:\n\t\t\tlg.Warn(\"failed to repair\", zap.String(\"path\", f.Name()), zap.Error(err))\n\t\t\treturn false\n\t\t}\n\t}\n}", "func checkPlayAgain(consolereader *bufio.Reader) bool {\n\tfor {\n\t\tfmt.Print(\"Play again? (Y/N): \")\n\t\tinput, err := consolereader.ReadString('\\n')\n\n\t\tif err != nil {\n\t\t\tfmt.Print(\"Please enter a correct value: \")\n\t\t\tcontinue\n\t\t}\n\n\t\tinput = strings.TrimSuffix(input, \"\\r\\n\")\n\t\tif input == \"Y\" || input == \"y\" {\n\t\t\treturn true\n\t\t}\n\t\tif input == \"N\" || input == \"n\" {\n\t\t\treturn false\n\t\t}\n\t}\n}", "func confirm(stdin io.Reader, stdout io.Writer, s string, tries int) (bool, error) {\n\tr := bufio.NewReader(stdin)\n\n\tfor ; tries > 0; tries-- {\n\t\tfmt.Fprintf(stdout, \"%s [y/n]: \", s)\n\n\t\tres, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\t// Empty input (i.e. \"\\n\")\n\t\tif len(res) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch strings.ToLower(strings.TrimSpace(res)) {\n\t\tcase \"y\":\n\t\t\treturn true, nil\n\t\tcase \"n\":\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn false, nil\n}", "func EndsWithStr(str, target string) bool {\n\tstrLen := len(str)\n\ttarLen := len(target)\n\tchunk := str[strLen-tarLen:]\n\treturn chunk == target\n}", "func strEq(s1, s2 string) bool {\n if len(s1) != len(s2) {\n return false\n }\n\n for i := range s1 {\n if s1[i] != s2[i] {\n return false\n }\n }\n\n return true\n}", "func (r *Reader) SkipString() {\n\tsize := r.ReadLong()\n\tif size <= 0 {\n\t\treturn\n\t}\n\tr.SkipNBytes(int(size))\n}", "func String(a string, b string) bool {\n\treturn a == b\n}", "func (me TdtypeType) IsString() bool { return me.String() == \"string\" }", "func TestStrings(t *testing.T){\n\tsrc := \"a\\\\b\\nc\\n\"\n\tdst := \"a\\\\\\\\b\\\\nc\\\\n\"\n\tif StringEscape(src) != dst {\n\t\tt.Fatal(dst, StringEscape(src))\n\t}\n\t// rev := StringUnescape(dst)\n\trev := dst\n\tfmt.Println(src)\n\tfmt.Println(dst)\n\tfmt.Println(rev)\n}", "func ValidateString(value string) bool {\n\tif len(value) == 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func String(s string) bool {\n\tfor i := 0; i < len(s); i++ {\n\t\tif b := s[i]; b < '0' || b > '9' {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func consume(r *strings.Reader, wanted byte) bool {\n\tif r.Len() > 0 {\n\t\tb, _ := r.ReadByte()\n\t\tif b == wanted {\n\t\t\treturn true\n\t\t}\n\t\tr.UnreadByte()\n\t}\n\treturn false\n}", "func (s *Scheduler) isHotString(filename string, str string) bool {\n\tstr = strings.ToLower(str)\n\tmatcher, ok := s.matcher[filename]\n\tif !ok {\n\t\tlog.Panicf(\"invalid filename detected %v\", filename)\n\t}\n\tisHot := len(matcher.MatchThreadSafe([]byte(str))) > 0\n\tif s.customFilter != nil {\n\t\treturn s.customFilter(str, isHot)\n\t}\n\treturn isHot\n}", "func checkStringNotAKeyword(s string, keys []string) error {\n\tif sliceContainsString(s, keys) {\n\t\treturn fmt.Errorf(\"Syntax error, back-to-back keyword: %s\", s)\n\t}\n\treturn nil\n}", "func down(start, end int, s string, ret [][]string) bool {\n\tfor i := 0; i < end-start; i++ {\n\t\tif start+i+2 > len(s) {\n\t\t\tbreak\n\t\t}\n\t\tc := s[start+i+1 : start+i+2]\n\t\tif len(c) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tret[i+1] = append(ret[i+1], c)\n\t}\n\n\treturn end < len(s)\n}", "func skipECS(file io.Reader) error {\n\tbuf := make([]byte, len(EncryptConfirmString))\n\tif _, err := io.ReadFull(file, buf); err != nil {\n\t\treturn err\n\t}\n\tif string(buf) != EncryptConfirmString {\n\t\treturn errors.New(\"data does not start with ECS\")\n\t}\n\treturn nil\n}", "func (me TAttlistSupplMeshNameType) IsDisease() bool { return me.String() == \"Disease\" }", "func (s commitLogSource) shouldReturnUnfulfilled(\n\tencounteredCorruptData bool,\n\tns namespace.Metadata,\n\tshardsTimeRanges result.ShardTimeRanges,\n\topts bootstrap.RunOptions,\n) (bool, error) {\n\tif !s.opts.ReturnUnfulfilledForCorruptCommitLogFiles() {\n\t\ts.log.Info(\"returning not-unfulfilled: ReturnUnfulfilledForCorruptCommitLogFiles is false\")\n\t\treturn false, nil\n\t}\n\n\tif !encounteredCorruptData {\n\t\ts.log.Info(\"returning not-unfulfilled: no corrupt data encountered\")\n\t\treturn false, nil\n\t}\n\n\tareShardsReplicated := s.areShardsReplicated(\n\t\tns, shardsTimeRanges, opts)\n\tif !areShardsReplicated {\n\t\ts.log.Info(\"returning not-unfulfilled: replication is not enabled\")\n\t}\n\n\treturn areShardsReplicated, nil\n}", "func (c *StringNotMatchCondition) Fulfills(value interface{}, _ *ladon.Request) bool {\n\ts, ok := value.(string)\n\n\tlog.Logger(context.Background()).Error(\"in string not match condition for string \" + s)\n\n\tmatches, _ := regexp.MatchString(c.Matches, s)\n\n\treturn !(ok && matches)\n}", "func equalStringSliceIgnoreOrder(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\tfound := false\n\n\t\tfor j := 0; j < len(b); j++ {\n\t\t\tif a[i] == b[j] {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (keyDB *KeyDB) ShouldRecover(lastAvailableBlock uint64) (bool, uint64, error) {\n\tsavepoint, err := keyDB.GetLastSavepoint()\n\tif err != nil {\n\t\treturn false, 0, err\n\t}\n\tif savepoint == nil {\n\t\treturn true, 0, nil\n\t}\n\treturn savepoint.BlockNum != lastAvailableBlock, savepoint.BlockNum + 1, nil\n}", "func (l *reader) accept(valid string) bool {\n\tif strings.IndexRune(valid, l.next()) >= 0 {\n\t\treturn true\n\t}\n\tl.backup()\n\treturn false\n}", "func suppressDurationStringDiff(_, old, new string, _ *schema.ResourceData) bool {\n\tif old == \"\" || new == \"\" {\n\t\treturn false\n\t}\n\n\toldDuration, _ := time.ParseDuration(old)\n\tnewDuration, _ := time.ParseDuration(new)\n\n\treturn oldDuration.Seconds() == newDuration.Seconds()\n}", "func VerifyReadSucess(t *testing.T,output string,version int64,contents string,outputcontnets string) {\n\tarr := strings.Split(output, \" \")\n\texpect(t, arr[0], \"CONTENTS\")\n expect(t, arr[1], fmt.Sprintf(\"%v\", version)) // expect only accepts strings, convert int version to string\n expect(t, arr[2], fmt.Sprintf(\"%v\", len(contents)))\n expect(t, contents, outputcontnets)\n}", "func (e ChecksumMismatch) IsChecksumMismatch() {}", "func SliceEqualsString(x, y []string) bool {\n\tif len(x) != len(y) {\n\t\treturn false\n\t}\n\tdiff := make(map[string]int, len(x))\n\tfor _, ix := range x {\n\t\tdiff[ix]++\n\t}\n\tfor _, iy := range y {\n\t\tif _, ok := diff[iy]; !ok {\n\t\t\treturn false\n\t\t}\n\t\tdiff[iy]--\n\t\tif diff[iy] == 0 {\n\t\t\tdelete(diff, iy)\n\t\t}\n\t}\n\n\treturn len(diff) == 0\n}", "func oneAway(s1, s2 string) bool {\n\tif math.Abs(float64(len(s1)-len(s2))) > 1 {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(s1) && i < len(s2); i++ {\n\t\tif s1[i] != s2[i] {\n\t\t\t// add\n\t\t\tsa1 := s1[:i] + string(s2[i]) + s1[i:]\n\t\t\tsa2 := s2[:i] + string(s1[i]) + s2[i:]\n\t\t\tif sa1 == s2 || sa2 == s1 {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t// remove\n\t\t\tsd1 := s1[:i] + s1[i+1:]\n\t\t\tsd2 := s2[:i] + s2[i+1:]\n\t\t\tif sd1 == s2 || sd2 == s1 {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\t// replace\n\t\t\tsr1 := s1[:i] + string(s2[i]) + s1[i+1:]\n\t\t\tsr2 := s2[:i] + string(s1[i]) + s2[i+1:]\n\t\t\tif sr1 == s2 || sr2 == s1 {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (disk *DiskInfoSimple) IsRepaired() bool {\n\treturn disk.Status == proto.DiskStatusRepaired\n}", "func (me TxsdSystemSpoofed) IsNo() bool { return me.String() == \"no\" }", "func NiceTestThree(s string) bool {\n\tvar forbidden = []string{\"ab\", \"cd\", \"pq\", \"xy\"}\n\tvar previous string\n\tfor _, char := range s {\n\t\tfor _, forbid := range forbidden {\n\t\t\tif previous+string(char) == forbid {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tprevious = string(char)\n\t}\n\treturn true\n}", "func isExclamation(a string) bool {\n\treturn strings.ToUpper(a) == a && strings.ToUpper(a) != strings.ToLower(a)\n}", "func (s DnaString) IsExact(s2 string) bool {\n\tchain1 := strings.ToLower(s.Value)\n\tchain2 := strings.ToLower(s2)\n\tlogger.Debugf(\"Bio isexact %s %s\", chain1, chain2)\n\n\ts1Len := len(chain1)\n\ts2Len := len(chain2)\n\tif s1Len != s2Len {\n\t\treturn false\n\t}\n\tfor i := 0; i < s1Len; i++ {\n\t\tchain2Char := chain2[i : i+1]\n\t\tmorph, ok := s.AllowedMorphisms[chain2Char]\n\t\tif ok {\n\t\t\tgotcha := false\n\t\t\tfor _, charMap := range morph {\n\t\t\t\tif chain1[i:i+1] == charMap {\n\t\t\t\t\tgotcha = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !gotcha {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif chain1[i:i+1] == \"n\" || chain2Char == \"n\" {\n\t\t\t\tcontinue\n\t\t\t} else if chain1[i] != chain2[i] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func check(t *testing.T, testname string, buf *Buffer, s string) {\n\tbytes := buf.Bytes()\n\tstr := buf.String()\n\tif buf.Len() != len(bytes) {\n\t\tt.Errorf(\"%s: buf.Len() == %d, len(buf.Bytes()) == %d\", testname, buf.Len(), len(bytes))\n\t}\n\n\tif buf.Len() != len(str) {\n\t\tt.Errorf(\"%s: buf.Len() == %d, len(buf.String()) == %d\", testname, buf.Len(), len(str))\n\t}\n\n\tif buf.Len() != len(s) {\n\t\tt.Errorf(\"%s: buf.Len() == %d, len(s) == %d\", testname, buf.Len(), len(s))\n\t}\n\n\tif string(bytes) != s {\n\t\tt.Errorf(\"%s: string(buf.Bytes()) == %q, s == %q\", testname, string(bytes), s)\n\t}\n}", "func MustReadFileString(filename string) string {\n\ts, err := ReadFileString(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}", "func containsString(s []string, e string) bool {\n\treturn sliceIndex(s, e) > -1\n}", "func palindromable(s string) bool {\n\tbs := []byte(s)\n\tm := make(map[byte]int)\n\tfor _, b := range bs {\n\t\tm[b]++\n\t}\n\tcenter := len(bs) % 2\n\tfor _, v := range m {\n\t\tif v%2 != 0 {\n\t\t\tif center == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcenter--\n\t\t}\n\t}\n\treturn true\n}", "func TestStringPrimitives(t *testing.T) {\n\to := old()\n\ts := \"now is the time\"\n\to.EncodeStringBytes(s)\n\tdecs_data, e := o.DecodeRawBytes()\n\tdecs := make([]byte, len(decs_data))\n\tcopy(decs, decs_data)\n\tif e != nil {\n\t\tt.Error(\"dec_string\")\n\t}\n\tif s != string(decs) {\n\t\tt.Error(\"string encode/decode fail:\", s, decs)\n\t}\n}", "func (conn *extHost) isDrained(replySeqNo int64) bool {\n\tconn.lk.RLock()\n\tif conn.state != extHostCloseWrite {\n\t\tconn.lk.RUnlock()\n\t\treturn false\n\t}\n\n\tret := false\n\tif atomic.LoadInt64(&conn.seqNo) == replySeqNo {\n\t\tconn.logger.WithFields(bark.Fields{\n\t\t\t`drainedSeqNo`: replySeqNo,\n\t\t}).Info(\"extent drained completely\")\n\t\tret = true\n\t}\n\n\tconn.lk.RUnlock()\n\treturn ret\n}", "func (z *Big) SetString(s string) (*Big, bool) {\n\tif err := z.scan(strings.NewReader(s)); err != nil {\n\t\treturn nil, false\n\t}\n\treturn z, true\n}", "func verifyStringProperty(s *Step, ps *Steps) error {\n\tpStr := ps.data.GetStringObjectValue(s.parameter)\n\tstrValue, ok := s.value.(string)\n\tif pStr == nil || !ok || *pStr != strValue {\n\t\treturn ps.getError(fmt.Sprintf(\"bad value for %s\", s.parameter))\n\t}\n\treturn nil\n}", "func isValidByline(str string) bool {\n\treturn strLen(str) > 0 && strLen(str) < 100\n}", "func TestStringNormalize(t *testing.T) {\n\tdata1 := \"NFzcPqhviddjRNnSOGo4rw==\"\n\tdata2 := \"text/plain\"\n\tdata3 := \"Mon, 27 Apr 2015 16:23:49 +0800\"\n\n\tresult1 := \"NFzcPqhviddjRNnSOGo4rw%3D%3D\"\n\tresult2 := \"text%2Fplain\"\n\tresult3 := \"Mon%2C%2027%20Apr%202015%2016%3A23%3A49%20%2B0800\"\n\n\ttestRes1 := stringNormalize(data1, true)\n\ttestRes2 := stringNormalize(data2, true)\n\ttestRes2WithoutSlash := stringNormalize(data2, false)\n\ttestRes3 := stringNormalize(data3, true)\n\n\terrorMsg := \"string normalize test fail %s\"\n\tif testRes1 != result1 {\n\t\tt.Errorf(errorMsg, testRes1)\n\t}\n\tif testRes2 != result2 {\n\t\tt.Errorf(errorMsg, testRes2)\n\t}\n\tif testRes2WithoutSlash != data2 {\n\t\tt.Errorf(errorMsg, testRes2WithoutSlash)\n\t}\n\tif testRes3 != result3 {\n\t\tt.Errorf(errorMsg, testRes3)\n\t}\n\n\tt.Log(\"string normalize test success\")\n}", "func Palindrome(str string) bool {\n\tj := len(str) - 1\n\n\tfor i := 0; i != j; i++ {\n\t\tif str[i] != str[j] {\n\t\t\treturn false\n\t\t}\n\t\tj--\n\t}\n\n\treturn true\n}", "func AssertString(t *testing.T, got string, want string) {\n\tt.Helper()\n\tif got != want {\n\t\tt.Errorf(\"got %q, want %q\", got, want)\n\t}\n}", "func hasDoubleJumpLetter(str *string) bool {\n\tif len(*str) < 3 {\n\t\treturn false\n\t}\n\n\tprev := 0\n\tfor i := 2; i < len(*str); i++ {\n\t\tif (*str)[prev] == (*str)[i] {\n\t\t\treturn true\n\t\t}\n\n\t\tprev = i - 1\n\t}\n\n\treturn false\n}", "func (s *String) IsNil() bool {\n\treturn s == nil\n}", "func VerifyDataInvariant(t *testing.T, data Data) {\n\toldLen := data.Len()\n\tdataString := fmt.Sprintf(\"%+v\", data)\n\n\tdata.Len()\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n\n\tdata.Less(0, oldLen/2)\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n\n\tdata.Type()\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n\n\tdata.Slice(0, oldLen/2)\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n\n\tdata.Append(data)\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n\n\tdata.Duplicate(5)\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n\n\t// allow types to not implement Strings() with a proper error message\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\trequire.Contains(t, r.(string), \"cannot be cast to strings\")\n\t\t}\n\t}()\n\tdata.Strings()\n\trequire.Equal(t, oldLen, data.Len())\n\trequire.Equal(t, dataString, fmt.Sprintf(\"%+v\", data))\n}", "func (s String) IsDisjoint(other String) bool {\n\tfor k := range s {\n\t\tif _, ok := other[k]; ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}" ]
[ "0.7409636", "0.7348035", "0.7164227", "0.7164227", "0.69773644", "0.6653572", "0.66276544", "0.6580599", "0.6532585", "0.63150513", "0.6164744", "0.50763667", "0.5054735", "0.4899544", "0.48503143", "0.48239964", "0.4809021", "0.4808761", "0.47824186", "0.4775752", "0.47520635", "0.47431502", "0.47421494", "0.47089192", "0.46999162", "0.4670502", "0.46519163", "0.46335253", "0.46272478", "0.4621496", "0.4611238", "0.4595805", "0.4577672", "0.45531854", "0.45531854", "0.45531854", "0.45531854", "0.45531854", "0.45531854", "0.45507595", "0.45333374", "0.45189", "0.4514057", "0.45138472", "0.45096213", "0.45009336", "0.4495328", "0.44904146", "0.44768488", "0.44680047", "0.44605944", "0.44515452", "0.44514036", "0.44281697", "0.4425898", "0.4423175", "0.44166252", "0.4416212", "0.43984097", "0.43973595", "0.43964037", "0.43949217", "0.4394607", "0.43943587", "0.43788064", "0.43733191", "0.43625614", "0.4361276", "0.4361078", "0.43522987", "0.43462688", "0.43442646", "0.43393758", "0.43367678", "0.4333467", "0.43327323", "0.4332003", "0.43186784", "0.4305394", "0.43005344", "0.42859763", "0.4278501", "0.42781273", "0.42732012", "0.42666978", "0.42617878", "0.42583132", "0.42487434", "0.4235265", "0.4230922", "0.4228142", "0.42260674", "0.42229575", "0.4221884", "0.42125607", "0.4208832", "0.4198127", "0.419178", "0.41904485", "0.41836476" ]
0.66241425
7
NewRobertaLMHead creates new RobertaLMHead.
func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead { dense := nn.NewLinear(p.Sub("dense"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig()) layerNormConfig := nn.DefaultLayerNormConfig() layerNormConfig.Eps = 1e-12 layerNorm := nn.NewLayerNorm(p.Sub("layer_norm"), []int64{config.HiddenSize}, layerNormConfig) decoder := util.NewLinearNoBias(p.Sub("decoder"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig()) bias := p.NewVar("bias", []int64{config.VocabSize}, nn.NewKaimingUniformInit()) return &RobertaLMHead{ dense: dense, decoder: decoder, layerNorm: layerNorm, bias: bias, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRobertaClassificationHead(p *nn.Path, config *bert.BertConfig) *RobertaClassificationHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\tnumLabels := int64(len(config.Id2Label))\n\toutProj := nn.NewLinear(p.Sub(\"out_proj\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\n\treturn &RobertaClassificationHead{\n\t\tdense: dense,\n\t\tdropout: dropout,\n\t\toutProj: outProj,\n\t}\n}", "func newHead(vres *salesviews.HeadView) *Head {\n\tres := &Head{}\n\tif vres.ID != nil {\n\t\tres.ID = *vres.ID\n\t}\n\tif vres.Name != nil {\n\t\tres.Name = *vres.Name\n\t}\n\treturn res\n}", "func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tlmHead := NewRobertaLMHead(p.Sub(\"lm_head\"), config)\n\n\treturn &RobertaForMaskedLM{\n\t\troberta: roberta,\n\t\tlmHead: lmHead,\n\t}\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func NewHeadTracker(orm *models.ORM) (*HeadTracker, error) {\n\tht := &HeadTracker{orm: orm}\n\tblockHeaders := []models.BlockHeader{}\n\terr := orm.AllByIndex(\"Number\", &blockHeaders, storm.Limit(1), storm.Reverse())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(blockHeaders) > 0 {\n\t\tht.blockHeader = &blockHeaders[0]\n\t}\n\treturn ht, nil\n}", "func NewRoar(author string, text string) *Roar {\n return &Roar{Author: author, Text: text,\n CreationDate: time.LocalTime().Format(time.RFC1123)}\n}", "func NewHeadline(val string) HeadlineField {\n\treturn HeadlineField{quickfix.FIXString(val)}\n}", "func New(questionsPath string, textPath string) *Truman {\n\tt := &Truman{}\n\n\tquestionsFilePath, _ := filepath.Abs(questionsPath)\n\ttextFilePath, _ := filepath.Abs(textPath)\n\n\tt.loadQuestions(questionsFilePath)\n\tt.loadText(textFilePath)\n\n\treturn t\n}", "func newHeadView(res *Head) *salesviews.HeadView {\n\tvres := &salesviews.HeadView{\n\t\tID: &res.ID,\n\t\tName: &res.Name,\n\t}\n\treturn vres\n}", "func newTruck(mk, mdl string) *truck {\n\treturn &truck{vehicle: vehicle{mk, mdl}}\n}", "func NewHead(children ...Element) Element {\n\treturn newWithChildren(\"head\", children)\n}", "func NewHeadline() *Headline {\n\treturn &Headline{}\n}", "func New(IP, firstContact, ID string, OutputTo io.Writer) *RaftMember {\n\t//try to get the existing data from file\n\tos.Mkdir(\"/tmp/raft/\", 0777)\n\tR, PStore, success := readPersist()\n\t//build the stateMachine\n\tpwd := \"/tmp\"\n\tos.Mkdir(pwd+\"/machines\", 0777) //make the machines directory\n\n\tR.hrt = new(time.Timer) //initialize our timer.\n\tR.giveStatus = make(chan StatusBall)\n\tR.outputTo = OutputTo\n\tR.needStatus = make(chan bool)\n\tR.giveLog = make(chan string)\n\tR.needLog = make(chan bool)\n\tR.nextIndex = make(map[string]int)\n\tR.matchIndex = make(map[string]int)\n\tR.appendRequests = make(chan string, 100)\n\tR.needScoreBoard = make(chan bool)\n\tR.suspend = make(chan int)\n\tR.GiveScoreboard = make(chan map[string]int)\n\tif !success {\n\t\t//load failed or files dont exist\n\t\tfmt.Println(\"Creating New Member\")\n\t\ttid, err := makeID()\n\t\tR.VoteLog = append(R.VoteLog, VoteRecord{Votes: make(map[string]bool), VotedFor: \"NIL\"}) //bootstrap the vote record for the 0 term\n\t\tterr.BreakError(\"ID Creation\", err)\n\t\tR.ID = tid\n\t\tR.Log = append(R.Log, LogEntry{Term: 0, Entry: \"init\"}) // make the first entry an initialize for counting purposes.\n\t\tR.Target = 1\n\t}\n\tR.Machine = stateMachine.CreateStateMachine(pwd+\"/machines/\"+R.ID[:6]+\".sm\", contentionLevel) //build or recreate the state machine.\n\tterr.VerbPrint(R.outputTo, 1, verb, \"Target Set to:\", R.Target)\n\tR.Machine.SetTarget(R.Target) //restores a target after a reboot\n\tif ID != \"\" {\n\t\tR.ID = ID\n\t}\n\n\tR.CM = CM.New(R.ID, IP, R.outputTo)\n\tif firstContact != \"\" {\n\t\tterr.VerbPrint(R.outputTo, 3, verb, \"connecting to\", firstContact)\n\t\tR.Connect(firstContact)\n\t}\n\tR.writePersist(PStore)\n\tR.et = timers.NewElectionTimer()\n\tR.run(PStore) //spawns a go routine to handle incomming messages\n\treturn R\n}", "func NewMsgClaimHTLC(\n\tsender sdk.AccAddress,\n\thashLock []byte,\n\tsecret []byte,\n) MsgClaimHTLC {\n\treturn MsgClaimHTLC{\n\t\tSender: sender,\n\t\tHashLock: hashLock,\n\t\tSecret: secret,\n\t}\n}", "func NewHead(charset string, metas ...*Element) *Head {\n\th := new(Head)\n\th.Element = NewElement(\"head\")\n\tif charset != \"\" {\n\t\th.Charset = charset\n\t}\n\th.AddMetas(metas...)\n\treturn h\n}", "func NewChainHeadTracker(t mockConstructorTestingTNewChainHeadTracker) *ChainHeadTracker {\n\tmock := &ChainHeadTracker{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newPerson(name string,class string, nationality string ) *Person {\n\treturn &Person{name: name,job: class, nationality: nationality}\n\n}", "func NewMsgCreateHTLC(\n\tsender sdk.AccAddress,\n\tto sdk.AccAddress,\n\treceiverOnOtherChain string,\n\tamount sdk.Coins,\n\thashLock []byte,\n\ttimestamp uint64,\n\ttimeLock uint64,\n) MsgCreateHTLC {\n\treturn MsgCreateHTLC{\n\t\tSender: sender,\n\t\tTo: to,\n\t\tReceiverOnOtherChain: receiverOnOtherChain,\n\t\tAmount: amount,\n\t\tHashLock: hashLock,\n\t\tTimestamp: timestamp,\n\t\tTimeLock: timeLock,\n\t}\n}", "func NewMontrealTrip(weight float32, deadline int) *Trip {\n trip := Trip{weight: weight, destination: \"Montreal\", deadline: deadline}\n return &trip\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tpeer2Progress := make(map[uint64]*Progress, len(c.peers))\n\tpeer2Vote := make(map[uint64]bool, len(c.peers))\n\tfor _, s := range c.peers {\n\t\tpeer2Vote[s] = false\n\t\tpeer2Progress[s] = &Progress{0, 0}\n\t}\n\trand.Seed(time.Now().UnixNano())\n\thardState, _, _ := c.Storage.InitialState()\n\treturn &Raft{id: c.ID, Term: hardState.Term, Vote: hardState.Vote, RaftLog: newLog(c.Storage), State: StateFollower, Prs: peer2Progress, votes: peer2Vote, Lead: 0, heartbeatTimeout: c.HeartbeatTick, electionTimeout: c.ElectionTick, heartbeatElapsed: 0, electionElapsed: 0, actualElectionTimeout: 0}\n}", "func NewRaft(cfg *ServerConfig) *Raft {\n\treturn &Raft{\n\t\tServer: NewServer(cfg),\n\t\tLeaderID: NoLeader,\n\t}\n}", "func NewMothership(host, username, password, binary string, port int, notls, verifytls bool, env environment.Environment) (*Mothership, error) {\n\tm := &Mothership{Host: host, Port: port, NoTLS: notls, VerifyTLS: verifytls, Username: username, Password: password, Binary: binary}\n\n\t// Push the uplink to the mothership\n\tuplinkInfo, err := env.GetUplinkInfo()\n\tif err != nil {\n\t\treturn m, fmt.Errorf(\"error getting uplink info: %v\", err)\n\t}\n\tif err = m.pushUplink(uplinkInfo.FileName, uplinkInfo.Name); err != nil {\n\t\treturn m, fmt.Errorf(\"error pushing uplink %s: %v\", uplinkInfo.FileName, err)\n\t}\n\tm.uplinkFileName = uplinkInfo.FileName\n\tm.Alias = fmt.Sprintf(\"lotto-%s-%s\", env.Name(), m.Username)\n\tlogrus.Infof(\"Starbase alias to use: %s\", m.Alias)\n\n\t// lastCheckTime is used to know when the testing started\n\tm.lastCheckTime = time.Now()\n\treturn m, nil\n}", "func NewRaft(config *ClusterConfig, thisServerId int) (*Raft, error) {\n\tvar raft Raft\n\traft.Id = thisServerId\n\traft.ClusterConfigV = config\n\traft.Log = make([] LogEntry,0)\n\traft.VotedTerm=-1\n\traft.VotedFor=-1\n\traft.CurrentTerm=0\n\traft.IsLeader = 2\n\traft.NextIndex=make([] int,5)\n\traft.MatchIndex=make([] int,5)\n\traft.CommitIndex=-1\n\traft.LeaderId=-1\n\traft.LastApplied = -1 \n\tfilePath:=\"log_\"+strconv.Itoa(thisServerId)+\".txt\" // log file\n f, err := os.Create(filePath)\n if(err!=nil) {\n log.Fatal(\"Error creating log file:\",err)\n }\n raft.File = f\n\treturn &raft, nil\n}", "func New() (*TimeLord, error) {\n\tglobalMut.Lock()\n\tdefer globalMut.Unlock()\n\tif timeLordExists {\n\t\treturn nil, fmt.Errorf(\"timelord.New has already been called (only one TimeLord can be created at a time)\")\n\t}\n\ttl := &TimeLord{}\n\ttl.warp()\n\ttimeLordExists = true\n\treturn tl, nil\n}", "func NewLB(addr string) *LB {\n\treturn &LB{\n\t\tServer: &http.Server{\n\t\t\tAddr: addr,\n\t\t},\n\t\tlf: lockfree.New(),\n\t}\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// Your Code Here (2A).\n\tr := &Raft{\n\t\tid: c.ID,\n\t\tPrs: make(map[uint64]*Progress),\n\t\tvotes: make(map[uint64]bool),\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\tRaftLog: newLog(c.Storage),\n\t}\n\thardSt, confSt, _ := r.RaftLog.storage.InitialState()\n\tif c.peers == nil {\n\t\tc.peers = confSt.Nodes\n\t}\n\tlastIndex := r.RaftLog.LastIndex()\n\tfor _, peer := range c.peers {\n\t\tif peer == r.id {\n\t\t\tr.Prs[peer] = &Progress{Next: lastIndex + 1, Match: lastIndex}\n\t\t} else {\n\t\t\tr.Prs[peer] = &Progress{Next: lastIndex + 1}\n\t\t}\n\t}\n\tr.becomeFollower(0, None)\n\tr.randomElectionTimeout = r.electionTimeout + rand.Intn(r.electionTimeout)\n\tr.Term, r.Vote, r.RaftLog.committed = hardSt.GetTerm(), hardSt.GetVote(), hardSt.GetCommit()\n\tif c.Applied > 0 {\n\t\tr.RaftLog.applied = c.Applied\n\t}\n\treturn r\n}", "func NewHeadBook(ds ds.TxnDatastore) core.HeadBook {\n\treturn &dsHeadBook{\n\t\tds: ds,\n\t}\n}", "func LABLMake() Chunk { return LABL() }", "func (m *Manager) NewTXT(name string, content string) (*cf.DNSRecord, error) {\n\tres, err := m.api.CreateDNSRecord(m.zoneID, cf.DNSRecord{\n\t\tType: \"TXT\",\n\t\tName: name,\n\t\tContent: content,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debugf(\"created TXT record %s -> %s\", name, content)\n\treturn &res.Result, nil\n}", "func newThread(writer http.ResponseWriter, request *http.Requet) {\n\t_, err := session(writer, request)\n\tif err != nil {\n\t\thttp.Redirect(writer, request, \"/login\", 302)\n\t} else {\n\t\tgenerateHTML(writer, nil, \"layout\", \"private.navbar\", \"new.thread\")\n\t}\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\ts := c.Storage\n\thardStatus, confStatus, err := s.InitialState()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tif c.peers == nil {\n\t\tc.peers = confStatus.Nodes\n\t}\n\n\tnodes := c.peers\n\t// init vote to false\n\tvotes := make(map[uint64]bool)\n\tfor _, nodeId := range nodes {\n\t\tvotes[nodeId] = false\n\t}\n\n\treturn &Raft{\n\t\tid: c.ID,\n\t\tTerm: hardStatus.Commit,\n\t\tVote: hardStatus.Vote,\n\t\tRaftLog: newLog(c.Storage),\n\t\tPrs: nil,\n\t\t// init as a follower\n\t\tState: StateFollower,\n\t\tvotes: nil,\n\t\tmsgs: nil,\n\t\tLead: None,\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\trandomElectionTimeout: randomTimeout(c.ElectionTick),\n\t\theartbeatElapsed: 0,\n\t\telectionElapsed: 0,\n\t\tleadTransferee: 0,\n\t\tPendingConfIndex: 0,\n\t\tnodes: nodes,\n\t}\n}", "func NewLLCtor() *Node {\n\t//empty node is created, small memory allocated.\n\treturn new(Node)\n}", "func (fbo *folderBranchOps) setNewInitialHeadLocked(ctx context.Context,\n\tlState *kbfssync.LockState, md ImmutableRootMetadata) error {\n\tfbo.mdWriterLock.AssertLocked(lState)\n\tfbo.headLock.AssertLocked(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\treturn errors.New(\"Unexpected non-nil head in setNewInitialHeadLocked\")\n\t}\n\tif md.Revision() != kbfsmd.RevisionInitial {\n\t\treturn errors.Errorf(\"setNewInitialHeadLocked unexpectedly called with revision %d\", md.Revision())\n\t}\n\treturn fbo.setHeadLocked(ctx, lState, md, headTrusted, mdToCommitType(md))\n}", "func (k *Keybase) NewTeam(name string) Team {\n\treturn Team{\n\t\tkeybase: k,\n\t\tName: name,\n\t}\n}", "func (llrb *LLRB) Clone(name string) *LLRB {\n\tif !llrb.lock() {\n\t\treturn nil\n\t}\n\n\tnewllrb := NewLLRB(llrb.name, llrb.setts)\n\tnewllrb.llrbstats = llrb.llrbstats\n\tnewllrb.h_upsertdepth = llrb.h_upsertdepth.Clone()\n\tnewllrb.seqno = llrb.seqno\n\n\tnewllrb.setroot(newllrb.clonetree(llrb.getroot()))\n\n\tllrb.unlock()\n\treturn newllrb\n}", "func newRaftLayer(addr string, ln net.Listener) *raftLayer {\n\treturn &raftLayer{\n\t\taddr: &raftLayerAddr{addr},\n\t\tln: ln,\n\t\tconn: make(chan net.Conn),\n\t\tclosed: make(chan struct{}),\n\t}\n}", "func NewCARBODY(config configuration_pkg.CONFIGURATION) *CARBODY_IMPL {\r\n client := new(CARBODY_IMPL)\r\n client.config = config\r\n return client\r\n}", "func NewHeadTracker(store *strpkg.Store, callbacks []strpkg.HeadTrackable, sleepers ...utils.Sleeper) *HeadTracker {\n\tvar sleeper utils.Sleeper\n\tif len(sleepers) > 0 {\n\t\tsleeper = sleepers[0]\n\t} else {\n\t\tsleeper = utils.NewBackoffSleeper()\n\t}\n\treturn &HeadTracker{\n\t\tstore: store,\n\t\tcallbacks: callbacks,\n\t\tsleeper: sleeper,\n\t}\n}", "func (st *fakeConn) NewLeaderParticipation(name, id string) (mp LeaderParticipation, err error) {\n\tif name == \"error\" {\n\t\treturn mp, fmt.Errorf(\"dummy error\")\n\n\t}\n\treturn mp, err\n}", "func NewRHT() *RHT {\n\treturn &RHT{\n\t\telementQueueMapByKey: make(map[string]*PriorityQueue),\n\t\titemMapByCreatedAt: make(map[string]*PQItem),\n\t}\n}", "func newBook(r CreateRequest) *book.Book {\n\tb := new(book.Book)\n\tb.ID = db.NextID()\n\tb.Author = r.Author\n\tb.Title = r.Title\n\treturn b\n}", "func NewPerson(first string, last string) *Person {\n return &Person{FirstName:first, LastName:last}\n}", "func NewMesh(db *DB, atxDb AtxDB, rewardConfig Config, trtl tortoise, txPool txMemPool, pr txProcessor, logger log.Log) *Mesh {\n\tmsh := &Mesh{\n\t\tLog: logger,\n\t\ttrtl: trtl,\n\t\ttxPool: txPool,\n\t\ttxProcessor: pr,\n\t\tdone: make(chan struct{}),\n\t\tDB: db,\n\t\tconfig: rewardConfig,\n\t\tAtxDB: atxDb,\n\t\tnextProcessedLayers: make(map[types.LayerID]struct{}),\n\t\tnextValidLayers: make(map[types.LayerID]*types.Layer),\n\t\tlatestLayer: types.GetEffectiveGenesis(),\n\t\tlatestLayerInState: types.GetEffectiveGenesis(),\n\t}\n\n\tmsh.Validator = &validator{Mesh: msh}\n\tgLyr := types.GetEffectiveGenesis()\n\tfor i := types.NewLayerID(1); i.Before(gLyr); i = i.Add(1) {\n\t\tif err := msh.SetZeroBlockLayer(i); err != nil {\n\t\t\tmsh.With().Panic(\"failed to set zero-block for genesis layer\", i, log.Err(err))\n\t\t}\n\t}\n\tif err := msh.persistLayerHashes(context.Background(), types.NewLayerID(1), gLyr); err != nil {\n\t\tmsh.With().Panic(\"failed to persist hashes for genesis layers\", log.Err(err))\n\t}\n\treturn msh\n}", "func New(ctx context.Context, clientset client.Clientset, opts Opts) (*MetalLBSpeaker, error) {\n\tctrl, err := newMetalLBSpeaker(ctx, clientset)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tspkr := &MetalLBSpeaker{\n\t\tFencer: fence.Fencer{},\n\t\tspeaker: ctrl,\n\n\t\tannounceLBIP: opts.LoadBalancerIP,\n\t\tannouncePodCIDR: opts.PodCIDR,\n\n\t\tqueue: workqueue.New(),\n\n\t\tservices: make(map[k8s.ServiceID]*slim_corev1.Service),\n\t}\n\n\tgo spkr.run(ctx)\n\n\tlog.Info(\"Started BGP speaker\")\n\n\treturn spkr, nil\n}", "func New(w http.ResponseWriter, r *http.Request) {\n\tgetTemplates().ExecuteTemplate(w, \"New\", nil)\n}", "func NewMsgRefundHTLC(\n\tsender sdk.AccAddress,\n\thashLock []byte,\n) MsgRefundHTLC {\n\treturn MsgRefundHTLC{\n\t\tSender: sender,\n\t\tHashLock: hashLock,\n\t}\n}", "func (c Threads) New(topic string) revel.Result {\n // Validate\n c.Validation.Required(topic)\n c.Validation.MinSize(topic, 3)\n\n if c.Validation.HasErrors() {\n c.Validation.Keep()\n c.FlashParams()\n return c.Redirect(Threads.ShowNew)\n }\n\n // Create thread\n user := c.connected()\n thread := &models.Thread{\n 0,\n 0,\n topic,\n \"\",\n user,\n time.Now(),\n }\n err := c.Txn.Insert(thread)\n if err != nil {\n c.Flash.Error(\"An error occurred, sorry\")\n fmt.Println(err)\n }\n\n return c.Redirect(\"/threads/%d\", thread.ThreadId)\n}", "func New(w http.ResponseWriter, r *http.Request) {\r\n\ttmpl.ExecuteTemplate(w, \"New\", nil)\r\n}", "func New(w http.ResponseWriter, r *http.Request) {\r\n\ttmpl.ExecuteTemplate(w, \"New\", nil)\r\n}", "func (fbo *folderBranchOps) SetInitialHeadToNew(\n\tctx context.Context, id tlf.ID, handle *tlfhandle.Handle) (err error) {\n\tstartTime, timer := fbo.startOp(ctx, \"SetInitialHeadToNew %s\", id)\n\tdefer func() {\n\t\tfbo.endOp(\n\t\t\tctx, startTime, timer, \"SetInitialHeadToNew %s done: %+v\", id, err)\n\t}()\n\n\trmd, err := makeInitialRootMetadata(\n\t\tfbo.config.MetadataVersion(), id, handle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn runUnlessCanceled(ctx, func() error {\n\t\t// New heads can only be set for the MasterBranch.\n\t\tfb := data.FolderBranch{Tlf: rmd.TlfID(), Branch: data.MasterBranch}\n\t\tif fb != fbo.folderBranch {\n\t\t\treturn WrongOpsError{fbo.folderBranch, fb}\n\t\t}\n\n\t\t// Always identify first when trying to initialize the folder,\n\t\t// even if we turn out not to be a writer. (We can't rely on\n\t\t// the identifyOnce call in getMDLocked, because that isn't\n\t\t// called from the initialization code path when the local\n\t\t// user is not a valid writer.) Also, we want to make sure we\n\t\t// fail before we set the head, otherwise future calls will\n\t\t// succeed incorrectly.\n\t\terr = fbo.identifyOnce(ctx, rmd.ReadOnly())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlState := makeFBOLockState()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\treturn fbo.initMDLocked(ctx, lState, rmd)\n\t})\n}", "func createLeafNode(data fmt.Stringer) *MerkleNode {\n\tnode := new(MerkleNode)\n\tnode.data = data\n\tnode.hash = node.calcNodeHash()\n\n\treturn node\n}", "func NewProtocol(action string, hID int64, note string) Protocol {\n\treturn Protocol{\n\t\tTime: time.Now(),\n\t\tAction: action,\n\t\tHeroID: hID,\n\t\tNote: note,\n\t}\n}", "func NewLeaf(data []byte, h hash.Hash) *MerkleTree {\n\tif h == nil {\n\t\th = sha256.New()\n\t}\n\n\tmt := &MerkleTree{\n\t\tnil, nil, h, nil,\n\t}\n\n\tmt.Hash(data)\n\treturn mt\n}", "func NewClientLMTP(conn net.Conn, host string) (*Client, error) {\n\tc, err := NewClient(conn, host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.lmtp = true\n\treturn c, nil\n}", "func NewToml(path string) (Toml, error) {\n\ttoml := Toml{\n\t\tpath: path,\n\t}\n\n\terr := toml.readFile()\n\tif err != nil {\n\t\treturn toml, err\n\t}\n\n\terr = toml.load()\n\tif err != nil {\n\t\treturn toml, err\n\t}\n\n\treturn toml, nil\n}", "func New(hash hash.Hash, data [][]byte) *MerkleTree {\n\tvar n int\n\n\tif data == nil || len(data) == 0 {\n\t\treturn nil\n\t}\n\tif n = len(data); n == 0 {\n\t\treturn nil\n\t}\n\tr := &MerkleTree{\n\t\thash: hash,\n\t}\n\tr.tree = r.mkMerkleTreeRoot(n, data)\n\treturn r\n}", "func NewRaft(config *ClusterConfig, thisServerId int, commitCh chan raft.LogEntry) (*Raft, error) {\n\traft := new(Raft)\n\traft.Init(config, thisServerId)\n\treturn raft, nil\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func (r *MockRepoManager) CreateNewRoll(ctx context.Context, from, to string, emails []string, cqExtraTrybots string, dryRun bool) (int64, error) {\n\tr.mtx.RLock()\n\tdefer r.mtx.RUnlock()\n\treturn r.mockIssueNumber, nil\n}", "func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *rpcHeader) (ethereum.Subscription, error) {\n\treturn ec.c.EthSubscribe(ctx, ch, \"newHeads\")\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func (l *listener) NewLeader(id string) {\n\tlog.Printf(\"[INFO] %s: new leader: %s\", hostname(), id)\n}", "func NewRulerBuilder(e e2e.Environment, name string) *RulerBuilder {\n\tf := e.Runnable(fmt.Sprintf(\"rule-%s\", name)).\n\t\tWithPorts(map[string]int{\"http\": 8080, \"grpc\": 9091}).\n\t\tFuture()\n\treturn &RulerBuilder{\n\t\treplicaLabel: name,\n\t\tLinkable: f,\n\t\tf: f,\n\t\timage: DefaultImage(),\n\t}\n}", "func (l *LNCChallenger) NewChallenge(price int64) (string, lntypes.Hash,\n\terror) {\n\n\treturn l.lndChallenger.NewChallenge(price)\n}", "func NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}", "func NewLuaObjectFromName(L *lua.State, path string) *LuaObject {\n Lookup(L, path, 0)\n return NewLuaObject(L, -1)\n}", "func NewUserTeamwork()(*UserTeamwork) {\n m := &UserTeamwork{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewMocklibrarian(t mockConstructorTestingTNewMocklibrarian) *Mocklibrarian {\n\tmock := &Mocklibrarian{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New(genesisHeader util.BlockHeader, db database.ChainStore) (*BlockChain, error) {\n\t// Init genesis header\n\t_, err := db.Headers().GetBest()\n\tif err != nil {\n\t\tstoreHeader := &util.Header{BlockHeader: genesisHeader, TotalWork: new(big.Int)}\n\t\tif err := db.Headers().Put(storeHeader, true); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &BlockChain{db: db}, nil\n}", "func New(repoRoot string, blockchainStore storage.Storage, logger logrus.FieldLogger) (*ChainLedger, error) {\n\tldb, err := leveldb.New(repo.GetStoragePath(repoRoot, \"ledger\"))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"create tm-leveldb: %w\", err)\n\t}\n\n\tchainMeta, err := loadChainMeta(blockchainStore)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"load chain meta: %w\", err)\n\t}\n\n\theight, blockJournal, err := getLatestJournal(ldb)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"get journal height: %w\", err)\n\t}\n\n\tif height < chainMeta.Height {\n\t\t// TODO(xcc): how to handle this case\n\t\tpanic(\"state tree height is less than blockchain height\")\n\t}\n\n\treturn &ChainLedger{\n\t\tlogger: logger,\n\t\tchainMeta: chainMeta,\n\t\tblockchainStore: blockchainStore,\n\t\tldb: ldb,\n\t\theight: height,\n\t\tevents: make(map[string][]*pb.Event, 10),\n\t\taccounts: make(map[string]*Account),\n\t\tprevJournalHash: blockJournal.ChangedHash,\n\t}, nil\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func (env *env) newTestHelperCreateLgr(id string, t *testing.T) *testhelper {\n\tgenesisBlk, err := constructTestGenesisBlock(id)\n\tassert.NoError(t, err)\n\tlgr, err := env.ledgerMgr.CreateLedger(id, genesisBlk)\n\tassert.NoError(t, err)\n\tclient, committer, verifier := newClient(lgr, id, t), newCommitter(lgr, t), newVerifier(lgr, t)\n\treturn &testhelper{client, committer, verifier, lgr, id, assert.New(t)}\n}", "func newPerson(name string, age int) *Person {\n\tnewperson := Person{name: name, age: age}\n\treturn &newperson\n}", "func NewNode(e string) *LNode {\n\treturn &LNode{\n\t\tE: e,\n\t}\n}", "func NewHeader(t, subject, issuer string) (*ClaimHeader, string, error) {\n\tch := &ClaimHeader{\n\t\tType: t,\n\t\tSubject: subject,\n\t\tIssuer: issuer,\n\t}\n\treturn ch, ch.ID(), ch.Set()\n}", "func newTurtle(bdp blockDataProvider, hdist, avgLayerSize int) *turtle {\n\tt := &turtle{\n\t\tlogger: log.NewDefault(\"trtl\"),\n\t\tHdist: types.LayerID(hdist),\n\t\tbdp: bdp,\n\t\tLast: 0,\n\t\tAvgLayerSize: avgLayerSize,\n\t\tGoodBlocksIndex: make(map[types.BlockID]struct{}),\n\t\tBlocksToBlocks: make(map[types.LayerID]map[types.BlockID]Opinion, hdist),\n\t\tBlocksToBlocksIndex: make(map[types.BlockID]int),\n\t\tMaxExceptions: hdist * avgLayerSize * 100,\n\t}\n\treturn t\n}", "func New(lms chan mysignals.LifeSignal) *Person {\n\t// create new Person\n\tp := Person{\n\t\tid: newPersonID(),\n\t\tage: Age{\n\t\t\tvalue: 15,\n\t\t\tlock: sync.Mutex{},\n\t\t\tmaxage: 40,\n\t\t},\n\t\tsmartphone: smartphone.New(),\n\t\tlifemsgs: lms,\n\t\tengaged: engaged{\n\t\t\tvalue: false,\n\t\t\tlock: sync.Mutex{},\n\t\t},\n\t\t// use &brain.Brain{}\n\t\t// instead of brain.Brain{}\n\t\t// because Brain implements the interface DecisionMaker{} using a pointer receiver\n\t\t// \t\t\t(b* Brain)Method(...)\n\t\t// instead of a value receiver\n\t\t// \t\t\t(b Brain)Method(...)\n\t\tbrain: &brain.Brain{},\n\t\t// sex is M or F\n\t\tsex: func() byte {\n\t\t\tif utils.NewRandomIntInRange(0, 1) == 0 {\n\t\t\t\treturn 'M'\n\t\t\t}\n\t\t\treturn 'F'\n\t\t}(),\n\t}\n\t// start listening for signals\n\tgo (&p).listenForSignals()\n\t// return Person information\n\treturn &p\n}", "func NewLocalLedger() *LocalLedger {\n\tlog.Printf(\"BLURB-LEDGER: Initializing\")\n\treturn &LocalLedger{\n\t\tledger: sync.Map{},\n\t\tbidCounter: 0,\n\t\tbidMutex: sync.Mutex{},\n\n\t\tfeeds: struct {\n\t\t\tcache sync.Map\n\t\t\tlength int\n\t\t\tblurbsPerUser int\n\t\t}{\n\t\t\tcache: sync.Map{},\n\t\t\tlength: 100,\n\t\t\tblurbsPerUser: 10,\n\t\t},\n\t}\n}", "func newTPMManagerBinary(r CmdRunner) *tpmManagerBinary {\n\treturn &tpmManagerBinary{r}\n}", "func NewEncodedHeadline(val string) EncodedHeadlineField {\n\treturn EncodedHeadlineField{quickfix.FIXString(val)}\n}", "func NewHeaders()(*Headers) {\n m := &Headers{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewLittr(fileName, filePath, flags string, timeout time.Duration) (*littr, error) {\n\tb, err := ioutil.ReadFile(\"../../data/timer.txt\")\n\tif err != nil {\n\t\treturn &littr{}, fmt.Errorf(\"file not found\")\n\t}\n\n\treturn &littr{\n\t\tfileName: fileName,\n\t\tfilePath: filePath,\n\t\tflags: flags,\n\t\ttimerDef: string(b),\n\t\terrorCh: make(chan error, 1),\n\t\ttimeout: timeout,\n\t}, nil\n}", "func CreateHead(samples []*MetricSample, chunkRange int64, logger log.Logger) (*Head, error) {\n\thead, err := NewHead(nil, logger, nil, chunkRange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapp := head.Appender()\n\tfor _, sample := range samples {\n\t\t_, err = app.Add(sample.Labels, sample.TimestampMs, sample.Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\terr = app.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn head, nil\n}", "func newNode(hash string) Node {\n\treturn Node{hash: hash, parent: nil}\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\t/// Start as a follower.\n\trf.currentState = \"FOLLOWER\"\n\trf.commitIndex=1\n\trf.lastApplied=1 // Initializing this to 1 as we have added dummy 0th entry\n\trf.votedFor=-1\n\t//05/12\n\t//Let the leader start with 0. When a candidate transitions to the candidate state it increments this value.\n\trf.currentTerm=0\n\t//Initialize the log.\n\t//This is a dummy entry\n\trf.log = append(rf.log, LogEntry{LastLogTerm: 0})\n\trf.applyCh = applyCh\n\trf.debug(\"++++++++++++++++++++++++++Length of the log during initialization---> %d \\n\",len(rf.log))\n\trf.electionTimer = time.NewTimer((400 + time.Duration(rand.Intn(300))) * time.Millisecond)\n\t// Your initialization code here (2A, 2B, 2C).\n\tgo rf.conductElection()\n\t//Send heart beat to everybody else\n\treturn rf\n}", "func BBMake(l, t, r, b Float) (BB) { \n return BB{L: l, B: b, R: r, T: t}\n}", "func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (siotchain.Subscription, error) {\n\treturn ec.c.SiotSubscribe(ctx, ch, \"newHeads\", map[string]struct{}{})\n}", "func (rc *RelayController) SetNewHeader(header *types.Header) {\n\tif header.Relayer == nil {\n\t\treturn\n\t}\n\n\tif header.Relayer.Address == rc.currentNodeAddress {\n\t\trc.logger.Debug(\"RELAY SetNewHeader\", \"rc.startRelay()\")\n\t\trc.startRelay()\n\t} else {\n\t\trc.logger.Debug(\"RELAY SetNewHeader\", \"rc.stopRelay()\",\n\t\t\tfmt.Sprintf(\"expcted: %s obtain: %s\", header.Relayer.Address, rc.currentNodeAddress))\n\t\trc.stopRelay()\n\t}\n}", "func (t *BPTree) newLeaf() *Node {\n\tleaf := t.newNode()\n\tleaf.isLeaf = true\n\treturn leaf\n}", "func NewRoutingTable(me Contact) *RoutingTable {\n\troutingTable := &RoutingTable{}\n\tfor i := 0; i < IDLength*8; i++ {\n\t\troutingTable.buckets[i] = newBucket()\n\t}\n\troutingTable.me = me\n\treturn routingTable\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func (t *MCTS) New(move int32, score float32) (retVal Naughty) {\n\tn := t.alloc()\n\tN := t.nodeFromNaughty(n)\n\tN.lock.Lock()\n\tdefer N.lock.Unlock()\n\tN.move = move\n\tN.visits = 1\n\tN.status = uint32(Active)\n\tN.qsa = 0\n\tN.psa = score\n\n\treturn n\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\t// Your initialization code here (2A, 2B, 2C).\n\trf.applyCh = applyCh\n\trf.candidateId = me\n\trf.votedFor = NILVOTE \n\trf.role = FOLLOWER\n\trf.currentTerm = 0\n\trf.resetTimeoutEvent = makeTimestamp()\n\trf.commitIndex = 0\n\trf.lastApplied = 0\n\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tif(len(rf.log) == 0) {\n\t\tentry := Entry {0, nil, 0}\n\t\trf.log = append(rf.log, entry)\n\t\trf.persist()\n\t}\n\n\tAssert(len(rf.log) >= 1, \"raft log not bigger than 0\")\n\n\trf.nextIndex = make([]int, len(rf.peers))\n\trf.matchIndex = make([]int, len(rf.peers))\n\n\t// start ticker goroutine to start elections\n\tgo rf.ticker()\n\n\t// have the leader send heartbeats out periodically\n\tgo rf.sendHeartbeats()\n\treturn rf\n}", "func NewTTFB(domain string, private bool) (*TTFB, error) {\n\tvar tester TTFB\n\n\tif domain == \"\" {\n\t\treturn nil, errors.New(\"Domain is invalid\")\n\t}\n\n\ttester.Domain = domain /* track domain name */\n\ttester.Private = private /* hide results from public */\n\ttester.Servers = make(map[string]string)\n\n\tif err := tester.LoadServers(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tester, nil\n}", "func new_job(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Handling connection...\")\n\n\t// Parse the HTTP request.\n\tif err := req.ParseForm(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Put the bytes from the request into a file\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(req.Body)\n\tjobJson := buf.String()\n\n\t// Convert string json to job struct\n\tjob := data.JsonToJob([]byte(jobJson))\n\n\tvar num *int = nil\n\n\tif job.ParameterEnd >= job.ParameterStart {\n\t\tnum = &job.ParameterStart\n\t}\n\n\tvar args []string\n\tif job.Args[0] != \"NONE\" {\n\t\targs = job.Args\n\t}\n\n\t// Run the code and get []byte output\n\toutput := runCode(job.Extension, job.Code, job.FileName, num, args)\n\n\t// Send a response back.\n\tw.Write(output)\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.commitIndex = -1\n\trf.lastApplied = -1\n\trf.leaderId = -1\n\n\tfor i := 0; i < len(peers); i++ {\n\t\trf.nextIndex = append(rf.nextIndex, -1)\n\t\trf.matchIndex = append(rf.matchIndex, -1)\n\t}\n\n\trf.role = FOLLOWER\n\tgo rf.electionTimer()\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\treturn rf\n}", "func NewProtocol(bc blockchain.Blockchain) *Protocol { return &Protocol{bc} }", "func New(opts ...Option) *HLTB {\n\th := &HLTB{}\n\n\tfor _, opt := range opts {\n\t\topt(h)\n\t}\n\n\treturn h\n}", "func NewTrace(lfn string, site string, ts int64, jobtype string, wnname string) Trace {\n\ttrc := Trace{}\n\ttrc.Account = \"fwjr\"\n\ttrc.ClientState = \"DONE\"\n\ttrc.Filename = lfn\n\ttrc.DID = \"cms:\" + fmt.Sprintf(\"%v\", trc.Filename)\n\ttrc.EventType = \"get\"\n\ttrc.EventVersion = \"API_1.21.6\"\n\ttrc.FileReadts = ts\n\ttrc.Jobtype = jobtype\n\ttrc.RemoteSite = site\n\ttrc.Scope = \"cms\"\n\ttrc.Timestamp = trc.FileReadts\n\ttrc.TraceTimeentryUnix = trc.FileReadts\n\ttrc.Usrdn = \"/DC=ch/DC=cern/OU=Organic Units/OU=Users/CN=yuyi/CN=639751/CN=Yuyi Guo/CN=706639693\"\n\ttrc.Wnname = wnname\n\treturn trc\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\trf.logger = log.New(GetLoggerWriter(), fmt.Sprintf(\"[Node %v] \", me), log.LstdFlags)\n\n\t// Your initialization code here.\n\trf.state = FOLLOWER\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.logs = make([]interface{}, 0)\n\trf.logs_term = make([]int, 0)\n\trf.commitCount = 0\n\trf.appliedCount = 0\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchCount = make([]int, len(peers))\n\trf.applyCh = applyCh\n\n\t// initialize from state persisted before a crash\n\trf.readPersist()\n\trf.resetTimer()\n\n\treturn rf\n}" ]
[ "0.6216581", "0.5670481", "0.55518067", "0.5520945", "0.540021", "0.524219", "0.51972264", "0.51203287", "0.510461", "0.50970316", "0.5024263", "0.50216347", "0.5017086", "0.5012589", "0.49524257", "0.4937669", "0.49000117", "0.4897512", "0.48824078", "0.4841005", "0.4789799", "0.4731525", "0.4721301", "0.46708137", "0.46452487", "0.46424526", "0.4612967", "0.45987737", "0.4598298", "0.45840794", "0.45682156", "0.45325413", "0.45308998", "0.45286858", "0.45262098", "0.45250311", "0.4521736", "0.4520959", "0.45140517", "0.45008028", "0.44999024", "0.44913775", "0.44775912", "0.4476553", "0.44622287", "0.44561553", "0.4453057", "0.44526708", "0.44526708", "0.44458318", "0.44405", "0.4436107", "0.44289356", "0.44053492", "0.44046628", "0.43921345", "0.4385465", "0.4383842", "0.43824843", "0.43806395", "0.43777204", "0.43746468", "0.43727133", "0.43681487", "0.43669462", "0.4357543", "0.43557057", "0.43552813", "0.43443894", "0.43440884", "0.43434176", "0.43380168", "0.4334905", "0.43330768", "0.43326735", "0.43323243", "0.43301326", "0.43295792", "0.43237242", "0.43202376", "0.4319413", "0.4319079", "0.4317838", "0.43124753", "0.43122566", "0.43078953", "0.4305037", "0.4304758", "0.43036836", "0.4301937", "0.42962977", "0.42953497", "0.4291398", "0.42889246", "0.42875758", "0.42851084", "0.428449", "0.4283921", "0.42823294", "0.42817104" ]
0.76238585
0
Foward forwards pass through RobertaLMHead model.
func (rh *RobertaLMHead) Forward(hiddenStates *ts.Tensor) *ts.Tensor { gelu := util.NewGelu() appliedDense := hiddenStates.Apply(rh.dense) geluFwd := gelu.Fwd(appliedDense) appliedLN := geluFwd.Apply(rh.layerNorm) appliedDecoder := appliedLN.Apply(rh.decoder) appliedBias := appliedDecoder.MustAdd(rh.bias, true) geluFwd.MustDrop() appliedDense.MustDrop() appliedLN.MustDrop() return appliedBias }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train)\n\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tpredictionScores := mlm.lmHead.Forward(hiddenState)\n\n\treturn predictionScores, allHiddenStates, allAttentions, nil\n}", "func (obj *Doc) Forward(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"Forward\", nil)\n\treturn err\n}", "func (mod *backendModule) Forward(f *gatepb.Forward) error {\n\treturn mod.send(proto.Type(f.Typ), f)\n}", "func (s *Service) forwardToLeader(w http.ResponseWriter, req *http.Request) {\n\turl, err := url.Parse(s.RaftConfig.RaftNodeConfig.NodeProtocol + req.RequestURI)\n\tif err != nil {\n\t\tpanic(\"parse leader host url failed: \" + err.Error())\n\t}\n\turl.Host = s.raftNode.GetLeaderHost()\n\n\t// without leader, then return special error\n\tif url.Host == \"\" {\n\t\trpc.ReplyErr(w, apierrors.CodeNoLeader, apierrors.ErrNoLeader.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"forward url: %v\", url)\n\n\tproxy := httpproxy.ReverseProxy{\n\t\tDirector: func(request *http.Request) {\n\t\t\trequest.URL = url\n\t\t},\n\t}\n\n\tproxy.ServeHTTP(w, req)\n}", "func (q *CQPU) forward(predicate []*pbUtils.AttributePredicate, streamRec *pbQPU.ResponseStreamRecord, streamOut pbQPU.QPU_QueryServer, seqID *int64, respond bool) error {\n\tif respond {\n\t\terr := streamOut.Send(\n\t\t\tprotoutils.ResponseStreamRecord(\n\t\t\t\t*seqID,\n\t\t\t\tstreamRec.GetType(),\n\t\t\t\tstreamRec.GetLogOp(),\n\t\t\t))\n\t\t(*seqID)++\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Model) Forward(x *Node, states States) (rv *Node, err error) {\n\trv = x\n\tfor _, l := range m.Layers {\n\t\tif rv, err = l.Forward(rv, states); err != nil {\n\t\t\treturn nil, errors.Wrap(err, l.Name())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func (g *game) forward() {\n\tg.player.Parse(g.input)\n\n\tif g.player.IsQuitting() {\n\t\tg.next = g.newMenu()\n\t}\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\th := nn.Affine(g, m.B, m.W, x)\n\tif yPrev != nil {\n\t\th = g.Add(h, g.Prod(m.WRec, yPrev))\n\t}\n\ts.Y = g.Invoke(m.Activation, h)\n\treturn\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func (b *BaseController) Forward(title, templateName string) {\n\tb.Layout = filepath.Join(prefixNg, \"layout.htm\")\n\tb.TplName = filepath.Join(prefixNg, templateName)\n\tb.Data[\"Title\"] = b.Tr(title)\n\tb.LayoutSections = make(map[string]string)\n\tb.LayoutSections[\"HeaderInclude\"] = filepath.Join(prefixNg, viewPath, \"header-include.htm\")\n\n\tif b.UseCompressedJS {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-min-include.htm\")\n\t} else {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-include.htm\")\n\t}\n\n\tlog.Debugf(\"Loaded HeaderScriptInclude file: %s\", b.LayoutSections[\"HeaderScriptInclude\"])\n\n\tb.LayoutSections[\"FooterInclude\"] = filepath.Join(prefixNg, viewPath, \"footer-include.htm\")\n\tb.LayoutSections[\"HeaderContent\"] = filepath.Join(prefixNg, viewPath, \"header-content.htm\")\n\tb.LayoutSections[\"FooterContent\"] = filepath.Join(prefixNg, viewPath, \"footer-content.htm\")\n\n}", "func (ms *MVCCStats) Forward(nowNanos int64) {\n\tif ms.LastUpdateNanos >= nowNanos {\n\t\treturn\n\t}\n\tms.AgeTo(nowNanos)\n}", "func (inst *instance) Forward(port int) (string, error) {\n\tvar reply proxyrpc.ForwardResult\n\terr := inst.ProxyApp.Call(\n\t\t\"ProxyVM.Forward\",\n\t\tproxyrpc.ForwardParams{\n\t\t\tID: inst.ID,\n\t\t\tPort: port,\n\t\t},\n\t\t&reply)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reply.ManagerAddress, nil\n}", "func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Ensure our request client does not follow redirects\n\thttpClient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tif config.TLS != nil {\n\t\ttlsConfig, err := config.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\ttracing.SetErrorAndDebugLog(r, \"Unable to configure TLS to call %s. Cause %s\", config.Address, err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(http.MethodGet, config.Address, http.NoBody)\n\ttracing.LogRequest(tracing.GetSpan(r), forwardReq)\n\tif err != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause %s\", config.Address, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteHeader(r, forwardReq, config.TrustForwardHeader)\n\n\ttracing.InjectRequestHeaders(forwardReq)\n\n\tforwardResponse, forwardErr := httpClient.Do(forwardReq)\n\tif forwardErr != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause: %s\", config.Address, forwardErr)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbody, readError := ioutil.ReadAll(forwardResponse.Body)\n\tif readError != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error reading body %s. Cause: %s\", config.Address, readError)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer forwardResponse.Body.Close()\n\n\t// Pass the forward response's body and selected headers if it\n\t// didn't return a response within the range of [200, 300).\n\tif forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {\n\t\tlog.Debugf(\"Remote error %s. StatusCode: %d\", config.Address, forwardResponse.StatusCode)\n\n\t\tutils.CopyHeaders(w.Header(), forwardResponse.Header)\n\t\tutils.RemoveHeaders(w.Header(), forward.HopHeaders...)\n\n\t\t// Grab the location header, if any.\n\t\tredirectURL, err := forwardResponse.Location()\n\n\t\tif err != nil {\n\t\t\tif err != http.ErrNoLocation {\n\t\t\t\ttracing.SetErrorAndDebugLog(r, \"Error reading response location header %s. Cause: %s\", config.Address, err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if redirectURL.String() != \"\" {\n\t\t\t// Set the location in our response if one was sent back.\n\t\t\tw.Header().Set(\"Location\", redirectURL.String())\n\t\t}\n\n\t\ttracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)\n\t\tw.WriteHeader(forwardResponse.StatusCode)\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tfor _, headerName := range config.AuthResponseHeaders {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tr.Header.Del(headerKey)\n\t\tif len(forwardResponse.Header[headerKey]) > 0 {\n\t\t\tr.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)\n\t\t}\n\t}\n\n\tr.RequestURI = r.URL.RequestURI()\n\tnext(w, r)\n}", "func (m *Model) Forward(qkv attention.QKV) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: m.Key.Forward(qkv.Keys...),\n\t\tValues: m.Value.Forward(qkv.Values...),\n\t}\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (a *insertApp) forward(app *App, args ...interface{}) error {\n\tapp.State = \"pending\"\n\treturn db.Session.Apps().Insert(app)\n}", "func (m *Linear) Forward(x mat.Tensor) mat.Tensor {\n\treturn ag.Add(ag.Mul(m.W, x), m.B)\n}", "func (ph *Handler) Forward() {\n\terr := recover()\n\tph.forward(err)\n}", "func (c *chrono) Forward(skew time.Duration) {\n\tc.skew = skew\n}", "func (fl *follow) forward(r io.Reader) (cont bool) {\n\tfl.Decoder.Reset(r)\n\treturn fl.Forwarder.Do(fl.Watcher, fl.Decoder)\n}", "func (la *Lattice) Forward(m TokenizeMode) {\n\tfor i, size := 1, len(la.list); i < size; i++ {\n\t\tcurrentList := la.list[i]\n\t\tfor index, target := range currentList {\n\t\t\tprevList := la.list[target.Start]\n\t\t\tif len(prevList) == 0 {\n\t\t\t\tla.list[i][index].Cost = maximumCost\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j, n := range prevList {\n\t\t\t\tvar c int16\n\t\t\t\tif n.Class != USER && target.Class != USER {\n\t\t\t\t\tc = la.dic.Connection.At(int(n.Right), int(target.Left))\n\t\t\t\t}\n\t\t\t\ttotalCost := int64(c) + int64(target.Weight) + int64(n.Cost)\n\t\t\t\tif m != Normal {\n\t\t\t\t\ttotalCost += int64(additionalCost(n))\n\t\t\t\t}\n\t\t\t\tif totalCost > maximumCost {\n\t\t\t\t\ttotalCost = maximumCost\n\t\t\t\t}\n\t\t\t\tif j == 0 || int32(totalCost) < la.list[i][index].Cost {\n\t\t\t\t\tla.list[i][index].Cost = int32(totalCost)\n\t\t\t\t\tla.list[i][index].prev = la.list[target.Start][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (rt *Router) forward() {\n\tfor i, v := range rt.InInterfaceL {\n\t\t//pktS := \"\"\n\n\t\t// TRYE\n\t\t// get packet from interface i\n\t\tif pktS, err := v.Get(); err == nil {\n\t\t\t//fmt.Println(\"in routher forward, packet from Get(): \", pktS)\n\t\t\t// if packet exists make a forwarding decision\n\t\t\tp, err := FromByteS(pktS)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not get packet\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// HERE you will need to implement a lookup into the\n\t\t\t// forwarding table to find the appropriate outgoing interface\n\t\t\t// for now we assume the outgoing interface is also i\n\t\t\tfmt.Printf(\"%s: forwarding packet %s from interface %d to %d with mtu %d\\n\", rt.Str(), p.Str(), i, i, rt.OutInterfaceL[i].Mtu)\n\n\t\t\tif err = rt.OutInterfaceL[i].Put(p.ToByteS(), false); err != nil {\n\t\t\t\t//log.Printf(\"Could not put packet %s in router %s, into outInterface %d. Error: %s\", p.str, rt.forward, i, err)\n\t\t\t\tlog.Printf(\"%s: packet '%s' lost on interface %d\\n\", rt.Str(), i)\n\t\t\t}\n\t\t}\n\t\t//log.Println(\"no packet to forard in router\")\n\t}\n}", "func (r *LeakyReLU[O]) Forward() (mat.Tensor, error) {\n\treturn r.x.Value().(mat.Matrix).ApplyWithAlpha(leakyReLU, r.alpha.Value().Item().F64()), nil\n}", "func (r *Raft) becomeFollower(term uint64, lead uint64) {\n\t// Your Code Here (2A).\n\tr.State = StateFollower\n\tr.Lead = lead\n\tr.Term = term\n\tr.Vote = None\n}", "func forwardTlcAck(gossiperPtr *core.Gossiper, ack *core.TLCAck) {\n\n\tif ack.HopLimit == 0 {\n\t\t// if we have reached the HopLimit, drop the message\n\t\treturn\n\t}\n\n\tgossiperPtr.DestinationTable.DsdvLock.Lock()\n\tforwardingAddress := gossiperPtr.DestinationTable.Dsdv[ack.Destination]\n\tgossiperPtr.DestinationTable.DsdvLock.Unlock()\n\t// If current node has no information about next hop to the destination in question\n\tif strings.Compare(forwardingAddress, \"\") == 0 {\n\t\t// TODO: What to do if there is no 'next hop' known when peer has to forward a private packet\n\t}\n\n\t// Decrement the HopLimit right before forwarding the packet\n\tack.HopLimit--\n\t// Encode and send packet\n\tpacketToSend := core.GossipPacket{Ack: ack}\n\tpacketBytes, err := protobuf.Encode(&packetToSend)\n\thelpers.HandleErrorFatal(err)\n\tcore.ConnectAndSend(forwardingAddress, gossiperPtr.Conn, packetBytes)\n}", "func (ch *RobertaClassificationHead) ForwardT(hiddenStates *ts.Tensor, train bool) *ts.Tensor {\n\tappliedDO1 := hiddenStates.MustSelect(1, 0, false).ApplyT(ch.dropout, train)\n\tappliedDense := appliedDO1.Apply(ch.dense)\n\ttanhTs := appliedDense.MustTanh(false)\n\tappliedDO2 := tanhTs.ApplyT(ch.dropout, train)\n\tretVal := appliedDO2.Apply(ch.outProj)\n\n\tappliedDO1.MustDrop()\n\tappliedDense.MustDrop()\n\ttanhTs.MustDrop()\n\tappliedDO2.MustDrop()\n\n\treturn retVal\n}", "func (b *RequiredArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) ArgumentNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\ts.InG = g.Sigmoid(nn.Affine(g, m.BIn, m.WIn, x, m.WInRec, yPrev))\n\ts.ForG = g.Sigmoid(nn.Affine(g, m.BFor, m.WFor, x, m.WForRec, yPrev))\n\ts.Cand = g.Tanh(g.Mul(m.WCand, x))\n\ts.Y = g.Prod(s.InG, s.Cand)\n\tif yPrev != nil {\n\t\ts.Y = g.Add(s.Y, g.Prod(g.Tanh(yPrev), s.ForG))\n\t}\n\treturn\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tlabels = sc.classifier.ForwardT(hiddenState, train)\n\thiddenState.MustDrop()\n\n\treturn labels, hiddenStates, attentions, nil\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tif p.RequiresFullSeq() {\n\t\treturn p.fullSeqForward(xs)\n\t}\n\treturn p.incrementalForward(xs)\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tg := m.Graph()\n\thalfSize := xs[0].Value().Size() / 2\n\n\tres := make([]ag.Node, len(xs))\n\tgate := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tres[i] = g.View(x, 0, 0, halfSize, 1)\n\t\tgate[i] = g.View(x, halfSize, 0, halfSize, 1)\n\t}\n\n\tgate = m.Norm.Forward(gate...)\n\tgate = m.Proj.Forward(gate...)\n\n\tif m.Act != nil {\n\t\tgate = m.Act.Forward(gate...)\n\t}\n\n\ty := make([]ag.Node, len(gate))\n\tfor i := range y {\n\t\ty[i] = g.Prod(gate[i], res[i])\n\t}\n\treturn y\n}", "func (m *Model) StepForward(ns Nodes) (rv Nodes, err error) {\n\tstates := States{}\n\tvar tmp *Node\n\tfor _, x := range ns {\n\t\tif tmp, err = m.Forward(x, states); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trv = append(rv, tmp)\n\t}\n\treturn rv, nil\n}", "func (r *RotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := Rotate(fx, r.angle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (tc *RobertaForTokenClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := tc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := hiddenState.ApplyT(tc.dropout, train)\n\toutput = appliedDO.Apply(tc.classifier)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (a *provisionApp) forward(app *App, args ...interface{}) error {\n\tvar units uint\n\tif len(args) > 0 {\n\t\tswitch args[0].(type) {\n\t\tcase int:\n\t\t\tunits = uint(args[0].(int))\n\t\tcase int64:\n\t\t\tunits = uint(args[0].(int64))\n\t\tcase uint:\n\t\t\tunits = args[0].(uint)\n\t\tcase uint64:\n\t\t\tunits = uint(args[0].(uint64))\n\t\tdefault:\n\t\t\tunits = 1\n\t\t}\n\t}\n\terr := Provisioner.Provision(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif units > 1 {\n\t\t_, err = Provisioner.AddUnits(app, units-1)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (r *Raft) Step(m pb.Message) error {\n\t// Your Code Here (2A).\n\n\t// ignore if term is less than me\n\tif m.Term < r.Term && (isCandidateMsg(m) || isLeaderMsg(m)) {\n\t\t//r.appendMsg(r.buildReject(pb.MessageType_MsgAppend, m.From))\n\t\treturn nil\n\t}\n\n\tswitch r.State {\n\tcase StateFollower:\n\t\tswitch m.MsgType {\n\t\tcase pb.MessageType_MsgHup:\n\t\t\tr.handleMsgUp()\n\t\tcase pb.MessageType_MsgAppend:\n\t\t\t// update state\n\t\t\t// use equal for handle vote success\n\t\t\tif m.Term >= r.Term {\n\t\t\t\t// only append entry as follower\n\t\t\t\tr.becomeFollower(m.Term, m.From)\n\t\t\t}\n\t\t\tr.handleAppendEntries(m)\n\t\tcase pb.MessageType_MsgRequestVote:\n\t\t\tif m.Term > r.Term {\n\t\t\t\t// update term\n\t\t\t\tr.becomeFollower(m.Term, None)\n\t\t\t}\n\t\t\tr.handleVoter(m)\n\t\tcase pb.MessageType_MsgHeartbeat:\n\t\t\tr.handleHeartbeat(m)\n\t\t\t// ignore other msg\n\t\t}\n\tcase StateCandidate:\n\t\tswitch m.MsgType {\n\t\tcase pb.MessageType_MsgHup:\n\t\t\tr.handleMsgUp()\n\t\tcase pb.MessageType_MsgAppend:\n\t\t\t// change state, reset follower info\n\t\t\tif m.Term >= r.Term {\n\t\t\t\tr.becomeFollower(m.Term, m.From)\n\t\t\t\t// only append entry as follower\n\t\t\t\tr.handleAppendEntries(m)\n\t\t\t}\n\t\tcase pb.MessageType_MsgHeartbeat:\n\t\t\tr.handleHeartbeat(m)\n\t\tcase pb.MessageType_MsgRequestVoteResponse:\n\t\t\tr.handleVoteResponse(m)\n\t\tcase pb.MessageType_MsgRequestVote:\n\t\t\tif m.Term > r.Term {\n\t\t\t\tr.becomeFollower(m.Term, None)\n\t\t\t\tr.handleVoter(m)\n\t\t\t} else {\n\t\t\t\tr.appendMsg(r.buildMsgWithoutData(pb.MessageType_MsgRequestVoteResponse, m.From, true))\n\t\t\t}\n\t\t\t// ignore other msg\n\t\t}\n\tcase StateLeader:\n\t\tswitch m.MsgType {\n\t\tcase pb.MessageType_MsgAppend:\n\t\t\t// change state, reset follower info\n\t\t\tif m.Term > r.Term {\n\t\t\t\tr.becomeFollower(m.Term, m.From)\n\t\t\t\t// only append entry as follower\n\t\t\t\tr.handleAppendEntries(m)\n\t\t\t}\n\t\tcase pb.MessageType_MsgHeartbeat:\n\t\t\tr.handleHeartbeat(m)\n\t\tcase pb.MessageType_MsgPropose:\n\t\t\tr.handlePropose(m)\n\t\tcase pb.MessageType_MsgAppendResponse:\n\t\t\tr.handleAppendResp(m)\n\t\tcase pb.MessageType_MsgBeat:\n\t\t\tr.sendHeartBeatToAll()\n\t\tcase pb.MessageType_MsgRequestVote:\n\t\t\tif m.Term > r.Term {\n\t\t\t\tr.becomeFollower(m.Term, None)\n\t\t\t\tr.handleVoter(m)\n\t\t\t} else {\n\t\t\t\tr.appendMsg(r.buildMsgWithoutData(pb.MessageType_MsgRequestVoteResponse, m.From, true))\n\t\t\t}\n\t\t\t// @think ignore heart resp,it seems not need to handle it\n\t\t\t// ignore other msg\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func (f *Forwarder) Forward(data *call.CallData) {\n\tf.transferAgents.Range(func(key interface{}, value interface{}) bool {\n\t\tstreamId := key.(userid.ID)\n\t\tstream := value.(TransferAgent)\n\t\tif streamId == userid.ID(data.UserId) { // Don't need to forward data back to sender\n\t\t\treturn true\n\t\t}\n\n\t\tif err := stream.Send(data); err != nil {\n\t\t\tf.logger.Error(err)\n\t\t}\n\n\t\treturn true\n\t})\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (r *Lachesis) FastForward(\n\treq *net.FastForwardRequest, resp *net.FastForwardResponse) error {\n\tresult, err := r.process(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, ok := result.(*net.FastForwardResponse)\n\tif !ok {\n\t\treturn ErrBadResult\n\t}\n\t*resp = *item\n\treturn nil\n}", "func (a *createRepository) forward(app *App, args ...interface{}) error {\n\tgUrl := repository.GitServerUri()\n\tvar users []string\n\tfor _, t := range app.GetTeams() {\n\t\tusers = append(users, t.Users...)\n\t}\n\tc := gandalf.Client{Endpoint: gUrl}\n\t_, err := c.NewRepository(app.Name, users, false)\n\treturn err\n}", "func (rr *RandRotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := RandomRotate(fx, rr.minAngle, rr.maxAngle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (b *TestDriver) Forward(val int) error {\n\tlog.Printf(\"Forward: %d\", val)\n\n\treturn nil\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tys := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = m.forward(x)\n\t}\n\treturn ys\n}", "func (device *SilentStepperBrick) DriveForward() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionDriveForward), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func Forward(b Branch, distance float64) Branch {\n\tvar b_new Branch\n\tb_new.phase = b.phase\n\tb_new.xy = b.xy + cmplx.Rect(distance, b.phase)\n\treturn b_new\n}", "func (c *ManetConnection) forward(bytes []byte) {\n\tincomingHeader := data.PacketHeaderFromBytes(bytes)\n\n\tcached := c.inCache(incomingHeader.SequenceNumber, incomingHeader.SendKey)\n\tfmt.Println(\"CACHE: \", incomingHeader.SequenceNumber, incomingHeader.SendKey, cached)\n\n\tif cached || incomingHeader.TTL <= 1 {\n\t\tfmt.Println(\"DROP!\")\n\t\treturn\n\t}\n\n\tc.cache[incomingHeader.SequenceNumber] = incomingHeader.SendKey\n\tdelete(c.cache, incomingHeader.SequenceNumber-cacheDepth)\n\n\toutgoingHeader := &data.PacketHeader{\n\t\tSourceAddress: incomingHeader.SourceAddress,\n\t\tDestinationAddress: incomingHeader.DestinationAddress,\n\t\tPreviousHop: GetMyAddress(),\n\t\tTTL: incomingHeader.TTL - 1,\n\t\tPacketType: incomingHeader.PacketType,\n\t\tSequenceNumber: incomingHeader.SequenceNumber,\n\t\tNumBytes: incomingHeader.NumBytes,\n\t\tSendKey: incomingHeader.SendKey,\n\t}\n\n\tfor i, b := range outgoingHeader.ToBytes() {\n\t\tbytes[i] = b\n\t}\n\n\tfor neighbor := range myNeighbors {\n\t\tif neighbor == incomingHeader.PreviousHop {\n\t\t\tcontinue\n\t\t}\n\t\traddr := ToUDPAddr(neighbor)\n\t\tfmt.Println(\"FORWARD to\", neighbor, \"DEST: \", incomingHeader.DestinationAddress, \"aka\", raddr)\n\t\tif _, err := c.conn.WriteToUDP(bytes, raddr); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (l *AffineLayer) Forward(x mat.Matrix) mat.Matrix {\n\t_, c := x.Dims()\n\tif c != l.dimIn {\n\t\tpanic(fmt.Sprintf(\"expect %d but got %d\", l.dimIn, c))\n\t}\n\tl.x = x\n\tvar ret mat.Dense\n\tret.Mul(x, l.Weight)\n\tret.Apply(func(i, j int, val float64) float64 {\n\t\treturn l.Bias.At(j, 0) + val\n\t}, &ret)\n\treturn &ret\n}", "func (t *Type) ForwardType() *ForwardType", "func (r *Raft) Step(m pb.Message) error {\n\t// Your Code Here (2A).\n\tswitch r.State {\n\n\tcase StateFollower:\n\t\tswitch m.MsgType {\n\t\tcase pb.MessageType_MsgRequestVote:\n\t\t\tr.handleVoting(m)\n\t\tcase pb.MessageType_MsgHup:\n\t\t\tr.startVoting()\n\t\tcase pb.MessageType_MsgHeartbeat:\n\t\t\tr.handleMsgHeartbeat(m)\n\t\tcase pb.MessageType_MsgAppend:\n\t\t\tr.handleAppendEntries(m)\n\t\t}\n\n\tcase StateCandidate:\n\t\tswitch m.MsgType {\n\t\tcase pb.MessageType_MsgRequestVote:\n\t\t\tr.handleVoting(m)\n\t\tcase pb.MessageType_MsgHup:\n\t\t\tr.startVoting()\n\t\tcase pb.MessageType_MsgRequestVoteResponse:\n\t\t\tr.handleVotingResponse(m)\n\t\tcase pb.MessageType_MsgAppend:\n\t\t\tr.handleAppendEntries(m)\n\t\t}\n\n\tcase StateLeader:\n\t\tswitch m.MsgType {\n\t\tcase pb.MessageType_MsgHeartbeat:\n\t\t\tr.handleHeartbeat(m)\n\t\tcase pb.MessageType_MsgHup:\n\n\t\tcase pb.MessageType_MsgRequestVote:\n\t\t\tr.handleVoting(m)\n\t\tcase pb.MessageType_MsgBeat:\n\t\t\tr.handleBeat()\n\t\tcase pb.MessageType_MsgAppend:\n\t\t\tr.handleAppendEntries(m)\n\t\tcase pb.MessageType_MsgPropose:\n\t\t\tr.handlePropose(m)\n\t\tcase pb.MessageType_MsgAppendResponse:\n\t\t\tr.handleAppendResponse(m)\n\t\t}\n\t}\n\treturn nil\n}", "func (r *Raft) becomeFollower(term uint64, lead uint64) {\n\t// Your Code Here (2A).\n\tr.State = StateFollower\n\tr.Term = term\n\tr.Lead = lead\n\tr.Vote = r.Lead\n\tr.electionElapsed = 0\n\tr.actualElectionTimeout = rand.Intn(r.electionTimeout) + r.electionTimeout\n\tr.leadTransferee = None\n}", "func MoveForward(n *Node, length int) *Node {\n\tfor i := 0; i < length; i++ {\n\t\tif n == nil {\n\t\t\tpanic(\"Null reference. Linked List Chain is broken.\")\n\t\t}\n\t\tn = n.Next\n\t}\n\treturn n\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tif len(xs) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tmean := ag.ReduceMean(x)\n\t\tdev := ag.SubScalar(x, mean)\n\t\tstdDev := ag.Sqrt(ag.Add(ag.ReduceMean(ag.Square(dev)), m.Eps))\n\t\tout[i] = ag.Add(ag.Prod(ag.DivScalar(dev, stdDev), m.W), m.B)\n\t}\n\treturn out\n}", "func (r *Raft) Step(m pb.Message) error {\n\t// Your Code Here (2A).\n\n\tvar peers []uint64\n\tfor k := range r.Prs {\n\t\tpeers = append(peers, k)\n\t}\n\tlog.DInfo(\"r %d {%v} receive %+v\", r.id, peers, m)\n\n\t// 非 Hup Beat Propose 等 local message,如果已经过期,直接丢弃消息\n\tif m.Term > 0 && m.Term < r.Term {\n\t\treturn nil\n\t}\n\n\tif m.Term > r.Term {\n\t\t// 1 2 | 3 隔离,1 term 6 leader, 3 term 7 candidate\n\t\t// 解除隔离以后,1 收到了 3 的请求投票 rpc,要更新自己的任期,但是不能接受对方的领导\n\t\t// 只有明确声明自己是领导才承认,即 Append Heartbeat Snapshot\n\t\tif m.MsgType == pb.MessageType_MsgAppend ||\n\t\t\tm.MsgType == pb.MessageType_MsgHeartbeat ||\n\t\t\tm.MsgType == pb.MessageType_MsgSnapshot {\n\t\t\tr.becomeFollower(m.Term, m.From)\n\t\t} else {\n\t\t\tr.becomeFollower(m.Term, None)\n\t\t}\n\t}\n\n\tswitch r.State {\n\tcase StateFollower:\n\t\t// 不可以 drop,比如新加的一个节点,不知道有谁是 peers\n\t\treturn r.stepFollower(m)\n\tcase StateCandidate:\n\t\tif _, ok := r.Prs[r.id]; !ok {\n\t\t\treturn nil\n\t\t}\n\t\treturn r.stepCandidate(m)\n\tcase StateLeader:\n\t\tif _, ok := r.Prs[r.id]; !ok {\n\t\t\treturn nil\n\t\t}\n\t\treturn r.stepLeader(m)\n\t}\n\treturn nil\n}", "func forward(statusch <-chan engine.SearchStatus, responsech chan<- uci.Response) {\n\tfor info := range statusch {\n\t\tresponsech <- uci.ResponseSearchInformation{Depth: info.Depth}\n\t}\n}", "func (m *EventItemRequestBuilder) Forward()(*i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.ForwardRequestBuilder) {\n return i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.NewForwardRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (t *TimeLine) forward(num, denom uint32, runCallbacks bool) {\n\tend := t.cursor + t.Ticks(num, denom)\n\tif runCallbacks {\n\t\tt.lastDelta = t.runCallbacks(t.cursor, end)\n\t}\n\tt.cursor = end\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (b *LiteralArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) LiteralNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (req *RequestData) Forward(client *http.Client, config BasketConfig, basket string) (*http.Response, error) {\n\tforwardURL, err := url.ParseRequestURI(config.ForwardURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid forward URL: %s - %s\", config.ForwardURL, err)\n\t}\n\n\t// expand path\n\tif config.ExpandPath && len(req.Path) > len(basket)+1 {\n\t\tforwardURL.Path = expandURL(forwardURL.Path, req.Path, basket)\n\t}\n\n\t// append query\n\tif len(req.Query) > 0 {\n\t\tif len(forwardURL.RawQuery) > 0 {\n\t\t\tforwardURL.RawQuery += \"&\" + req.Query\n\t\t} else {\n\t\t\tforwardURL.RawQuery = req.Query\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(req.Method, forwardURL.String(), strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create forward request: %s\", err)\n\t}\n\n\t// copy headers\n\tfor header, vals := range req.Header {\n\t\tfor _, val := range vals {\n\t\t\tforwardReq.Header.Add(header, val)\n\t\t}\n\t}\n\t// headers cleanup\n\tforwardHeadersCleanup(forwardReq)\n\t// set do not forward header\n\tforwardReq.Header.Set(DoNotForwardHeader, \"1\")\n\n\t// forward request\n\tresponse, err := client.Do(forwardReq)\n\tif err != nil {\n\t\t// HTTP issue during forwarding - HTTP 502 Bad Gateway\n\t\tlog.Printf(\"[warn] failed to forward request for basket: %s - %s\", basket, err)\n\t\tbadGatewayResp := &http.Response{\n\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(\"Failed to forward request: %s\", err)))}\n\t\tbadGatewayResp.Header.Set(\"Content-Type\", \"text/plain\")\n\n\t\treturn badGatewayResp, nil\n\t}\n\n\treturn response, nil\n}", "func (p *Player) Forward() mgl32.Vec3 {\n\treturn p.Speed\n}", "func (m *Model) Forward(cache Cache, q, x []mat.Tensor) ([]mat.Tensor, []mat.Tensor, Cache) {\n\tvar pk, pv mat.Tensor\n\n\tpq := m.Query.Forward(q...)\n\n\tif hasCache := cache.HasValues(); hasCache && m.IsCrossAttention {\n\t\tpk = cache[0]\n\t\tpv = cache[1]\n\t} else {\n\t\tk := m.Key.Forward(x...)\n\t\tv := m.Value.Forward(x...)\n\n\t\tif hasCache {\n\t\t\tpk = ag.AppendRows(cache[0], k...)\n\t\t\tpv = ag.AppendRows(cache[1], v...)\n\t\t} else {\n\t\t\tpk = ag.Stack(k...)\n\t\t\tpv = ag.Stack(v...)\n\t\t}\n\t}\n\n\tresult, weights := attention.ScaledDotProductAttention(pq, pk, pv, m.ScaleFactor, m.UseCausalMask)\n\n\treturn result, weights, Cache{pk, pv}\n}", "func (app *upApplication) GSLeftwards() {\n\tapp.teleportSettings.Reverse = true\n\tapp.teleportSettings.Vertical = false\n\tapp.teleportSettings.Length = upTeleportLen\n}", "func (s *Server) forward(method string, info structs.RPCInfo, args interface{}, reply interface{}) (bool, error) {\n\tvar firstCheck time.Time\n\n\t// Handle DC forwarding\n\tdc := info.RequestDatacenter()\n\tif dc != s.config.Datacenter {\n\t\terr := s.forwardDC(method, dc, args, reply)\n\t\treturn true, err\n\t}\n\n\t// Check if we can allow a stale read, ensure our local DB is initialized\n\tif info.IsRead() && info.AllowStaleRead() && !s.raft.LastContact().IsZero() {\n\t\treturn false, nil\n\t}\n\nCHECK_LEADER:\n\t// Fail fast if we are in the process of leaving\n\tselect {\n\tcase <-s.leaveCh:\n\t\treturn true, structs.ErrNoLeader\n\tdefault:\n\t}\n\n\t// Find the leader\n\tisLeader, leader := s.getLeader()\n\n\t// Handle the case we are the leader\n\tif isLeader {\n\t\treturn false, nil\n\t}\n\n\t// Handle the case of a known leader\n\trpcErr := structs.ErrNoLeader\n\tif leader != nil {\n\t\trpcErr = s.connPool.RPC(s.config.Datacenter, leader.Addr,\n\t\t\tleader.Version, method, leader.UseTLS, args, reply)\n\t\tif rpcErr != nil && canRetry(info, rpcErr) {\n\t\t\tgoto RETRY\n\t\t}\n\t\treturn true, rpcErr\n\t}\n\nRETRY:\n\t// Gate the request until there is a leader\n\tif firstCheck.IsZero() {\n\t\tfirstCheck = time.Now()\n\t}\n\tif time.Since(firstCheck) < s.config.RPCHoldTimeout {\n\t\tjitter := lib.RandomStagger(s.config.RPCHoldTimeout / jitterFraction)\n\t\tselect {\n\t\tcase <-time.After(jitter):\n\t\t\tgoto CHECK_LEADER\n\t\tcase <-s.leaveCh:\n\t\tcase <-s.shutdownCh:\n\t\t}\n\t}\n\n\t// No leader found and hold time exceeded\n\treturn true, rpcErr\n}", "func (r *Raft) becomeFollower(term uint64, lead uint64) {\n\tr.State = StateFollower\n\tr.Term = term\n\tr.Lead = lead\n\tr.Vote = None\n\tr.electionElapsed = 0\n\tr.randomElectionTimeout = randomTimeout(r.electionTimeout)\n\t// Your Code Here (2A).\n}", "func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {\n\tlState := makeFBOLockState()\n\tfbo.headLock.RLock(lState)\n\tdefer fbo.headLock.RUnlock(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t// We're already up to date.\n\t\treturn\n\t}\n\tif !fbo.hasBeenCleared {\n\t\t// No reason to fast-forward here if it hasn't ever been\n\t\t// cleared.\n\t\treturn\n\t}\n\n\tfbo.forcedFastForwards.Add(1)\n\tfbo.goTracked(func() {\n\t\tdefer fbo.forcedFastForwards.Done()\n\t\tctx, cancelFunc := fbo.newCtxWithFBOID()\n\t\tdefer cancelFunc()\n\n\t\tfbo.log.CDebugf(ctx, \"Forcing a fast-forward\")\n\t\tvar currHead ImmutableRootMetadata\n\t\tvar err error\n\tgetMD:\n\t\tfor i := 0; ; i++ {\n\t\t\tcurrHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)\n\t\t\tswitch errors.Cause(err).(type) {\n\t\t\tcase nil:\n\t\t\t\tbreak getMD\n\t\t\tcase kbfsmd.ServerErrorUnauthorized:\n\t\t\t\t// The MD server connection might not be authorized\n\t\t\t\t// yet, so give it a few chances to go through.\n\t\t\t\tif i > 5 {\n\t\t\t\t\tfbo.log.CDebugf(ctx,\n\t\t\t\t\t\t\"Still unauthorized for TLF %s; giving up fast-forward\",\n\t\t\t\t\t\tfbo.id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i == 0 {\n\t\t\t\t\tfbo.log.CDebugf(\n\t\t\t\t\t\tctx, \"Got unauthorized error when fast-forwarding %s; \"+\n\t\t\t\t\t\t\t\"trying again after a delay\", fbo.id())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tdefault:\n\t\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif currHead == (ImmutableRootMetadata{}) {\n\t\t\tfbo.log.CDebugf(ctx, \"No MD yet\")\n\t\t\treturn\n\t\t}\n\t\tfbo.log.CDebugf(ctx, \"Current head is revision %d\", currHead.Revision())\n\n\t\tlState := makeFBOLockState()\n\t\t// Kick off partial prefetching once the latest merged\n\t\t// revision is set.\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tfbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)\n\t\t\t}\n\t\t}()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\tfbo.headLock.Lock(lState)\n\t\tdefer fbo.headLock.Unlock(lState)\n\n\t\tif !fbo.hasBeenCleared {\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t\tfbo.hasBeenCleared = false\n\t\t\t}\n\t\t}()\n\n\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t// We're already up to date.\n\t\t\tfbo.log.CDebugf(ctx, \"Already up-to-date: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = fbo.doFastForwardLocked(ctx, lState, currHead)\n\t\tif err != nil {\n\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %v\", err)\n\t\t}\n\t})\n}", "func (r *Pow) Forward() mat.Matrix {\n\treturn r.x.Value().Pow(r.power)\n}", "func (s *Service) Forward(topicID, msgID, targetAddr, text string) error {\n\tpayload := map[string]interface{}{\n\t\t\"id\": msgID,\n\t\t\"address\": targetAddr,\n\t\t\"text\": text,\n\t}\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpf, err := s.client.Publish(topicID, b, 2, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pf.Wait(5 * time.Second)\n}", "func (r *Redirect) Forward(conn net.Conn) {\n\tif conn == nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\trequest = []byte{}\n\t\trequestTmp = make([]byte, 1024)\n\t)\n\n\tfor {\n\t\tn, err := conn.Read(requestTmp)\n\t\tif err != nil {\n\t\t\tr.reply(conn, nil, \"\", err)\n\t\t\treturn\n\t\t}\n\t\trequest = append(request, requestTmp[:n]...)\n\t\tif n < 1024 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(request)))\n\n\tif err != nil {\n\t\tr.reply(conn, nil, \"\", err)\n\t\treturn\n\t}\n\n\tu, err := url.Parse(string(req.RequestURI[1:]))\n\tif err != nil {\n\t\tr.reply(conn, req, \"\", err)\n\t\treturn\n\t}\n\treq.URL = u\n\treq.Host = u.Host\n\n\treq.RequestURI = \"\"\n\trequestObj := r.requestPool.Get().(*RequestWrapper)\n\trequestObj.CreatedTime = time.Now()\n\trequestObj.request = req\n\trequestObj.TryCount = 0\n\trequestObj.ID = r.makeID()\n\n\tif !r.putTask(requestObj, false) {\n\t\tr.reply(conn, req, \"\", errors.New(\"request put into buffer timeout\"))\n\t\treturn\n\t}\n\n\tr.reply(conn, req, requestObj.ID, nil)\n}", "func forward(session *api.Session, msg []byte) error {\n\tframe := &pb.Game_Frame{\n\t\tType: pb.Game_Message,\n\t\tMessage: msg,\n\t}\n\n\t// check stream\n\tif session.Stream == nil {\n\t\treturn ErrorStreamNotOpen\n\t}\n\n\t// forward the frame to game\n\tif err := session.Stream.Send(frame); err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func (s *Server) Forward(id int64, event api.Event) {\n\tif event.Type == \"logging\" {\n\t\t// Parse the message\n\t\tlogEntry := api.EventLogging{}\n\t\terr := json.Unmarshal(event.Metadata, &logEntry)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && logEntry.Level == \"dbug\" {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && !s.verbose && logEntry.Level == \"info\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := s.broadcast(event, true)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to forward event from member %d: %v\", id, err)\n\t}\n}", "func updateModel() {\n\t//update the state for the state machine\n\tif robotArm2.isStopped() { //if both joints are stopped\n\t\tarmloop.setState(finished) //set the state to finished\n\n\t\tif len(pts)-1 > pointIndex { //if there is another point to move to\n\t\t\tpointIndex++ //request to move to new goal point\n\t\t} //if\n\t} //if\n\n\tarmloop.onLoop() //move the arm\n}", "func (t *TimeLine) Forward(nbars, num, denom uint32) {\n\tif nbars > 0 {\n\t\toldCursor := t.cursor\n\t\tt.forwardNBars(nbars)\n\t\tt.lastDelta = t.runCallbacks(oldCursor, t.cursor)\n\t}\n\n\tif num > 0 && denom > 0 {\n\t\tt.forward(num, denom, true)\n\t}\n\n}", "func (r *Raft) Step(m pb.Message) error {\n\tif _, ok := r.Prs[r.id]; !ok && m.MsgType == pb.MessageType_MsgTimeoutNow {\n\t\treturn nil\n\t}\n\tif m.Term > r.Term {\n\t\tr.leadTransferee = None\n\t\tr.becomeFollower(m.Term, None)\n\t}\n\tswitch r.State {\n\tcase StateFollower:\n\t\tr.stepFollower(m)\n\tcase StateCandidate:\n\t\tr.stepCandidate(m)\n\tcase StateLeader:\n\t\tr.stepLeader(m)\n\t}\n\treturn nil\n}", "func (qa *RobertaForQuestionAnswering) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (startScores, endScores *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := qa.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, ts.None, nil, nil, err\n\t}\n\n\tsequenceOutput := hiddenState.Apply(qa.qaOutputs)\n\tlogits := sequenceOutput.MustSplit(1, -1, true)\n\tstartScores = logits[0].MustSqueeze1(-1, false)\n\tendScores = logits[1].MustSqueeze1(-1, false)\n\n\tfor _, x := range logits {\n\t\tx.MustDrop()\n\t}\n\n\treturn startScores, endScores, hiddenStates, attentions, nil\n}", "func (c *compiler) patchForward(mark int) {\n\toffset := len(c.code) - mark\n\tc.code[mark-1] = opcodeInt(offset)\n}", "func (a *createBucketIam) forward(app *App, args ...interface{}) error {\n\tenv, err := createBucket(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _ := config.GetString(\"host\")\n\tenvVars := []bind.EnvVar{\n\t\t{Name: \"APPNAME\", Value: app.Name},\n\t\t{Name: \"TSURU_HOST\", Value: host},\n\t}\n\tvariables := map[string]string{\n\t\t\"ENDPOINT\": env.endpoint,\n\t\t\"LOCATIONCONSTRAINT\": strconv.FormatBool(env.locationConstraint),\n\t\t\"ACCESS_KEY_ID\": env.AccessKey,\n\t\t\"SECRET_KEY\": env.SecretKey,\n\t\t\"BUCKET\": env.bucket,\n\t}\n\tfor name, value := range variables {\n\t\tenvVars = append(envVars, bind.EnvVar{\n\t\t\tName: fmt.Sprintf(\"TSURU_S3_%s\", name),\n\t\t\tValue: value,\n\t\t\tInstanceName: s3InstanceName,\n\t\t})\n\t}\n\tapp.SetEnvsToApp(envVars, false, true)\n\treturn nil\n}", "func (r *RaftNode) shiftToFollower(t Term, leaderID HostID) {\n\tif r.verbose {\n\t\tlog.Printf(\"############ SHIFT TO FOLLOWER, Term: %d, LeaderID: %d\", t, leaderID)\n\t}\n\tr.state = follower\n\tr.CurrentTerm = t\n\tr.currentLeader = leaderID\n\tr.nextIndex = nil\n\tr.matchIndex = nil\n\tr.VotedFor = -1\n}", "func (ship *Ship) fwdThrustersOn() {\n\tif !ship.fwdThrusters {\n\t\tship.fwdThrusters = true\n\t\tstartRcsSound()\n\t}\n}", "func (f *LinkedList) printAllElmtForward() () {\n\tif (f.length == 0) {\n\t\tfmt.Printf(\"List empty\")\n\t} else {\n\t\tfmt.Printf(\"Forward (%d): \",f.length)\n\t\tcurrentElmt := f.start\n\t\tfor currentElmt != nil {\n\t\t\tfmt.Printf(\"%d \",currentElmt.body)\n\t\t\tcurrentElmt = currentElmt.next\n\t\t}\n\t\tfmt.Println()\n\t}\n}", "func (lay *Layer) Forward(x *mat.Dense) (a *mat.Dense) {\n\t// x is (n x in )\n\trow, _ := x.Dims()\n\n\txx := new(mat.Dense)\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\tz.Apply(func(i, j int, v float64) float64 { return lay.act.f(v) }, z)\n\treturn z\n}", "func (bc *BlockChain) SetHead(head uint64) error {\n\tlog.Fatal(\"Rewinding blockchain\", \"target\", head)\n\n\tbc.mu.Lock()\n\tdefer bc.mu.Unlock()\n\n\t/// Rewind the header chain, deleting all block bodies until then\n\tdelFn := func(db rawdb.DatabaseDeleter, hash common.Hash, num uint64) {\n\t\trawdb.DeleteBody(db, hash, num)\n\t}\n\tbc.hc.SetHead(head, delFn)\n\tcurrentHeader := bc.hc.CurrentHeader()\n\n\t// Clear out any stale content from the caches\n\tbc.bodyCache.Purge()\n\tbc.bodyRLPCache.Purge()\n\n\t// Rewind the block chain, ensuring we don't end up with a stateless head block\n\tif currentBlock := bc.CurrentBlock(); currentBlock != nil && currentHeader.Number.Uint64() < currentBlock.NumberU64() {\n\t\tbc.currentBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))\n\t}\n\n\n\t// If either blocks reached nil, reset to the genesis state\n\tif currentBlock := bc.CurrentBlock(); currentBlock == nil {\n\t\tbc.currentBlock.Store(bc.genesisBlock)\n\t}\n\n\tcurrentBlock := bc.CurrentBlock()\n\n\trawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())\n\n\treturn nil\n}", "func HandleForwardProto(bot *Bot, data []byte) (ack []byte, err error) {\n\treturn\n}", "func (c *Cursor) Forward(n int) {\n\t(*c).Index += n\n}", "func (r *Raft) becomeFollower(term uint64, lead uint64) {\n\tr.State = StateFollower\n\tr.Term = term\n\tr.Lead = lead\n\tr.electionElapsed = 0\n\tr.actualElectionTimeout = r.generateElectionTimeout()\n}", "func Forward(in, out Link) rules.Rule {\n\treturn rules.Rule(fmt.Sprintf(\n\t\t\"-t filter -A fw-interfaces -j ACCEPT -i %v -o %v\",\n\t\tin.Name(), out.Name()))\n}", "func (t *Transaction) forwardTransaction() {\n\tif t.tx == nil {\n\t\tpanic(\"tx is nil while forward was being called\")\n\t}\n\tselect {\n\tcase t.sendTxFound <- t.tx:\n\tcase <-t.shutdown:\n\t\treturn\n\t}\n}", "func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {\n\t// TODO: implement mining rewards\n}", "func (p *SignalChannel) forward(req Request, customer *models.Customer) (res Response, err error) {\n\tlog.Debug(\"[forward] SignalChannel\")\t\n\tlog.Debugf(\"req.Uri=%+v, req.Type=%+v\", req.Uri, req.Type)\n\tvar controller ControllerInterface\n\n\t// Select controller based on prefix\n\tfor i := range req.Uri {\n\t\tif strings.HasPrefix(req.Uri[i], \"mitigate\") {\n\t\t\tlog.Debug(\"Call MitigationRequest controller\")\n\t\t\tcontroller = &MitigationRequest{}\n\t\t\tbreak;\n\t\n\t\t} else if strings.HasPrefix(req.Uri[i], \"config\") {\n\t\t\tlog.Debug(\"Call SessionConfig controller\")\n\t\t\tcontroller = &SessionConfiguration{}\n\t\t\tbreak;\t\n\t\t} else if strings.HasPrefix(req.Uri[i], \"tm-setup\") {\n\t\t\tlog.Debug(\"Call TelemetrySetupRequest controller\")\n\t\t\tcontroller = &TelemetrySetupRequest{}\n\t\t\tbreak;\n\t\t} else if strings.HasPrefix(req.Uri[i], \"tm\") {\n\t\t\tlog.Debug(\"Call TelemetryPreMitigationRequest controller\")\n\t\t\tcontroller = &TelemetryPreMitigationRequest{}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (controller == nil) {\n\t\tlog.Debug (\"No controller supports this kind of request\")\n\t\treturn Response{\n Code: dots_common.NotFound,\n Type: dots_common.NonConfirmable,\n }, nil\n\t}\n\n\t// Invoke controller service method to process request\n\tswitch req.Code {\n\tcase libcoap.RequestGet:\n\t\treturn controller.HandleGet(req, customer)\n\tcase libcoap.RequestPost:\n\t\treturn controller.HandlePost(req, customer)\n\tcase libcoap.RequestPut:\n\t\treturn controller.HandlePut(req, customer)\n\tcase libcoap.RequestDelete:\n\t\treturn controller.HandleDelete(req, customer)\n\tdefault:\n\t\tlog.Debug (\"No controller supports this type of request\")\n\t\treturn Response{\n Code: dots_common.NotFound,\n Type: dots_common.NonConfirmable,\n }, nil\n\t}\t\n}", "func forwardBox(ctx *Context, t *Tuple, w Writer) error {\n\tw.Write(ctx, t)\n\treturn nil\n}", "func forwardBackHelper(from *net.TCPConn, to *net.TCPConn, symmKey []byte, timeoutMillis int, vecLogger *govec.GoLog) {\n\tdefer func() {\n\t\tfrom.Close()\n\t\tto.Close()\n\t\tfmt.Printf(\"TorNode: connection to previous hop: %s, and next hop %s are closed\\n\", to.RemoteAddr(), from.RemoteAddr())\n\t}()\n\n\tderr := from.SetReadDeadline(time.Now().Add(time.Duration(timeoutMillis) * time.Millisecond))\n\tif derr != nil {\n\t\tfmt.Printf(\"TorNode: WARNING failed to set read deadline: %s\\n\", derr)\n\t\treturn\n\t}\n\tfmt.Printf(\"TorNode: Wating response from nextHop: %s\\n\", from.RemoteAddr())\n\tpayload, rerr := utils.TCPRead(from, vecLogger, \"Response onion received\")\n\n\tif dpassederr, ok := rerr.(net.Error); ok && dpassederr.Timeout() {\n\t\tfmt.Printf(\"TorNode: WARNING waiting data from %s timeout.\\n\", from.RemoteAddr())\n\t\treturn\n\t}\n\n\tif rerr == io.EOF {\n\t\tfmt.Printf(\"TorNode: Failed to forward response back: unexpected remote connection from [%s] closed\\n\", from.RemoteAddr())\n\t\treturn\n\t}\n\n\tif rerr != nil {\n\t\tfmt.Printf(\"TorNode: WARNING failed to read from connection: %s\\n\", rerr)\n\t\treturn\n\t}\n\n\tforwardPayload, oerr := wrapOnion(payload, symmKey)\n\n\tif oerr != nil {\n\t\tfmt.Printf(\"TorNode: WARNING could not wrap onion: %s\\n\", oerr)\n\t\treturn\n\t}\n\n\t_, werr := utils.TCPWrite(to, forwardPayload, vecLogger, \"Response onion forwarded to previous hop\")\n\tif werr != nil {\n\t\tfmt.Printf(\"TorNode: WARNING failed to forward previous hop: %s\\n\", werr)\n\t\treturn\n\t}\n\tfmt.Printf(\"TorNode: Successfully fowarded onion from %s BACK to %s, payload size: %d\\n\", from.RemoteAddr(), to.RemoteAddr(), len(payload))\n}", "func (s *State) MoveForward() {\n\tif s.robotLost {\n\t\treturn\n\t}\n\tswitch s.direction {\n\tcase North:\n\t\ts.y++\n\t\tbreak\n\tcase South:\n\t\ts.y--\n\t\tbreak\n\tcase West:\n\t\ts.x--\n\t\tbreak\n\tcase East:\n\t\ts.x++\n\t\tbreak\n\t}\n\ts.robotLost = s.grid.hasRobotFallenOff(s.x, s.y)\n}", "func (n *Network) Forward() {\n\tif !n.constructed() {\n\t\tlog.Panic(\"Cannot run an emtpy Network\")\n\t}\n\n\tfor l := range n.layers {\n\t\tcandy.Must(parallel.For(0, len(n.layers[l]), 1, func(g int) {\n\t\t\tgate := n.layers[l][g]\n\t\t\tgate.forward(gate)\n\t\t}))\n\t}\n}", "func forwardUpdateAccount(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) {\n\tw.WriteHeader(http.StatusNoContent)\n\truntime.ForwardResponseMessage(ctx, mux, marshaler, w, req, resp, opts...)\n}", "func (m *NN) Forward(x *gorgonia.Node) (err error) {\n\tl := make([]*gorgonia.Node, len(m.W)+1)\n\tldot := make([]*gorgonia.Node, len(m.W))\n\tp := make([]*gorgonia.Node, len(m.W))\n\n\t// initial the first layer\n\tl[0] = x\n\n\t// W X + B\n\tfor i := 0; i < len(m.W); i++ {\n\t\tif len(m.B) != 0 && i < len(m.W) {\n\t\t\tL1, err := gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(l[i].Shape(), m.W[i].Shape())\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tldot[i], err = gorgonia.BroadcastAdd(L1, m.B[i], nil, []byte{0})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tldot[i], err = gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"mul wrong \", err)\n\t\t\t}\n\t\t}\n\n\t\t// Dropout\n\t\tp[i], err = gorgonia.Dropout(ldot[i], m.D[i])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Can't drop!\")\n\t\t}\n\n\t\t//activation function\n\t\tl[i+1] = gorgonia.Must(m.A[i](p[i]))\n\t}\n\n\tm.Pred = gorgonia.Must(m.A[len(m.A)-1](l[len(l)-1]))\n\tgorgonia.Read(m.Pred, &m.PredVal)\n\treturn\n}", "func forwardRequest(originatorAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte, toNode Node) {\n\tif self.Addr.String() == toNode.Addr.String() {\n\t\tfmt.Println(\"Stop. Can't forward to self - \", toNode.Addr.String())\n\t\treturn\n\t}\n\n\tsendRequestToNode(msgID, reqPay, &toNode)\n}" ]
[ "0.6255751", "0.60953754", "0.60477453", "0.60463643", "0.6005756", "0.5827889", "0.5759985", "0.57281214", "0.56785464", "0.5660496", "0.5638164", "0.5615751", "0.55979073", "0.55658805", "0.55035555", "0.54785925", "0.54708135", "0.5467028", "0.5461007", "0.54442316", "0.54352707", "0.5414916", "0.53992265", "0.536681", "0.5335434", "0.5328628", "0.53283787", "0.5304722", "0.5289026", "0.52880967", "0.5287259", "0.52752763", "0.52593124", "0.5230758", "0.52054626", "0.52050626", "0.52044326", "0.5201378", "0.5199158", "0.5199158", "0.5192642", "0.5186841", "0.51859736", "0.5184046", "0.5183831", "0.5177197", "0.51692367", "0.5167003", "0.51521355", "0.51521355", "0.5136797", "0.5115004", "0.5114031", "0.51103646", "0.5108893", "0.5105884", "0.5099827", "0.5085926", "0.50757873", "0.50755495", "0.5060458", "0.5043889", "0.503756", "0.503451", "0.50313526", "0.502819", "0.5000962", "0.5000014", "0.49988738", "0.4992134", "0.49852112", "0.49791265", "0.49675107", "0.49539563", "0.49517798", "0.49498183", "0.4933321", "0.49281362", "0.49238873", "0.49138537", "0.49131563", "0.49098745", "0.49047506", "0.4901984", "0.48869216", "0.48827818", "0.48794422", "0.48678246", "0.48636645", "0.48609915", "0.485438", "0.48507136", "0.48384866", "0.48336548", "0.48309118", "0.48144114", "0.48074684", "0.48040172", "0.47968268", "0.47962353" ]
0.6625633
0
NewRobertaForMaskedLM builds a new RobertaForMaskedLM.
func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM { roberta := bert.NewBertModel(p.Sub("roberta"), config) lmHead := NewRobertaLMHead(p.Sub("lm_head"), config) return &RobertaForMaskedLM{ roberta: roberta, lmHead: lmHead, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\n\tlayerNormConfig := nn.DefaultLayerNormConfig()\n\tlayerNormConfig.Eps = 1e-12\n\tlayerNorm := nn.NewLayerNorm(p.Sub(\"layer_norm\"), []int64{config.HiddenSize}, layerNormConfig)\n\n\tdecoder := util.NewLinearNoBias(p.Sub(\"decoder\"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig())\n\n\tbias := p.NewVar(\"bias\", []int64{config.VocabSize}, nn.NewKaimingUniformInit())\n\n\treturn &RobertaLMHead{\n\t\tdense: dense,\n\t\tdecoder: decoder,\n\t\tlayerNorm: layerNorm,\n\t\tbias: bias,\n\t}\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func New[T float.DType](c Config) *RAdam[T] {\n\tadam := &RAdam[T]{\n\t\tConfig: c,\n\t\tRoMax: 2.0/(1.0-c.Beta2) - 1.0,\n\t\tTimeStep: 1.0,\n\t}\n\treturn adam\n}", "func newRaftLayer(addr string, ln net.Listener) *raftLayer {\n\treturn &raftLayer{\n\t\taddr: &raftLayerAddr{addr},\n\t\tln: ln,\n\t\tconn: make(chan net.Conn),\n\t\tclosed: make(chan struct{}),\n\t}\n}", "func NewRaft(cfg *ServerConfig) *Raft {\n\treturn &Raft{\n\t\tServer: NewServer(cfg),\n\t\tLeaderID: NoLeader,\n\t}\n}", "func NewMask() (ret [4]byte) {\n\tbinary.BigEndian.PutUint32(ret[:], rand.Uint32())\n\treturn\n}", "func NewMocklibrarian(t mockConstructorTestingTNewMocklibrarian) *Mocklibrarian {\n\tmock := &Mocklibrarian{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New() *RabinKarp64 {\n\tp, err := RandomPolynomial(1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn NewFromPol(p)\n}", "func newManager() *roolManager {\n\treturn &roolManager{pathes: make(map[string]*rool)}\n}", "func newMobileNumber(countryAbbreviation string, number string) (*mobileNumber, error) {\n\tmobileNum := &mobileNumber{\n\t\tNumberProvided: number,\n\t\tFixedNumber: number,\n\t\tcountryAbbreviation: countryAbbreviation,\n\t\tValid: true,\n\t}\n\terr := mobileNum.fix()\n\treturn mobileNum, err\n}", "func NewMMRABA(pid *idchannel.PrimitiveID, s config.Start) *MMRABA {\n\tc := s.GetConfig()\n\tm := &MMRABA{\n\t\trootpid: pid,\n\t\tc: c,\n\t\tnig: s.Getnig(),\n\t\tpig: s.Getpig(),\n\t\tl: logger.NewLoggerWithID(\"MMRABA\", c.MyID),\n\t\ts: s,\n\t\tsid: []byte(pid.Id),\n\t}\n\treturn m\n}", "func NewRulerBuilder(e e2e.Environment, name string) *RulerBuilder {\n\tf := e.Runnable(fmt.Sprintf(\"rule-%s\", name)).\n\t\tWithPorts(map[string]int{\"http\": 8080, \"grpc\": 9091}).\n\t\tFuture()\n\treturn &RulerBuilder{\n\t\treplicaLabel: name,\n\t\tLinkable: f,\n\t\tf: f,\n\t\timage: DefaultImage(),\n\t}\n}", "func (mlm *RobertaForMaskedLM) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmlm.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmlm.lmHead = NewRobertaLMHead(p.Sub(\"lm_head\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewCreateanewLnpNumberRequest(server string, body CreateanewLnpNumberJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewLnpNumberRequestWithBody(server, \"application/json\", bodyReader)\n}", "func NewRaft(config *ClusterConfig, thisServerId int) (*Raft, error) {\n\tvar raft Raft\n\traft.Id = thisServerId\n\traft.ClusterConfigV = config\n\traft.Log = make([] LogEntry,0)\n\traft.VotedTerm=-1\n\traft.VotedFor=-1\n\traft.CurrentTerm=0\n\traft.IsLeader = 2\n\traft.NextIndex=make([] int,5)\n\traft.MatchIndex=make([] int,5)\n\traft.CommitIndex=-1\n\traft.LeaderId=-1\n\traft.LastApplied = -1 \n\tfilePath:=\"log_\"+strconv.Itoa(thisServerId)+\".txt\" // log file\n f, err := os.Create(filePath)\n if(err!=nil) {\n log.Fatal(\"Error creating log file:\",err)\n }\n raft.File = f\n\treturn &raft, nil\n}", "func NewCreateanewLnpNumberRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/lnpnumbers\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tpeer2Progress := make(map[uint64]*Progress, len(c.peers))\n\tpeer2Vote := make(map[uint64]bool, len(c.peers))\n\tfor _, s := range c.peers {\n\t\tpeer2Vote[s] = false\n\t\tpeer2Progress[s] = &Progress{0, 0}\n\t}\n\trand.Seed(time.Now().UnixNano())\n\thardState, _, _ := c.Storage.InitialState()\n\treturn &Raft{id: c.ID, Term: hardState.Term, Vote: hardState.Vote, RaftLog: newLog(c.Storage), State: StateFollower, Prs: peer2Progress, votes: peer2Vote, Lead: 0, heartbeatTimeout: c.HeartbeatTick, electionTimeout: c.ElectionTick, heartbeatElapsed: 0, electionElapsed: 0, actualElectionTimeout: 0}\n}", "func NewCreateanewLnpCarrierRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/lnpcarriers\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func New(glabel string, flags int) (*GlvlStruct, error) {\n\treturn newll(glabel, flags, LflagsDef, nil, false)\n}", "func NewRobo(pitches []mlpapi.Pitch, rules []mlpapi.Rule) (robo *RoboRooney) {\n\trobo = &RoboRooney{}\n\trobo.cred = readCredentials()\n\n\trobo.mlpClient = mlpapi.New()\n\trobo.tracker = NewTracker()\n\trobo.ticker = time.NewTicker(time.Minute * time.Duration(robo.cred.TickerInterval))\n\n\tif len(pitches) == 0 {\n\t\tlog.Fatal(\"Need atleast one pitch to check\")\n\t}\n\n\trobo.pitches = pitches\n\trobo.rules = rules\n\n\treturn robo\n}", "func toLadonRequest(req *http.Request, subject string, aclCtx AccessContext) *ladon.Request {\n\n\tladonCtx := ladon.Context{}\n\n\tfor key, val := range aclCtx {\n\t\tladonCtx[key] = val\n\t}\n\n\treturn &ladon.Request{\n\t\tAction: getAction(req),\n\t\tResource: req.URL.Path,\n\t\tSubject: subject,\n\t\tContext: ladonCtx,\n\t}\n}", "func NewRobertaForTokenClassification(p *nn.Path, config *bert.BertConfig) *RobertaForTokenClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tnumLabels := int64(len(config.Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForTokenClassification{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func New(numVisibleUnits, numHiddenUnits int) *RBM {\n\trbm := new(RBM)\n\trand.Seed(time.Now().UnixNano())\n\trbm.NumVisibleUnits = numVisibleUnits\n\trbm.NumHiddenUnits = numHiddenUnits\n\trbm.W = nnet.MakeMatrix(numHiddenUnits, numVisibleUnits)\n\trbm.B = make([]float64, numVisibleUnits)\n\trbm.C = make([]float64, numHiddenUnits)\n\trbm.GradW = nnet.MakeMatrix(numHiddenUnits, numVisibleUnits)\n\trbm.GradB = make([]float64, numVisibleUnits)\n\trbm.GradC = make([]float64, numHiddenUnits)\n\trbm.InitParam()\n\treturn rbm\n}", "func NewRoar(author string, text string) *Roar {\n return &Roar{Author: author, Text: text,\n CreationDate: time.LocalTime().Format(time.RFC1123)}\n}", "func NewRaid(inputPlanes ...Plane) (Raid, error) {\n\tif len(inputPlanes) == 0 {\n\t\treturn Raid{}, errors.New(\"no planes to launch\")\n\t}\n\tvar planes []Plane\n\tfor _, plane := range inputPlanes {\n\t\tplanes = append(planes, plane)\n\t}\n\treturn Raid{Planes: planes}, nil\n}", "func BBMake(l, t, r, b Float) (BB) { \n return BB{L: l, B: b, R: r, T: t}\n}", "func NewIskratelMsan() *IskratelMsan {\r\n var t = &IskratelMsan{}\r\n\r\n return t\r\n}", "func newBruteRanger() Ranger {\n\treturn &bruteRanger{\n\t\tipV4Entries: make(map[string]RangerEntry),\n\t\tipV6Entries: make(map[string]RangerEntry),\n\t}\n}", "func newPRMRemapIdentity(prefix, signedPrefix string) (*prmRemapIdentity, error) {\n\tif err := validateIdentityRemappingPrefix(prefix); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := validateIdentityRemappingPrefix(signedPrefix); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &prmRemapIdentity{\n\t\tprmCommon: prmCommon{Type: prmTypeRemapIdentity},\n\t\tPrefix: prefix,\n\t\tSignedPrefix: signedPrefix,\n\t}, nil\n}", "func NewRTree() *RTree { //TODO could take M (and m) as input?\n\treturn &RTree{\n\t\troot: &node{\n\t\t\tparent: nil,\n\t\t\tentries: make([]entry, 0, RTree_M+1),\n\t\t\theight: 0,\n\t\t},\n\t}\n}", "func New(IP, firstContact, ID string, OutputTo io.Writer) *RaftMember {\n\t//try to get the existing data from file\n\tos.Mkdir(\"/tmp/raft/\", 0777)\n\tR, PStore, success := readPersist()\n\t//build the stateMachine\n\tpwd := \"/tmp\"\n\tos.Mkdir(pwd+\"/machines\", 0777) //make the machines directory\n\n\tR.hrt = new(time.Timer) //initialize our timer.\n\tR.giveStatus = make(chan StatusBall)\n\tR.outputTo = OutputTo\n\tR.needStatus = make(chan bool)\n\tR.giveLog = make(chan string)\n\tR.needLog = make(chan bool)\n\tR.nextIndex = make(map[string]int)\n\tR.matchIndex = make(map[string]int)\n\tR.appendRequests = make(chan string, 100)\n\tR.needScoreBoard = make(chan bool)\n\tR.suspend = make(chan int)\n\tR.GiveScoreboard = make(chan map[string]int)\n\tif !success {\n\t\t//load failed or files dont exist\n\t\tfmt.Println(\"Creating New Member\")\n\t\ttid, err := makeID()\n\t\tR.VoteLog = append(R.VoteLog, VoteRecord{Votes: make(map[string]bool), VotedFor: \"NIL\"}) //bootstrap the vote record for the 0 term\n\t\tterr.BreakError(\"ID Creation\", err)\n\t\tR.ID = tid\n\t\tR.Log = append(R.Log, LogEntry{Term: 0, Entry: \"init\"}) // make the first entry an initialize for counting purposes.\n\t\tR.Target = 1\n\t}\n\tR.Machine = stateMachine.CreateStateMachine(pwd+\"/machines/\"+R.ID[:6]+\".sm\", contentionLevel) //build or recreate the state machine.\n\tterr.VerbPrint(R.outputTo, 1, verb, \"Target Set to:\", R.Target)\n\tR.Machine.SetTarget(R.Target) //restores a target after a reboot\n\tif ID != \"\" {\n\t\tR.ID = ID\n\t}\n\n\tR.CM = CM.New(R.ID, IP, R.outputTo)\n\tif firstContact != \"\" {\n\t\tterr.VerbPrint(R.outputTo, 3, verb, \"connecting to\", firstContact)\n\t\tR.Connect(firstContact)\n\t}\n\tR.writePersist(PStore)\n\tR.et = timers.NewElectionTimer()\n\tR.run(PStore) //spawns a go routine to handle incomming messages\n\treturn R\n}", "func BuildLorad(gtw *ttnpb.Gateway, fps *frequencyplans.Store) (*LoradConfig, error) {\n\tfp, err := fps.GetByID(gtw.FrequencyPlanId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsx1301Conf := &shared.SX1301Config{}\n\tif len(fp.Radios) != 0 {\n\t\tsx1301Conf, err = shared.BuildSX1301Config(fp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar gatewayConf LoradGatewayConf\n\tif antennas := gtw.GetAntennas(); len(antennas) > 0 {\n\t\tantenna := antennas[0]\n\t\tsx1301Conf.AntennaGain = antenna.Gain\n\t\tif location := antenna.Location; location != nil {\n\t\t\tgatewayConf.BeaconLatitude = location.Latitude\n\t\t\tgatewayConf.BeaconLongitude = location.Longitude\n\t\t}\n\t}\n\t// TODO: Configure Class B (https://github.com/TheThingsNetwork/lorawan-stack/issues/1748).\n\treturn &LoradConfig{\n\t\tSX1301Conf: LoradSX1301Conf{\n\t\t\tSX1301Config: *sx1301Conf,\n\t\t\t// Following fields are set equal to defaults present in CPF 1.1.6 DOTA for Kerlink Wirnet Station.\n\t\t\tAntennaGainDesc: \"Antenna gain, in dBi\",\n\t\t\tInsertionLoss: 0.5,\n\t\t\tInsertionLossDesc: \"Insertion loss, in dBi\",\n\t\t},\n\t\tGatewayConf: gatewayConf,\n\t}, nil\n}", "func NewMit-raToken(address common.Address, backend bind.ContractBackend) (*Mit-raToken, error) {\n\tcontract, err := bindMit-raToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mit-raToken{Mit-raTokenCaller: Mit-raTokenCaller{contract: contract}, Mit-raTokenTransactor: Mit-raTokenTransactor{contract: contract}, Mit-raTokenFilterer: Mit-raTokenFilterer{contract: contract}}, nil\n}", "func MustNew(glabel string, flags int) *GlvlStruct {\n\tg, _ := newll(glabel, flags, LflagsDef, nil, true)\n\treturn g\n}", "func NewRaft(config *ClusterConfig, thisServerId int, commitCh chan raft.LogEntry) (*Raft, error) {\n\traft := new(Raft)\n\traft.Init(config, thisServerId)\n\treturn raft, nil\n}", "func New() (*TimeLord, error) {\n\tglobalMut.Lock()\n\tdefer globalMut.Unlock()\n\tif timeLordExists {\n\t\treturn nil, fmt.Errorf(\"timelord.New has already been called (only one TimeLord can be created at a time)\")\n\t}\n\ttl := &TimeLord{}\n\ttl.warp()\n\ttimeLordExists = true\n\treturn tl, nil\n}", "func NewRosetteFormulaFromMarshalObject(marshalObject MarshaledFormula) *Formula {\n\tterms := []*exponential.RosetteFriezeTerm{}\n\tfor _, termMarshal := range marshalObject.Terms {\n\t\tnewTerm := exponential.NewTermFromMarshalObject(*termMarshal)\n\t\tterms = append(terms, newTerm)\n\t}\n\treturn &Formula{Terms: terms}\n}", "func LABLMake() Chunk { return LABL() }", "func NewLmc(address common.Address, backend bind.ContractBackend) (*Lmc, error) {\n\tcontract, err := bindLmc(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Lmc{LmcCaller: LmcCaller{contract: contract}, LmcTransactor: LmcTransactor{contract: contract}, LmcFilterer: LmcFilterer{contract: contract}}, nil\n}", "func (llrb *LLRB) Clone(name string) *LLRB {\n\tif !llrb.lock() {\n\t\treturn nil\n\t}\n\n\tnewllrb := NewLLRB(llrb.name, llrb.setts)\n\tnewllrb.llrbstats = llrb.llrbstats\n\tnewllrb.h_upsertdepth = llrb.h_upsertdepth.Clone()\n\tnewllrb.seqno = llrb.seqno\n\n\tnewllrb.setroot(newllrb.clonetree(llrb.getroot()))\n\n\tllrb.unlock()\n\treturn newllrb\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// Your Code Here (2A).\n\tr := &Raft{\n\t\tid: c.ID,\n\t\tPrs: make(map[uint64]*Progress),\n\t\tvotes: make(map[uint64]bool),\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\tRaftLog: newLog(c.Storage),\n\t}\n\thardSt, confSt, _ := r.RaftLog.storage.InitialState()\n\tif c.peers == nil {\n\t\tc.peers = confSt.Nodes\n\t}\n\tlastIndex := r.RaftLog.LastIndex()\n\tfor _, peer := range c.peers {\n\t\tif peer == r.id {\n\t\t\tr.Prs[peer] = &Progress{Next: lastIndex + 1, Match: lastIndex}\n\t\t} else {\n\t\t\tr.Prs[peer] = &Progress{Next: lastIndex + 1}\n\t\t}\n\t}\n\tr.becomeFollower(0, None)\n\tr.randomElectionTimeout = r.electionTimeout + rand.Intn(r.electionTimeout)\n\tr.Term, r.Vote, r.RaftLog.committed = hardSt.GetTerm(), hardSt.GetVote(), hardSt.GetCommit()\n\tif c.Applied > 0 {\n\t\tr.RaftLog.applied = c.Applied\n\t}\n\treturn r\n}", "func New(randomized bool) *RF1R {\n\tres := RF1R{}\n\n\tif randomized {\n\t\tres.hasher1 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t\tres.hasher2 = func(b []byte) uint64 { return siphash.Hash(2, 3, b) }\n\t} else {\n\t\tres.hasher1 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t\tres.hasher2 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t}\n\n\treturn &res\n}", "func newTimerBuilder(timeSource clock.TimeSource) *timerBuilder {\n\treturn &timerBuilder{\n\t\tuserTimers: timers{},\n\t\tpendingUserTimers: make(map[string]*persistence.TimerInfo),\n\t\tactivityTimers: timers{},\n\t\tpendingActivityTimers: make(map[int64]*persistence.ActivityInfo),\n\t\tlocalSeqNumGen: &localSeqNumGenerator{counter: 1},\n\t\ttimeSource: timeSource,\n\t}\n}", "func (a *Lisp_address) lisp_make_address(iid int, addr []byte) {\n\ta.instance_id = iid\n\ta.address = addr\n\ta.mask_len = len(a.address) * 8\n\ta.mask_address = net.CIDRMask(a.mask_len, len(a.address) * 8)\n}", "func NewMsgRagnarok(tx ObservedTx, blockHeight int64, signer cosmos.AccAddress) MsgRagnarok {\n\treturn MsgRagnarok{\n\t\tTx: tx,\n\t\tBlockHeight: blockHeight,\n\t\tSigner: signer,\n\t}\n}", "func CloneMPT(mpt MerklePatriciaTrieI) *MerklePatriciaTrie {\n\tclone := NewMerklePatriciaTrie(mpt.GetNodeDB(), mpt.GetVersion(), mpt.GetRoot())\n\treturn clone\n}", "func NewRoundRobin() consensus.LeaderRotation {\n\treturn &roundRobin{}\n}", "func NewRingMock(t minimock.Tester) *RingMock {\n\tm := &RingMock{t: t}\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.DecryptMock = mRingMockDecrypt{mock: m}\n\tm.DecryptMock.callArgs = []*RingMockDecryptParams{}\n\n\tm.EncryptMock = mRingMockEncrypt{mock: m}\n\tm.EncryptMock.callArgs = []*RingMockEncryptParams{}\n\n\treturn m\n}", "func New() helper.Moduler {\n\treturn &Moduler{}\n}", "func New() helper.Moduler {\n\treturn &Moduler{}\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\ts := c.Storage\n\thardStatus, confStatus, err := s.InitialState()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tif c.peers == nil {\n\t\tc.peers = confStatus.Nodes\n\t}\n\n\tnodes := c.peers\n\t// init vote to false\n\tvotes := make(map[uint64]bool)\n\tfor _, nodeId := range nodes {\n\t\tvotes[nodeId] = false\n\t}\n\n\treturn &Raft{\n\t\tid: c.ID,\n\t\tTerm: hardStatus.Commit,\n\t\tVote: hardStatus.Vote,\n\t\tRaftLog: newLog(c.Storage),\n\t\tPrs: nil,\n\t\t// init as a follower\n\t\tState: StateFollower,\n\t\tvotes: nil,\n\t\tmsgs: nil,\n\t\tLead: None,\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\trandomElectionTimeout: randomTimeout(c.ElectionTick),\n\t\theartbeatElapsed: 0,\n\t\telectionElapsed: 0,\n\t\tleadTransferee: 0,\n\t\tPendingConfIndex: 0,\n\t\tnodes: nodes,\n\t}\n}", "func NewRobertaForMultipleChoice(p *nn.Path, config *bert.BertConfig) *RobertaForMultipleChoice {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, 1, nn.DefaultLinearConfig())\n\n\treturn &RobertaForMultipleChoice{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func NewLllnumeric(val string) *Lllnumeric {\n\treturn &Lllnumeric{val}\n}", "func BuildRTMToken(appID string, appCertificate string, userAccount string, privilegeExpiredTs time.Time) (string, error) {\n\ttoken := NewAccessTokenStrUID(appID, appCertificate, userAccount, \"\")\n\ttoken.AddPrivilege(PrivilegeLoginRtm, privilegeExpiredTs)\n\treturn token.Build()\n}", "func NewLlnumeric(val string) *Llnumeric {\n\treturn &Llnumeric{val}\n}", "func NewLlnumeric(val string) *Llnumeric {\n\treturn &Llnumeric{val}\n}", "func newNGram(n int) *nGram {\n\tngram := new(nGram)\n\tngram.nValue = n\n\treturn ngram\n}", "func NewMaskedTextField(width int, value []rune, validateFn func(string) (string, bool)) *MaskedTextField {\n\treturn &MaskedTextField{\n\t\twidth: width,\n\t\tcursorX: -1,\n\t\tvalidFn: validateFn,\n\t}\n}", "func NewAsyncBR(t mockConstructorTestingTNewAsyncBR) *AsyncBR {\n\tmock := &AsyncBR{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New(r io.Reader, buflen int, secure bool, f EditFn) *T {\n\tif buflen < 1 {\n\t\tbuflen = 4096\n\t}\n\tif f == nil {\n\t\tf = BasicLineEdit\n\t}\n\tbuf := make([]byte, buflen+1)\n\treturn &T{\n\t\teditFn: f,\n\t\tsrc: r,\n\t\trbuf: buf[:1],\n\t\tbuf: buf[1:],\n\t\tsecure: secure,\n\t}\n}", "func NewMit-raTokenCaller(address common.Address, caller bind.ContractCaller) (*Mit-raTokenCaller, error) {\n\tcontract, err := bindMit-raToken(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mit-raTokenCaller{contract: contract}, nil\n}", "func newPRMMatchExact() *prmMatchExact {\n\treturn &prmMatchExact{prmCommon{Type: prmTypeMatchExact}}\n}", "func newRouteManager(wg *sync.WaitGroup, logRouteChanges bool, syncPeriod time.Duration) *routeManager {\n\treturn &routeManager{\n\t\tlogRouteChanges: logRouteChanges,\n\t\tsyncPeriod: syncPeriod,\n\t\tstore: make(map[string]routesPerLink),\n\t\taddRouteCh: make(chan routesPerLink, 5),\n\t\tdelRouteCh: make(chan routesPerLink, 5),\n\t\twg: wg,\n\t}\n}", "func NewRobertaForQuestionAnswering(p *nn.Path, config *bert.BertConfig) *RobertaForQuestionAnswering {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForQuestionAnswering{\n\t\troberta: roberta,\n\t\tqaOutputs: qaOutputs,\n\t}\n}", "func NewBuilder(buffer []byte) *Builder {\n\treturn &Builder{\n\t\tresult: buffer,\n\t}\n}", "func newTruck(mk, mdl string) *truck {\n\treturn &truck{vehicle: vehicle{mk, mdl}}\n}", "func newReconciledMTAdapterRoleBinding() *rbacv1.RoleBinding {\n\treturn NewMTAdapterRoleBinding(newReconciledServiceAccount())()\n}", "func NewLsystem(Axiom, RuleLeft, RuleRight string, Result []string) *Lsystem {\n\tl := &Lsystem{}\n\tl.Axiom = Axiom\n\tl.RuleLeft = RuleLeft\n\tl.RuleRight = RuleRight\n\tl.Result = Result\n\n\treturn l\n}", "func NewRumourMessage(id uint32, txt, origin string) *RumourMessage {\n\trumour := &RumourMessage{\n\t\tOrigin: origin,\n\t\tID: id,\n\t\tText: txt,\n\t}\n\treturn rumour\n}", "func makeMockRafts(mkcl *mock.MockCluster,logFileName string, hbTimeout int, timeout int) ([]*RaftNode, error){\r\n\trand.Seed(3587) \r\n\ttime.Sleep(time.Millisecond)\r\n\trafts := make([]*RaftNode, len(mkcl.Servers))\r\n\tfor id, mksrvr := range mkcl.Servers {\r\n\t\tcurrLogFileName := logFileName + \"_\" + fmt.Sprintf(\"%v\",id) \r\n\t\tos.RemoveAll(currLogFileName)\r\n\t\tos.RemoveAll(currLogFileName + \"_state\")\r\n\t\tnode , err := NewMockRN(FOLLOWER, mksrvr, currLogFileName, hbTimeout, timeout)\r\n\t\tif err != nil{\r\n\t\t\tfmt.Fprintln(os.Stderr,err)\r\n\t\t\treturn rafts, err\r\n\t\t}\r\n\t\trafts[id-1] = node\r\n\t}\r\n\treturn rafts, nil\r\n}", "func BuildMrSignerBlacklist(allowTestKeys bool) {\n\tif !allowTestKeys {\n\t\tfor _, v := range []string{\n\t\t\tsgx.FortanixDummyMrSigner.String(),\n\t\t} {\n\t\t\tvar signer sgx.MrSigner\n\t\t\tif err := signer.UnmarshalHex(v); err != nil {\n\t\t\t\tpanic(\"ias/avr: failed to decode MRSIGNER: \" + v)\n\t\t\t}\n\t\t\tmrSignerBlacklist[signer] = true\n\t\t}\n\t}\n}", "func RemindLector(t *store.Task, b *bot.Bot) {\n\tlog.Info(\"got new reminder lector:\", t)\n\tif err := t.TakeTask(); err != nil {\n\t\tlog.Errorf(\"failed to take task %d error:%s\", t.ID, err)\n\t\tif err := t.ReleaseTask(); err != nil {\n\t\t\tlog.Errorf(\"failed to release task %d error:%s\", t.ID, err)\n\t\t}\n\t\treturn\n\t}\n\tr, err := t.LoadReminderLecture()\n\tif err != nil {\n\t\tlog.Errorf(\"failed to load reminder lecture of task %d error:%s\", t.ID, err)\n\t\tif err := t.ReleaseTask(); err != nil {\n\t\t\tlog.Errorf(\"failed to release task %d error:%s\", t.ID, err)\n\t\t}\n\t\treturn\n\t}\n\tl, err := r.LoadLecture()\n\tif err != nil {\n\t\tlog.Errorf(\"failed to load lecture of task %d error:%s\", t.ID, err)\n\t\tif err := t.ReleaseTask(); err != nil {\n\t\t\tlog.Errorf(\"failed to release task %d error:%s\", t.ID, err)\n\t\t}\n\t\treturn\n\t}\n\tif l.Description != \"\" {\n\t\tif err = t.FinishTask(); err != nil {\n\t\t\tlog.Errorf(\"failed to finish task %d error:%s\", t.ID, err)\n\t\t}\n\t\treturn\n\t}\n\t// skip unregistered users (bot hasn't spoken with them yet)\n\tif l.Lector.TGUserID == 0 {\n\t\tlog.Info(fmt.Sprintf(\"reminder skip the user %d since it doesn't have tg id\", l.Lector.ID))\n\t\treturn\n\t}\n\tb.SendText(int64(l.Lector.TGUserID), lang.TEMPLATE_LECTURE_DESCRIPTION_REMINDER)\n\t// Udate task with new execution time and attempts\n\tif err = r.PostponeTask(t.ID); err != nil {\n\t\tlog.Errorf(\"failed to postpone task %d error:%s\", t.ID, err)\n\t\treturn\n\t}\n\tlog.Info(t)\n}", "func NewRobertaClassificationHead(p *nn.Path, config *bert.BertConfig) *RobertaClassificationHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\tnumLabels := int64(len(config.Id2Label))\n\toutProj := nn.NewLinear(p.Sub(\"out_proj\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\n\treturn &RobertaClassificationHead{\n\t\tdense: dense,\n\t\tdropout: dropout,\n\t\toutProj: outProj,\n\t}\n}", "func NewCreateanewLnpCarrierRequest(server string, body CreateanewLnpCarrierJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewCreateanewLnpCarrierRequestWithBody(server, \"application/json\", bodyReader)\n}", "func (m *Message) LRL() (*LRL, error) {\n\tps, err := m.Parse(\"LRL\")\n\tpst, ok := ps.(*LRL)\n\tif ok {\n\t\treturn pst, err\n\t}\n\treturn nil, err\n}", "func (env *env) newTestHelperCreateLgr(id string, t *testing.T) *testhelper {\n\tgenesisBlk, err := constructTestGenesisBlock(id)\n\tassert.NoError(t, err)\n\tlgr, err := env.ledgerMgr.CreateLedger(id, genesisBlk)\n\tassert.NoError(t, err)\n\tclient, committer, verifier := newClient(lgr, id, t), newCommitter(lgr, t), newVerifier(lgr, t)\n\treturn &testhelper{client, committer, verifier, lgr, id, assert.New(t)}\n}", "func newTPMManagerBinary(r CmdRunner) *tpmManagerBinary {\n\treturn &tpmManagerBinary{r}\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func NewNormalizer() *Normalizer {\n\treturn &Normalizer{\n\t\ttrans: transform.Chain(norm.NFD, runes.Remove(mn), norm.NFC),\n\t}\n}", "func New() *Motto {\n return &Motto{otto.New(), make(map[string]ModuleLoader), nil, make(map[string]otto.Value)}\n}", "func NewRoundRobin(hs *hotstuff.HotStuff, termLength int, schedule []hotstuff.ReplicaID, timeout time.Duration) *RoundRobin {\n\treturn &RoundRobin{\n\t\tHotStuff: hs,\n\t\ttermLength: termLength,\n\t\tschedule: schedule,\n\t\ttimeout: timeout,\n\t\tresetTimer: make(chan struct{}),\n\t}\n}", "func NewRaft(conf *Config, store Store, logs LogStore, peerStore PeerStore, fsm FSM, trans Transport) (*Raft, error) {\n\t// Try to restore the current term\n\tcurrentTerm, err := store.GetUint64(keyCurrentTerm)\n\tif err != nil && errors.Is(err, ErrNotFound) {\n\t\treturn nil, fmt.Errorf(\"failed to load current term: %w\", err)\n\t}\n\n\tlastLog, err := logs.LastIndex()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to find last log: %w\", err)\n\t}\n\n\t// Construct the list of peers that excludes us\n\tlocalAddr := trans.LocalAddr()\n\tpeers, err := peerStore.Peers()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"peer store failed: %w\", err)\n\t}\n\tpeers = excludePeer(peers, localAddr)\n\n\tr := &Raft{\n\t\tconf: conf,\n\t\tstable: store,\n\t\tlogs: logs,\n\t\tfsm: fsm,\n\t\tshutdownCh: make(chan struct{}),\n\t\tlogE: log.New(os.Stdout, \"[ERROR]\", log.LstdFlags|log.Lshortfile),\n\t\tlogW: log.New(os.Stdout, \"[WARN]\", log.LstdFlags|log.Lshortfile),\n\t\tlogD: log.New(os.Stdout, \"[DEBUG]\", log.LstdFlags|log.Lshortfile),\n\t\tcommitCh: make(chan commitTuple, 128),\n\t\tapplyCh: make(chan *DeferLog),\n\t\trpcCh: trans.Consume(),\n\t\tpeers: peers,\n\t\tpeerStore: peerStore,\n\t\ttrans: trans,\n\t\tlocalAddr: localAddr,\n\t}\n\t// Initialize as a follower\n\tr.setState(Follower)\n\n\t// Restore the current term and the last log\n\t_ = r.setCurrentTerm(currentTerm)\n\tr.setLastLogIndex(lastLog)\n\n\tgo r.run()\n\tgo r.runFSM()\n\treturn r, nil\n}", "func New(o *Options) (Matcher, error) {\n\t// creates data clients\n\tdataClients, err := createDataClients(o.RoutesFile)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trouting := createRouting(dataClients, o)\n\n\treturn &matcher{\n\t\trouting,\n\t}, nil\n}", "func New(opt *Option) *Masketeer {\n\tif opt == nil {\n\t\topt = &Option{}\n\t}\n\n\treturn &Masketeer{\n\t\topt: opt,\n\t}\n}", "func New(pN string, b uint32, p string) *Rfm12b {\n\treturn &Rfm12b{\n\t\tportName: pN, baud: b, loggerPath: p,\n\t\tchOut: make(chan []byte), ChIn: make(chan interface{}),\n\t\tlogger: logger.New(p),\n\t}\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\trf.id = string(rune(me + 'A'))\n\n\t// Your initialization code here (2A, 2B, 2C).\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\n\tgo rf.startElectionProcess()\n\n\tgo rf.startLocalApplyProcess(applyCh)\n\n\treturn rf\n}", "func Make(peers []*labrpc.ClientEnd, me int,\n\tpersister *Persister, applyCh chan ApplyMsg) *Raft {\n\trf := &Raft{}\n\trf.peers = peers\n\trf.persister = persister\n\trf.me = me\n\n\t// Your initialization code here.\n\trf.state = FOLLOWER\n\trf.applyChan = applyCh\n\n\trf.currentTerm = 0\n\trf.votedFor = -1\n\trf.log = make([]LogEntry, 0)\n\trf.commitIndex = -1\n\trf.lastApplied = -1\n\trf.nextIndex = make([]int, len(peers))\n\trf.matchIndex = make([]int, len(peers))\n\n\t// initialize from state persisted before a crash\n\trf.readPersist(persister.ReadRaftState())\n\trf.timer = time.NewTimer(properTimeDuration(rf.state))\n\t//repeat\n\tgo func() {\n\t\tfor {\n\t\t\t<-rf.timer.C\n\t\t\trf.solveTimeOut()\n\t\t}\n\t}()\n\n\treturn rf\n}", "func NewMockReminds(ctrl *gomock.Controller) *MockReminds {\n\tmock := &MockReminds{ctrl: ctrl}\n\tmock.recorder = &MockRemindsMockRecorder{mock}\n\treturn mock\n}", "func NewLoan(amount int64, rate float64, durationInMonths int) *Loan {\n\tif amount <= 0 || durationInMonths <= 0 {\n\t\tpanic(\"Amount and durationInMonths must be positive.\")\n\t}\n\tpayment := solveForPayment(amount, rate/12.0, durationInMonths)\n\treturn &Loan{amount, rate, durationInMonths, payment}\n}", "func newRLockedFile(lkFile *LockedFile) (*RLockedFile, error) {\n\tif lkFile == nil {\n\t\treturn nil, os.ErrInvalid\n\t}\n\n\treturn &RLockedFile{\n\t\tLockedFile: lkFile,\n\t\trefs: 1,\n\t}, nil\n}", "func NewRBACTransactor(address common.Address, transactor bind.ContractTransactor) (*RBACTransactor, error) {\n\tcontract, err := bindRBAC(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBACTransactor{contract: contract}, nil\n}", "func NewCreateanewNcosLnpCarrierRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/ncoslnpcarriers\")\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}", "func New(localAddress raft.ServerAddress, dialOptions []grpc.DialOption) *Manager {\n\treturn &Manager{\n\t\tlocalAddress: localAddress,\n\t\tdialOptions: dialOptions,\n\n\t\trpcChan: make(chan raft.RPC),\n\t\tconnections: map[raft.ServerID]*conn{},\n\t}\n}", "func (t *DemoChaincode) createLoanForm(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments, Expecting 1\")\n\t}\n\n\tfmt.Println(\"- start create loan form\")\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\n\tformBlob := []byte(args[0])\n\n\tvar loanForm LoanForm\n\terr := json.Unmarshal(formBlob, &loanForm)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tfmt.Printf(\"loan form %+v\", loanForm)\n\n\tloanFormJSONasBytes, err := json.Marshal(&loanForm)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\terr = stub.PutState(loanForm.Name, loanFormJSONasBytes)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tfmt.Println(\"- end create loan form\")\n\n\treturn shim.Success(nil)\n}", "func NewMontrealTrip(weight float32, deadline int) *Trip {\n trip := Trip{weight: weight, destination: \"Montreal\", deadline: deadline}\n return &trip\n}", "func NewSettlBrkrCode(val string) SettlBrkrCodeField {\n\treturn SettlBrkrCodeField{quickfix.FIXString(val)}\n}", "func (static TransactionCalculator)ReformerRuleByRCRCreatePB(in *Aphro_Room_pb.RCRCreateRequest) (*TCRule) {\n\treturn &TCRule{\n\t\tin.Fee,\n\t\tin.Start,\n\t\tin.End,\n\t\tin.Interval,\n\t\tin.IntervalUnit,\n\t\tin.MerchantID,\n\t\tin.RoomID,\n\t\t0,\n\t\tin.Flag,\n\t\tin.RcrID,\n\t\t0,\n\t\t0,\n\t}\n}", "func NewLocalLedger() *LocalLedger {\n\tlog.Printf(\"BLURB-LEDGER: Initializing\")\n\treturn &LocalLedger{\n\t\tledger: sync.Map{},\n\t\tbidCounter: 0,\n\t\tbidMutex: sync.Mutex{},\n\n\t\tfeeds: struct {\n\t\t\tcache sync.Map\n\t\t\tlength int\n\t\t\tblurbsPerUser int\n\t\t}{\n\t\t\tcache: sync.Map{},\n\t\t\tlength: 100,\n\t\t\tblurbsPerUser: 10,\n\t\t},\n\t}\n}", "func newSMTPBufferedReader(rd io.Reader) *smtpBufferedReader {\n\talr := newAdjustableLimitedReader(rd, CommandLineMaxLength)\n\ts := &smtpBufferedReader{bufio.NewReader(alr), alr}\n\treturn s\n}" ]
[ "0.56021535", "0.51360244", "0.5057678", "0.47741595", "0.46441257", "0.46423316", "0.4629943", "0.45565084", "0.4553068", "0.45473307", "0.4484458", "0.44752312", "0.44710892", "0.44612712", "0.4439623", "0.44129133", "0.43823466", "0.43730444", "0.43224025", "0.43211555", "0.43195608", "0.43165067", "0.4309962", "0.43000418", "0.42986447", "0.42979044", "0.42469543", "0.4243042", "0.4236665", "0.42340136", "0.4221035", "0.4219449", "0.4212101", "0.42111766", "0.4203409", "0.42020756", "0.4192194", "0.4191815", "0.41898102", "0.41857776", "0.4183962", "0.41691813", "0.41687134", "0.41506526", "0.4149658", "0.41414717", "0.41209742", "0.41155392", "0.41081595", "0.41081595", "0.4107203", "0.41018575", "0.40934962", "0.4087711", "0.40833503", "0.40822873", "0.40822873", "0.40704194", "0.4056078", "0.404716", "0.40461144", "0.40459174", "0.40335023", "0.40312636", "0.40308988", "0.40305692", "0.40273398", "0.40209988", "0.40199313", "0.40149817", "0.40147662", "0.40143228", "0.40138924", "0.40137872", "0.40132713", "0.40082198", "0.4007081", "0.40016356", "0.40003666", "0.40002003", "0.39908418", "0.39807004", "0.39768755", "0.39760387", "0.3970418", "0.396897", "0.39688727", "0.39635932", "0.39495906", "0.3942996", "0.3941734", "0.394124", "0.39331442", "0.39326903", "0.39309677", "0.39306253", "0.39265466", "0.39252377", "0.39176747", "0.3914992" ]
0.81801337
0
Load loads model from file or model name. It also updates default configuration parameters if provided. This method implements `PretrainedModel` interface.
func (mlm *RobertaForMaskedLM) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error { var urlOrFilename string // If modelName, infer to default configuration filename: if modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok { urlOrFilename = modelFile } else { // Otherwise, just take the input urlOrFilename = modelNameOrPath } cachedFile, err := util.CachedPath(urlOrFilename) if err != nil { return err } vs := nn.NewVarStore(device) p := vs.Root() mlm.roberta = bert.NewBertModel(p.Sub("roberta"), config.(*bert.BertConfig)) mlm.lmHead = NewRobertaLMHead(p.Sub("lm_head"), config.(*bert.BertConfig)) err = vs.Load(cachedFile) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load(fileName string, src interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tdecoder := gob.NewDecoder(file)\n\t\tif err = decoder.Decode(src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Restore parameters\n\tswitch src.(type) {\n\tcase Model:\n\t\tmodel := src.(Model)\n\t\tmodel.SetParams(model.GetParams())\n\tdefault:\n\t\treturn errors.New(\"the file is not a model dump\")\n\t}\n\treturn nil\n}", "func (mc *RobertaForMultipleChoice) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmc.dropout = util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, 1, nn.DefaultLinearConfig())\n\tmc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sc *RobertaForSequenceClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tsc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tsc.classifier = NewRobertaClassificationHead(p.Sub(\"classifier\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Model) Load(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\tif err := json.Unmarshal(data, m); err != nil {\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\treturn nil\n}", "func Load(modelArchive string, framework Framework, flags ModelFlags) (*Model, error) {\n\tf, _ := os.Open(modelArchive)\n\tdefer f.Close()\n\tvar outDir string\n\tif fi, err := f.Stat(); err == nil && fi.IsDir() {\n\t\toutDir = modelArchive\n\t} else if err == nil && !fi.IsDir() {\n\t\ttmpDir := os.TempDir()\n\t\toutDir = filepath.Join(tmpDir, utils.PseudoUuid())\n\t\tif err := utils.Unzip(modelArchive, outDir); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to extract model archive: %v\", err)\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s does not exist\", modelArchive)\n\t}\n\n\tmodelFilename := filepath.Join(outDir, \"saved_model.pb\")\n\tif _, err := os.Stat(modelFilename); err != nil {\n\t\t// This if is here for when we can read pbtxt files\n\t\tif _, err2 := os.Stat(modelFilename + \"txt\"); err2 == nil {\n\t\t\tmodelFilename = modelFilename + \"txt\"\n\t\t\treturn nil, errors.New(\"Currently loading saved_model.pbtxt is not supported\")\n\t\t\t//comment the return when we can read pbtxt\n\t\t} else {\n\t\t\treturn nil, errors.New(\"saved_model.pb does not exist\")\n\t\t}\n\t}\n\n\tflags.ModelPath = outDir\n\tflags.ModelFile = modelFilename\n\tvar model Model\n\terr := framework.Load(&model, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &model, nil\n}", "func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tdropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tnumLabels := int64(len(config.(*bert.BertConfig).Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\ttc.roberta = roberta\n\ttc.dropout = dropout\n\ttc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (am *AssetManager) LoadModel(name, iname string) {\n\tif strings.Contains(name, \".obj\") {\n\t\tam.Models[iname] = NewWavefrontModelFromFile(am.modelsDir + name)\n\t} else {\n\t\tlog.Fatal(\"cannot find \" + name)\n\t}\n}", "func (qa *RobertaForQuestionAnswering) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\tqa.roberta = roberta\n\tqa.qaOutputs = qaOutputs\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(model interface{}, provider Provider, strict bool) error {\n\treturn load(model, provider, strict)\n}", "func LoadModel(r io.Reader) (Model, error) {\n\tdec := json.NewDecoder(r)\n\tvar m Model\n\tif err := dec.Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\tm.setWeightVec()\n\treturn m, nil\n}", "func Load(modelName string) (r *pb.TextResponse, err error) {\n\tif modelName == \"\" {\n\t\tmodelName = defaultModel\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tr, err = grpcClient.LoadModel(ctx, &pb.TextRequest{Text: modelName})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}", "func (s *DataStore) Load() error {\n\tfile, err := os.Open(s.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = json.NewDecoder(file).Decode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadModelFile(path string) (Model, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fp.Close()\n\treturn LoadModel(fp)\n}", "func Load(filename string) (*SvmModel, error) {\n\n\tcfn := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cfn))\n\n\tmdl := C.svm_load_model(cfn)\n\tif mdl == nil {\n\t\treturn nil, SvmError{Message: fmt.Sprintf(\"unable to load model file: %s\", filename)}\n\t}\n\n\treturn &SvmModel{object: mdl}, nil\n}", "func (wrapper *TvmWrapper) LoadModel(modelParam *ModelParam) (*moduleInfo, error) {\n\tdefer runtime.GC()\n\n\t// debug model parameters\n\tfmt.Print(modelParam.DebugStr())\n\n\t// load module library\n\tfmt.Print(\"start to load module library...\\n\")\n\tmodLibP, err := gotvm.LoadModuleFromFile(modelParam.ModelLibPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// read module json file\n\tfmt.Print(\"start to read module json file...\\n\")\n\tbytes, err := ioutil.ReadFile(modelParam.ModelJSONPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tmodJsonStr := string(bytes)\n\n\t// create graph module of tvm\n\tfmt.Print(\"start to create graph module of tvm...\\n\")\n\tfuncp, err := gotvm.GetGlobalFunction(\"tvm.graph_runtime.create\")\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t\treturn nil, err\n\t}\n\t// graph_runtime.create\n\t// arg[0] : model json text\n\t// arg[1] : model library\n\t// arg[2] : device type (ex. KDLCPU, KDLGPU...)\n\t// arg[3] : device id\n\tgraphrt, err := funcp.Invoke(modJsonStr, modLibP, wrapper.config.DeviceType, (int64)(0))\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tgraphmod := graphrt.AsModule()\n\n\t// import params to graph module\n\tfmt.Print(\"start to import params to graph module...\\n\")\n\tbytes, err = ioutil.ReadFile(modelParam.ModelParamsPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tfuncp, err = graphmod.GetFunction(\"load_params\")\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\t_, err = funcp.Invoke(bytes)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// create module information\n\tfmt.Print(\"start to create module information...\\n\")\n\tinfo := newModuleInfo(graphmod, modelParam.InputShape, modelParam.OutputShape)\n\treturn info, nil\n}", "func loadModel(modelName string) (multilayer.MultiLayerPerceptron, error) {\n\tf, err := os.Open(\"models/\" + modelName + \".model.gob\")\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, fmt.Errorf(\"failed opening model: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\n\tnn := multilayer.MultiLayerPerceptron{}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\terr = nn.UnmarshalBinary(data)\n\treturn nn, err\n}", "func (t *TOMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif t.Reader != nil {\n\t\tr = t.Reader\n\t} else if t.Path != \"\" {\n\t\tfile, err := getConfig(t.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tif _, err := toml.DecodeReader(r, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (env *Environment) LoadExistingModel(m string) *text.NaiveBayes {\n\t// get the classifier definition to make sure it is well defined\n\tclf := env.GetClassifierDefinition(m)\n\tclf.panicErrors()\n\n\tstreamChan := make(chan base.TextDatapoint, clf.TextChannelSize)\n\tmodel := clf.getModel(streamChan)\n\terr := model.RestoreFromFile(env.baseModelPath(clf.ModelOut))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn model\n}", "func Load(fileName string) (*openapi3.Swagger, error) {\n\tmodel, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = model.Validate(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"Loaded OpenAPI 3 Specification file:\", fileName)\n\treturn model, nil\n}", "func Load(r io.Reader) error {\n\treturn DefaultInstance.Load(r)\n}", "func (l *OptionalTOMLLoader) Load(s interface{}) error {\n\tif _, err := os.Stat(l.Path); err == nil {\n\t\treturn l.TOMLLoader.Load(s)\n\t}\n\treturn nil\n}", "func (e *CachedEnforcer) LoadModel() error {\n\tif e.autoClear {\n\t\tdefer e.InvalidateCache()\n\t}\n\treturn e.base.LoadModel()\n}", "func (c *IntentClassifier) Load(filePath string) error {\n\tlog.Printf(\"Loading Classifier from %s...\", filePath)\n\tmeta := persist.Load(filePath)\n\t//get the classifier current meta data\n\tname, version := c.getMeta()\n\tif meta.Name != name {\n\t\treturn fmt.Errorf(\"This file doesn't contain a KNearestNeighbors classifier\")\n\t}\n\tif meta.Version != version {\n\t\treturn fmt.Errorf(\"Can't understand this file format\")\n\t}\n\n\tdecoder := gob.NewDecoder(bytes.NewBuffer(meta.Data))\n\terr := decoder.Decode(&c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding RNN checkpoint file: %s\", err)\n\t}\n\n\tcheckpointFile = filePath\n\treturn nil\n}", "func (k *KMP) Load(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(b, k)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid load format, %s\", format)\n\t}\n\treturn err\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(filename string) (*Params, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar params Params\n\tif err := json.Unmarshal(file, &params); err != nil {\n\t\tlog.Printf(\"failed to parse %s: %s\", file, string(file))\n\t\treturn nil, err\n\t}\n\treturn &params, nil\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func (lm *LocalMeta) Load() error {\n\t// initialize gset\n\tvar err error\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, \"\")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfile, err := os.Open(lm.filename)\n\tif err != nil && !os.IsNotExist(errors.Cause(err)) {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif os.IsNotExist(errors.Cause(err)) {\n\t\treturn nil\n\t}\n\tdefer file.Close()\n\n\t_, err = toml.DecodeReader(file, lm)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, lm.BinlogGTID)\n\treturn errors.Trace(err)\n}", "func InitModel(modelDir string, modelFile string) *TfModel {\n\tmodelpath := filepath.Join(modelDir, modelFile)\n\tmodel, err := ioutil.ReadFile(modelpath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Construct an in-memory graph from the serialized form.\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toperations := graph.Operations()\n\tfor _, op := range operations {\n\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t}\n\t// Create a session for inference over graph.\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &TfModel{Model: &tf.SavedModel{Graph: graph, Session: session}}\n}", "func (e *Definition) Load(path, entity string) error {\n\n\tfullPath := filepath.Join(path, entity)\n\n\tb, err := ioutil.ReadFile(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontent := string(b)\n\te.json = jsonutil.NewFromString(content)\n\te.byteRead = 0\n\n\ts, err := schema.Read(e)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read schema: %s\", err)\n\t\treturn err\n\t}\n\n\te.schema = s\n\tv := validator.New(s)\n\te.validator = v\n\treturn nil\n}", "func Load(reader io.Reader, configuration interface{}) error {\n\tif err := FromYAML(reader, configuration); err != nil {\n\t\treturn err\n\t}\n\treturn FromEnv(configuration)\n}", "func Init(path string, tags []string) *TfModel {\n\tmodel, err := tf.LoadSavedModel(path, tags, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading Saved Model:%v\\n\", err.Error())\n\t\treturn nil\n\t}\n\toperations := model.Graph.Operations()\n\tfor _, op := range operations {\n\t\tname := op.Name()\n\t\tif strings.HasPrefix(name, \"sentence\") || strings.HasPrefix(name, \"dropout\") || strings.HasPrefix(name, \"inference\") {\n\t\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t\t}\n\t}\n\tlog.Println(\"op loading finished\")\n\treturn &TfModel{Model: model}\n}", "func Load(filename string, v interface{}) {\n\tParse(read(filename), v)\n}", "func (trm *TrmConfig) Load(pathTrm, pathVoice string) {\n\tfmt.Println(\"trm config load\")\n\ttrm.OpenJSON(pathTrm)\n\ttrm.OpenJSON(pathVoice)\n}", "func Load() error {\n\treturn def.Load()\n}", "func LoadModel(args ...interface{}) (*WordModel, error) {\n\tvar arg interface{}\n\tif len(args) == 0 {\n\t\targ = \"https://raw.githubusercontent.com/go-ego/gse/master/data/dict/dictionary.txt\"\n\t} else {\n\t\targ = args[0]\n\t}\n\n\tr, err := readerFromAnything(arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodel := NewWordModel()\n\n\tscanner := bufio.NewScanner(r)\n\tvar words []WordFreq\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, errors.New(\"Error: not enough fields\")\n\t\t}\n\t\tword := fields[0]\n\t\tfreq, _ := strconv.ParseFloat(fields[1], 32)\n\t\tif len([]rune(word)) < 2 {\n\t\t\t//freq = 2\n\t\t}\n\t\twords = append(words, WordFreq{\n\t\t\tWord: word,\n\t\t\tLogProbability: float32((freq)),\n\t\t})\n\t}\n\n\tsort.Slice(words, func(a, b int) bool {\n\t\treturn words[a].Word < words[b].Word\n\t})\n\n\tprev := \"\"\n\tfor _, word := range words {\n\t\tif word.Word == prev {\n\t\t\tcontinue\n\t\t}\n\t\tprev = word.Word\n\t\tmodel.AddWord(word.Word, word.LogProbability)\n\t}\n\n\tmodel.Finish()\n\n\treturn model, nil\n}", "func (self *LSHforest) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn msgpack.Unmarshal(b, self)\n}", "func Load() models.Language {\n\tif models.ConfigFile != \"\" {\n\t\tlangFile = models.ConfigFile\n\t} else {\n\t\tmodels.ConfigFile = langFile\n\t}\n\n\tlang := language.LoadLanguages(langFile)\n\treturn lang\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func Load(config interface{}, configPath string) error {\n\tswitch fileExtension(configPath) {\n\tcase \"yaml\":\n\t\treturn loadYaml(config, configPath)\n\tcase \"json\":\n\t\treturn loadJson(config, configPath)\n\tdefault:\n\t\treturn ero.Newf(\"Can not support load file %s\", configPath)\n\t}\n}", "func (lf LoaderFunc) Load(serverType string) (Input, error) {\n\treturn lf(serverType)\n}", "func Load(v interface{}, loadFrom string) error {\n\tcfg, err := ini.Load(loadFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.NameMapper = ini.TitleUnderscore\n\n\treturn cfg.MapTo(v)\n}", "func Load(filePath string, t Tomler) error {\n\ttomlValue := t.TOMLValue()\n\tvar err error\n\tif _, err = toml.DecodeFile(filePath, tomlValue); err != nil {\n\t\treturn err\n\t}\n\treturn t.FromTOML(tomlValue)\n}", "func (p *BaseProvider) Load() error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (b *baseLoader) Load(ctx context.Context, src *url.URL) (*Schema, error) {\n\t// open IO\n\tvar r io.ReadCloser\n\tswitch src.Scheme {\n\tcase \"file\":\n\t\tvar err error\n\t\tif r, err = os.Open(src.Path); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q from %q: %w\", src.Path, src, err)\n\t\t}\n\tcase \"http\", \"https\":\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, src.String(), nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create request for %q: %w\", src, err)\n\t\t}\n\t\tresp, err := b.client.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed requesting %q: %w\", src, err)\n\t\t}\n\t\tr = resp.Body\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme: %v\", src.Scheme)\n\t}\n\tdefer func() {\n\t\t_ = r.Close()\n\t}()\n\n\t// read and init schema\n\tvar s Schema\n\tif err := json.NewDecoder(r).Decode(&s); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding %q failed: %w\", src, err)\n\t}\n\tif s.ID == nil {\n\t\treturn nil, fmt.Errorf(\"no ID set on %q\", src)\n\t}\n\ts.calculateID()\n\ts.setSrc(src)\n\n\treturn &s, nil\n}", "func Load(path string) (*OBJFile, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\treturn Decode(in)\n}", "func (dto *GetAdapterModelResponse) Load(data base.ModelInterface) error {\n\tm, ok := data.(*model.AdapterModel)\n\tif !ok {\n\t\tlog.Error(\"GetAdapterModelResponse.Load() failed, convert interface failed.\")\n\t\treturn base.ErrorDataConvert\n\t}\n\tdto.GetResponse.Load(&m.Model)\n\tdto.Name = m.Name\n\tdto.Type = m.Type\n\tdto.Capability.Load(m.Capability)\n\treturn nil\n}", "func (l *Loader) LoadObjModel(file string) models.RawModel {\n\tdat, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvertices := make([]mgl32.Vec3, 0)\n\ttextures := make([]mgl32.Vec2, 0)\n\tnormals := make([]mgl32.Vec3, 0)\n\tvar verticesArray []float32\n\tvar texturesArray []float32\n\tvar normalsArray []float32\n\tindicesArray := make([]uint32, 0)\n\tlines := strings.Split(string(dat), \"\\n\")\n\tvar fStart int\n\tfor i, line := range lines {\n\t\tsplited := strings.Split(line, \" \")\n\t\tif len(splited) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := splited[0]\n\t\tif t == \"v\" {\n\t\t\tvertices = append(vertices, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vn\" {\n\t\t\tnormals = append(normals, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vt\" {\n\t\t\ttextures = append(textures, mgl32.Vec2{toFloat(splited[1]), toFloat(splited[2])})\n\t\t}\n\t\tif t == \"f\" {\n\t\t\tfStart = i\n\t\t\ttexturesArray = make([]float32, len(vertices)*2)\n\t\t\tnormalsArray = make([]float32, len(vertices)*3)\n\t\t\tverticesArray = make([]float32, len(vertices)*3)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor i := fStart; i < len(lines); i++ {\n\t\tsplited := strings.Split(lines[i], \" \")\n\t\tif len(splited) == 0 || splited[0] != \"f\" {\n\t\t\tbreak\n\t\t}\n\t\tvertex1 := strings.Split(splited[1], \"/\")\n\t\tvertex2 := strings.Split(splited[2], \"/\")\n\t\tvertex3 := strings.Split(splited[3], \"/\")\n\t\tindicesArray = processVertex(vertex1, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex2, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex3, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t}\n\tcolors := make([]float32, len(normalsArray))\n\tfor i := range colors {\n\t\tcolors[i] = 1\n\t}\n\treturn l.LoadToVAO(verticesArray, texturesArray, indicesArray, normalsArray, colors)\n}", "func (f *Flow) Load(cacheDir string) (err error) {\n\tif f.FlowFile == \"\" {\n\t\treturn nil\n\t}\n\tvar content []byte\n\tswitch getURLType(f.FlowFile) {\n\tcase \"local\":\n\t\tcontent, err = ioutil.ReadFile(f.FlowFile)\n\tcase \"web\":\n\t\tcontent, err = get(cacheDir, f.FlowFile)\n\t// TODO git - including the branch\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognised floe file type: <%s>\", f.FlowFile)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal into a flow\n\tnewFlow := &Flow{}\n\terr = yaml.Unmarshal(content, &newFlow)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up the flow, and copy bits into this flow\n\terr = newFlow.zero()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(newFlow.Name) != 0 {\n\t\tf.Name = newFlow.Name\n\t}\n\tf.ReuseSpace = newFlow.ReuseSpace\n\tif len(newFlow.HostTags) != 0 {\n\t\tf.HostTags = newFlow.HostTags\n\t}\n\tif len(newFlow.ResourceTags) != 0 {\n\t\tf.ResourceTags = newFlow.ResourceTags\n\t}\n\tif len(newFlow.Env) != 0 {\n\t\tf.Env = newFlow.Env\n\t}\n\tif len(newFlow.Tasks) != 0 {\n\t\tf.Tasks = newFlow.Tasks\n\t}\n\t// Pointless overriding triggers - as they are what caused this load\n\treturn nil\n}", "func (s *CommandLineSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.callback != nil {\n\t\treturn s.koanf.Load(posflag.ProviderWithFlag(s.flags, \".\", s.koanf, s.callback), nil)\n\t}\n\n\treturn s.koanf.Load(posflag.Provider(s.flags, \".\", s.koanf), nil)\n}", "func (s *YAMLFileSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.path == \"\" {\n\t\treturn errors.New(\"invalid yaml path source configuration\")\n\t}\n\n\treturn s.koanf.Load(file.Provider(s.path), yaml.Parser())\n}", "func Load(p string) (Spec, error) {\n\tvar spec Spec\n\n\tbuf, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to read file: %s - %w\", p, err)\n\t}\n\n\terr = yaml.Unmarshal(buf, &spec)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to parse spec: %s - %w\", p, err)\n\t}\n\n\tspec.Path = p\n\n\treturn spec, nil\n}", "func Load(config *Config) error {\n\treturn NewLoader(config).Load()\n}", "func Load(path string, target interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn load(formatter, data, target)\n}", "func Load(filepath string, config interface{}) error {\n\tmagazine := make(map[string]interface{})\n\tfileBytes, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := yaml.Unmarshal(fileBytes, &magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagazine = flatten(magazine)\n\tif err := applyEnv(magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagBytes, err := yaml.Marshal(bellows.Expand(magazine))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(magBytes, config)\n}", "func (m *SynapsesPersist) Load() {\n\tdataPath, err := filepath.Abs(m.relativePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teFile, err := os.Open(dataPath + m.file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer eFile.Close()\n\n\tbytes, err := ioutil.ReadAll(eFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(bytes, &m.Synapses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (defaultStorage) Load() error {\n\tpanic(noConfigStorage)\n}", "func (function *Function) Load() (err error) {\n\tdefinition, err := ioutil.ReadFile(function.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfunction.Definition = string(definition)\n\n\treturn\n}", "func Load(state *state.State, driverName string, name string, config map[string]string, logger logger.Logger, volIDFunc func(volType VolumeType, volName string) (int64, error), commonRulesFunc func() map[string]func(string) error) (Driver, error) {\n\t// Locate the driver loader.\n\tdriverFunc, ok := drivers[driverName]\n\tif !ok {\n\t\treturn nil, ErrUnknownDriver\n\t}\n\n\td := driverFunc()\n\terr := d.init(state, name, config, logger, volIDFunc, commonRulesFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (vm *BFVM) LoadFromString(source string) error {\n\treturn vm.LoadFromStream(strings.NewReader(source))\n}", "func (appConf *AppConf) Load(filename string, forceReload bool) (*AppConf, error){\n\t// appConf is load and force reload is false return direction\n\tif isLoad && !forceReload{\n\t\treturn appConf, nil\n\t}\n\tfilename, err := appConf.getEnvConfigPath(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = toml.DecodeFile(filename, appConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"使用配置文件: %s\", filename)\n\t// mark appConf as loaded\n\tisLoad = true\n\treturn appConf, nil\n}", "func (d *Datastore) Load() (Object, error) {\n\td.localLock.Lock()\n\tdefer d.localLock.Unlock()\n\n\t// clear Object first, as mapstructure's decoder doesn't have ZeroFields set to true for merging purposes\n\td.meta.Object = d.meta.Object[:0]\n\n\terr := d.kv.LoadConfig(d.meta)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = d.meta.unmarshall()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.meta.object, nil\n}", "func (ctx *AppContext) Load(env string) {\n\tlog.Println(\"Load app context\")\n\n\t// Load env specific config\n\tenvConfig := viper.Sub(env)\n\tctx.Env = env\n\tctx.ProjectID = envConfig.GetString(\"project_id\")\n\tctx.SuffixOfKind = envConfig.GetString(\"datastore.kind_suffix\")\n\tctx.EtcdServers = envConfig.GetStringSlice(\"etcd\")\n\n\t// Load common config\n\tctx.CommonConfig = viper.Sub(\"common\")\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tif err == nil {\n\t\tdecoder := json.NewDecoder(file)\n\t\terr = decoder.Decode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func Load() {\n\tvar err error\n\n\tconfLen := len(FilePath)\n\tif confLen != 0 {\n\t\terr = readFromJSON(FilePath)\n\t}\n\tif err == nil {\n\t\terr = readFromENV()\n\t}\n\tif err != nil {\n\t\tpanic(`Configuration not found. Please specify configuration`)\n\t}\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func TestDnn_LoadModel(t *testing.T) {\n\t//MODEL_PARAM=tmodel.pb,input_1,reshape_3/Reshape\n\tparam := os.Getenv(\"MODEL_PARAM\")\n\tif param == \"\" {\n\t\tt.Skip(\"Skipping model loading test; no MODEL_PARAM set\")\n\t\t//t.Error(\"no MODEL_PARAM set\")\n\t}\n\tstr2dnnfilter := func(inp string) VideoProfile {\n\t\tdnnfilter := VideoProfile{}\n\t\tstrs := strings.Split(inp, \",\")\n\t\tif len(strs) != 3 {\n\t\t\treturn dnnfilter\n\t\t}\n\t\tdnnfilter.Detector.ModelPath = strs[0]\n\t\tdnnfilter.Detector.Input = strs[1]\n\t\tdnnfilter.Detector.Output = strs[2]\n\t\treturn dnnfilter\n\t}\n\n\t_, dir := setupTest(t)\n\tdefer os.RemoveAll(dir)\n\n\tdnncfg := str2dnnfilter(param)\n\n\tif len(dnncfg.Detector.ModelPath) <= 0 || len(dnncfg.Detector.Input) <= 0 || len(dnncfg.Detector.Output) <= 0 {\n\t\tt.Errorf(\"invalid MODEL_PARAM set %v\", param)\n\t}\n\n\tdnnfilter := NewDnnFilter()\n\tdnnfilter.dnncfg = dnncfg\n\tif dnnfilter.InitDnnFilter(dnncfg) != true {\n\t\tt.Errorf(\"Can not load model file %v\", dnncfg.Detector.ModelPath)\n\t}\n\tdnnfilter.StopDnnFilter()\n}", "func (p *Puck) Load(name ...string) error {\n\tcmd := []byte(\"load();\\n\")\n\terr := p.command(name, cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *tomlLoader) Load(out interface{}) error {\n\tif _, err := toml.DecodeReader(l.r, out); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load(key string, data []byte) Entity {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tentity Entity\n\t)\n\n\tbuffer.Write(data)\n\tdecoder := gob.NewDecoder(&buffer)\n\tentityType := strings.Split(key, \".\")[0]\n\n\tswitch entityType {\n\tcase \"player\":\n\t\tentity = new(Player)\n\tcase \"planet\":\n\t\tentity = new(Planet)\n\tcase \"mission\":\n\t\tentity = new(Mission)\n\tcase \"sun\":\n\t\tentity = new(Sun)\n\tcase \"ss\":\n\t\tentity = new(SolarSlot)\n\tcase \"spy_report\":\n\t\tentity = new(SpyReport)\n\tdefault:\n\t\treturn nil\n\t}\n\tdecoder.Decode(entity)\n\treturn entity\n}", "func Load(r io.Reader, v interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSONLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\tif j.Reader != nil {\n\t\tr = j.Reader\n\t} else if j.Path != \"\" {\n\t\tfile, err := getConfig(j.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\treturn json.NewDecoder(r).Decode(s)\n}", "func (y *YAMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif y.Reader != nil {\n\t\tr = y.Reader\n\t} else if y.Path != \"\" {\n\t\tfile, err := getConfig(y.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(data, s)\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func (m *Method) TrainModel(c *gin.Context) {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(c.Request.Body)\n\tJSONStr := buf.String()\n\tm.GoPython(`ml.py`, JSONStr)\n\n\tvar response Response = Response{Status: `model training started`}\n\tc.JSON(http.StatusOK, response)\n}", "func (tfl tiltfileLoader) Load(ctx context.Context, tf *corev1alpha1.Tiltfile, prevResult *TiltfileLoadResult) TiltfileLoadResult {\n\tstart := time.Now()\n\tfilename := tf.Spec.Path\n\tabsFilename, err := ospath.RealAbs(tf.Spec.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn TiltfileLoadResult{\n\t\t\t\tConfigFiles: []string{filename},\n\t\t\t\tError: fmt.Errorf(\"No Tiltfile found at paths '%s'. Check out https://docs.tilt.dev/tutorial.html\", filename),\n\t\t\t}\n\t\t}\n\t\tabsFilename, _ = filepath.Abs(filename)\n\t\treturn TiltfileLoadResult{\n\t\t\tConfigFiles: []string{absFilename},\n\t\t\tError: err,\n\t\t}\n\t}\n\n\ttiltignorePath := watch.TiltignorePath(absFilename)\n\ttlr := TiltfileLoadResult{\n\t\tConfigFiles: []string{absFilename, tiltignorePath},\n\t}\n\n\ttiltignore, err := watch.ReadTiltignore(tiltignorePath)\n\n\t// missing tiltignore is fine, but a filesystem error is not\n\tif err != nil {\n\t\ttlr.Error = err\n\t\treturn tlr\n\t}\n\n\ttlr.Tiltignore = tiltignore\n\n\ts := newTiltfileState(ctx, tfl.dcCli, tfl.webHost, tfl.execer, tfl.k8sContextPlugin, tfl.versionPlugin,\n\t\ttfl.configPlugin, tfl.extensionPlugin, tfl.ciSettingsPlugin, feature.FromDefaults(tfl.fDefaults))\n\n\tmanifests, result, err := s.loadManifests(tf)\n\n\ttlr.BuiltinCalls = result.BuiltinCalls\n\ttlr.DefaultRegistry = s.defaultReg\n\n\t// All data models are loaded with GetState. We ignore the error if the state\n\t// isn't properly loaded. This is necessary for handling partial Tiltfile\n\t// execution correctly, where some state is correctly assembled but other\n\t// state is not (and should be assumed empty).\n\tws, _ := watch.GetState(result)\n\ttlr.WatchSettings = ws\n\n\t// NOTE(maia): if/when add secret settings that affect the engine, add them to tlr here\n\tss, _ := secretsettings.GetState(result)\n\ts.secretSettings = ss\n\n\tioState, _ := io.GetState(result)\n\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, ioState.Paths...)\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, s.postExecReadFiles...)\n\ttlr.ConfigFiles = sliceutils.DedupedAndSorted(tlr.ConfigFiles)\n\n\tdps, _ := dockerprune.GetState(result)\n\ttlr.DockerPruneSettings = dps\n\n\taSettings, _ := tiltfileanalytics.GetState(result)\n\ttlr.AnalyticsOpt = aSettings.Opt\n\n\ttlr.Secrets = s.extractSecrets()\n\ttlr.FeatureFlags = s.features.ToEnabled()\n\ttlr.Error = err\n\ttlr.Manifests = manifests\n\ttlr.TeamID = s.teamID\n\n\tobjectSet, _ := v1alpha1.GetState(result)\n\ttlr.ObjectSet = objectSet\n\n\tvs, _ := version.GetState(result)\n\ttlr.VersionSettings = vs\n\n\ttelemetrySettings, _ := telemetry.GetState(result)\n\ttlr.TelemetrySettings = telemetrySettings\n\n\tus, _ := updatesettings.GetState(result)\n\ttlr.UpdateSettings = us\n\n\tci, _ := cisettings.GetState(result)\n\ttlr.CISettings = ci\n\n\tconfigSettings, _ := config.GetState(result)\n\tif tlr.Error == nil {\n\t\ttlr.EnabledManifests, tlr.Error = configSettings.EnabledResources(tf, manifests)\n\t}\n\n\tduration := time.Since(start)\n\tif tlr.Error == nil {\n\t\ts.logger.Infof(\"Successfully loaded Tiltfile (%s)\", duration)\n\t}\n\textState, _ := tiltextension.GetState(result)\n\thashState, _ := hasher.GetState(result)\n\n\tvar prevHashes hasher.Hashes\n\tif prevResult != nil {\n\t\tprevHashes = prevResult.Hashes\n\t}\n\ttlr.Hashes = hashState.GetHashes()\n\n\ttfl.reportTiltfileLoaded(s.builtinCallCounts, s.builtinArgCounts, duration,\n\t\textState.ExtsLoaded, prevHashes, tlr.Hashes)\n\n\tif len(aSettings.CustomTagsToReport) > 0 {\n\t\treportCustomTags(tfl.analytics, aSettings.CustomTagsToReport)\n\t}\n\n\treturn tlr\n}", "func (k *Kluster) Load() error {\n\tif err := k.LoadSummary(); err != nil {\n\t\treturn err\n\t}\n\n\t// DEBUG:\n\t// fmt.Printf(\"DEBUG: cluster %s config version: %s\\tMin: %s\\tMax: %s\\n\", k.Name, k.Version, MinSemVersion, SemVersion)\n\n\tver, err := version.NewSemVer(k.Version)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"the cluster version (%s) is not well formed or not SemVer compliance. %s\", k.Version, err)\n\t}\n\tif ver.LT(MinSemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is not supported by this KubeKit, the minimun version supported is %s\", k.Version, MinVersion)\n\t}\n\tif ver.GT(SemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is greater than the cluster version supported by this KubeKit (%s)\", k.Version, Version)\n\t}\n\n\tk.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tname := k.Platform()\n\tconfig := k.Platforms[name]\n\n\tcred, err := k.GetCredentials()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tplatform, err := provisioner.NewPlatform(name, k.Name, config, cred, k.ui, k.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.provisioner[name] = platform\n\n\treturn nil\n}", "func (c *Info) Load() error {\n\tb, err := ioutil.ReadFile(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Lock()\n\terr = json.Unmarshal(b, c)\n\tc.Unlock()\n\n\treturn err\n}", "func Load(filename string) (*Beam, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treader := bufio.NewReader(f)\n\tdecoder := json.NewDecoder(reader)\n\tdecoder.DisallowUnknownFields()\n\tcfg := new(Beam)\n\t// This **Beam double-pointer appears to be required to detect an invalid\n\t// input of \"null\". See Test_Load/file_contains_null test.\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding JSON value in %v: %v\", filename, err)\n\t}\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"loading %v resulted in nil config\", filename)\n\t}\n\tif decoder.More() {\n\t\treturn nil, fmt.Errorf(\"found unexpected data after config in %v\", filename)\n\t}\n\treturn cfg, nil\n}", "func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}", "func (s *Startup) Load() error {\n\n\t// TODO: parameterize startup config file name\n\tjsonFile, err := ioutil.ReadFile(\"startup.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(jsonFile, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil // no error\n}", "func (component *Component) Load(filename string) error {\n\treturn util.LoadYAML(filename, component)\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func (s *EnvironmentSource) Load(_ *schema.StructValidator) (err error) {\n\tkeyMap, ignoredKeys := getEnvConfigMap(schema.Keys, s.prefix, s.delimiter)\n\n\treturn s.koanf.Load(env.ProviderWithValue(s.prefix, constDelimiter, koanfEnvironmentCallback(keyMap, ignoredKeys, s.prefix, s.delimiter)), nil)\n}", "func Load(filename string, data any, validation bool) error {\n\tisJSON := strings.HasSuffix(filename, \".json\")\n\n\tbs, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif validation {\n\t\terr := validate(bs, data, isJSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn unmarshal(bs, data, isJSON)\n}", "func Load(env string) *Configuration {\n\t_, filePath, _, _ := runtime.Caller(0)\n\tconfigName := \"config.\" + env + \".yaml\"\n\tconfigPath := filePath[:len(filePath)-9] + \"files\" + string(filepath.Separator)\n\n\tviper.SetConfigName(configName)\n\tviper.AddConfigPath(configPath)\n\tviper.SetConfigType(\"yaml\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Configuration\n\tviper.Unmarshal(&config)\n\tsetGinMode(config.Server.Mode)\n\n\treturn &config\n}", "func Load(path string) (*LevelDB, error) {\n\treturn LoadWithOptions(path, DefaultOptions)\n}", "func Load(name string, data interface{}) error {\n\tp := jsonPath(name)\n\t// Don't load anything if the file doesn't exist\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"File %s didn't exist, loading with fresh data\\n\", p)\n\t\treturn nil\n\t}\n\n\t// Read and unmarshal the json\n\tif b, err := ioutil.ReadFile(p); err != nil {\n\t\treturn err\n\t} else if len(b) == 0 {\n\t\tlog.Printf(\"File %s was empty, loading with fresh data\\n\", p)\n\t\treturn nil\n\t} else if err := json.Unmarshal(b, data); err != nil {\n\t\treturn fmt.Errorf(\"failed to load file %s error: %s\", p, err)\n\t}\n\n\tlog.Printf(\"Loaded %s\\n\", p)\n\treturn nil\n}", "func (rs *Restake) LoadProto(pbAct *iotextypes.StakeRestake) error {\n\tif pbAct == nil {\n\t\treturn ErrNilProto\n\t}\n\n\trs.bucketIndex = pbAct.GetBucketIndex()\n\trs.payload = pbAct.GetPayload()\n\trs.duration = pbAct.GetStakedDuration()\n\trs.autoStake = pbAct.GetAutoStake()\n\n\treturn nil\n}", "func (config *Config) Load() error {\n\tvar env string\n\tflag.StringVar(&env, \"env\", \"dev\", \"environment\")\n\n\tflag.Parse()\n\n\tviperRegistry := viper.New()\n\tviperRegistry.AddConfigPath(\"./config\")\n\tviperRegistry.SetConfigName(env)\n\tviperRegistry.SetConfigType(\"json\")\n\tviperRegistry.SetEnvPrefix(\"todo\")\n\tviperRegistry.AutomaticEnv()\n\n\tconfig.Env = env\n\n\tif err := viperRegistry.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureApplication(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureDB(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureAuth(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (wlt *Wallet) Load(dir string) error {\n\tr := &ReadableWallet{}\n\tif err := r.Load(filepath.Join(dir, wlt.GetFilename())); err != nil {\n\t\treturn err\n\t}\n\tr.Meta[\"filename\"] = wlt.GetFilename()\n\t*wlt = NewWalletFromReadable(r)\n\treturn nil\n}", "func Load(filepath string, startTag, endTag string, vars map[string]string) (result string, err error) {\n\tvar data []byte\n\tif data, err = ioutil.ReadFile(filepath); err == nil {\n\t\tvar tpl *Engine\n\t\tif tpl, err = New(string(data), startTag, endTag); err == nil {\n\t\t\tif result, err = tpl.Process(vars); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if err == errs.TmplVarsNotFoundError {\n\t\t\terr = nil\n\t\t\tresult = string(data)\n\t\t}\n\t}\n\treturn\n}", "func (l *Loader) Load(cfg *config.Config) {\n\tcfg.Address = os.Getenv(\"BRCEP_ADDRESS\")\n\tcfg.LogLevel = os.Getenv(\"BRCEP_LOG_LEVEL\")\n\tcfg.PreferredAPI = os.Getenv(\"BRCEP_PREFERRED_API\")\n\tcfg.ViaCepURL = os.Getenv(\"BRCEP_VIACEP_URL\")\n\tcfg.CepAbertoURL = os.Getenv(\"BRCEP_CEPABERTO_URL\")\n\tcfg.CepAbertoToken = os.Getenv(\"BRCEP_CEPABERTO_TOKEN\")\n\tcfg.CorreiosURL = os.Getenv(\"BRCEP_CORREIOS_URL\")\n}", "func Load(cfg interface{}, configPath string) error {\n\tif err := readConfigFile(configPath, cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ClusterState == nil {\n\t\tcfg.ClusterState = &ClusterState{}\n\t}\n\tif cfg.ALBIngressController == nil {\n\t\tcfg.ALBIngressController = &ALBIngressController{}\n\t}\n\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.ClusterState.UpTook != \"\" {\n\t\tcfg.ClusterState.upTook, err = time.ParseDuration(cfg.ClusterState.UpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif cfg.ALBIngressController.IngressUpTook != \"\" {\n\t\tcfg.ALBIngressController.ingressUpTook, err = time.ParseDuration(cfg.ALBIngressController.IngressUpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}" ]
[ "0.70856375", "0.6931012", "0.691719", "0.67702013", "0.6714875", "0.6647788", "0.6632438", "0.6570047", "0.6427433", "0.6367626", "0.63450754", "0.6210927", "0.62089187", "0.6141275", "0.6126932", "0.5932069", "0.59089965", "0.5824516", "0.5803706", "0.57926947", "0.56931376", "0.5685074", "0.56759435", "0.5629026", "0.5624409", "0.55188453", "0.5496034", "0.549438", "0.5485185", "0.5469166", "0.54661906", "0.5462454", "0.544723", "0.5436073", "0.54302883", "0.54199696", "0.5392638", "0.5384862", "0.53777784", "0.53655183", "0.53620535", "0.5341112", "0.5309845", "0.5309004", "0.5252267", "0.5244161", "0.5244161", "0.52102965", "0.5200908", "0.5191221", "0.51873565", "0.5179895", "0.517651", "0.5174189", "0.5173903", "0.51596195", "0.5154276", "0.51491684", "0.5142233", "0.51373446", "0.51358354", "0.51347655", "0.5117462", "0.5103656", "0.510187", "0.5097216", "0.50966686", "0.50809854", "0.50709903", "0.5022858", "0.50180924", "0.5016142", "0.50149995", "0.5002425", "0.49866006", "0.4971974", "0.4967155", "0.49617535", "0.4960292", "0.4955598", "0.49451393", "0.49449015", "0.49324843", "0.4930584", "0.4926257", "0.4920262", "0.49176425", "0.4904417", "0.4903159", "0.4899459", "0.48970014", "0.48836428", "0.48743317", "0.48730356", "0.48698953", "0.48682275", "0.48675355", "0.48576903", "0.48446506", "0.4835371" ]
0.6942267
1
Forwad forwads pass through the model. Params: + `inputIds`: Optional input tensor of shape (batch size, sequence length). If None, precomputed embeddings must be provided (see inputEmbeds). + `mask`: Optional mask of shape (batch size, sequence length). Masked position have value 0, nonmasked value 1. If None set to 1. + `tokenTypeIds`: Optional segment id of shape (batch size, sequence length). Convention is value of 0 for the first sentence (incl. ) and 1 for the second sentence. If None set to 0. + `positionIds`: Optional position ids of shape (batch size, sequence length). If None, will be incremented from 0. + `inputEmbeds`: Optional precomputed input embeddings of shape (batch size, sequence length, hidden size). If None, input ids must be provided (see inputIds). + `encoderHiddenStates`: Optional encoder hidden state of shape (batch size, encoder sequence length, hidden size). If the model is defined as a decoder and the encoder hidden states is not None, used in the crossattention layer as keys and values (query from the decoder). + `encoderMask`: Optional encoder attention mask of shape (batch size, encoder sequence length). If the model is defined as a decoder and the encoder_hidden_states is not None, used to mask encoder values. Positions with value 0 will be masked. + `train`: boolean flag to turn on/off the dropout layers in the model. Should be set to false for inference. Returns: + `output`: tensor of shape (batch size, numLabels, vocab size) + `hiddenStates`: optional slice of tensors of length numHiddenLayers with shape (batch size, sequence length, hidden size). + `attentions`: optional slice of tensors of length num hidden layers with shape (batch size, sequence length, hidden size). + `err`: error
func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) { hiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train) if err != nil { return ts.None, nil, nil, err } predictionScores := mlm.lmHead.Forward(hiddenState) return predictionScores, allHiddenStates, allAttentions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tc *RobertaForTokenClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := tc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := hiddenState.ApplyT(tc.dropout, train)\n\toutput = appliedDO.Apply(tc.classifier)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tlabels = sc.classifier.ForwardT(hiddenState, train)\n\thiddenState.MustDrop()\n\n\treturn labels, hiddenStates, attentions, nil\n}", "func (qa *RobertaForQuestionAnswering) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (startScores, endScores *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := qa.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, ts.None, nil, nil, err\n\t}\n\n\tsequenceOutput := hiddenState.Apply(qa.qaOutputs)\n\tlogits := sequenceOutput.MustSplit(1, -1, true)\n\tstartScores = logits[0].MustSqueeze1(-1, false)\n\tendScores = logits[1].MustSqueeze1(-1, false)\n\n\tfor _, x := range logits {\n\t\tx.MustDrop()\n\t}\n\n\treturn startScores, endScores, hiddenStates, attentions, nil\n}", "func (*protobufLang) Embeds(r *rule.Rule, from label.Label) []label.Label { return nil }", "func (n *Network) Forword(ins []float64) []float64 {\n\tif n.Weights == nil {\n\t\tfmt.Println(\"Weights are nil.\")\n\t\treturn nil\n\t}\n\tif n.Baiases == nil {\n\t\tfmt.Println(\"Baiases are nil.\")\n\t\treturn nil\n\t}\n\tif n.Activator == nil {\n\t\tfmt.Println(\"Activator is nil.\")\n\t\treturn nil\n\t}\n\tiped := InnerProduct(ins,n.Weights)\n\tadded := Add(iped,n.Baiases)\n\touts := Activate(added,n.Activator)\n\treturn outs\n}", "func trainAndPredict(pis []PredictIndices, xs mat.Matrix, fs, weights []float64,\n\tfolds []Fold, fitters []Fitter, p distmv.RandLogProber, predictFull, keepFits bool) (evAll []float64, evs [][]float64, fps []FoldPrediction, err error) {\n\n\tnFolds := len(folds)\n\tnFit := len(fitters)\n\t_, dim := xs.Dims()\n\n\t// First, allocate the memory for the return arguments.\n\tevs = make([][]float64, nFolds)\n\tfor i := range folds {\n\t\tevs[i] = make([]float64, nFit)\n\t}\n\n\tfps = make([]FoldPrediction, nFolds)\n\tfor i := 0; i < nFolds; i++ {\n\t\tfps[i].PredictIndices = pis[i]\n\t\tif keepFits {\n\t\t\tfps[i].Predictors = make([]Predictor, nFit)\n\t\t}\n\t\tpredictions := make([][]float64, nFit)\n\t\tfor j := 0; j < nFit; j++ {\n\t\t\tpredictions[j] = make([]float64, len(fps[i].Unique))\n\t\t\tfor k := range predictions[j] {\n\t\t\t\tpredictions[j][k] = math.NaN()\n\t\t\t}\n\t\t}\n\t\tfps[i].Predictions = predictions\n\t}\n\n\t// Train each fitter individually and make predictions.\n\tfor i := range folds {\n\t\tfor j := range fitters {\n\t\t\tfold := folds[i]\n\t\t\tfitter := fitters[j]\n\n\t\t\tpred, err := fitter.Fit(xs, fs, weights, fold.Train)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, FitError{Fit: j, Fold: i, Err: err}\n\t\t\t}\n\t\t\tif keepFits {\n\t\t\t\tfps[i].Predictors[j] = pred\n\t\t\t}\n\t\t\tx := make([]float64, dim)\n\t\t\tfor k, v := range fps[i].Unique {\n\t\t\t\tmat.Row(x, v, xs)\n\t\t\t\tfps[i].Predictions[j][k] = pred.Predict(x)\n\t\t\t}\n\t\t\tevs[i][j] = pred.ExpectedValue(p)\n\t\t}\n\t}\n\n\t// Train on all the indices if necessary.\n\tif predictFull {\n\t\tevAll = make([]float64, nFit)\n\t\tallTrain := FindAllTrain(folds)\n\t\tfor i := range evAll {\n\t\t\tpred, err := fitters[i].Fit(xs, fs, weights, allTrain)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, nil, FitError{Fit: i, Fold: -1, Err: err}\n\t\t\t}\n\t\t\tevAll[i] = pred.ExpectedValue(p)\n\t\t}\n\t}\n\n\treturn evAll, evs, fps, nil\n}", "func (mc *RobertaForMultipleChoice) ForwardT(inputIds, mask, tokenTypeIds, positionIds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\tnumChoices := inputIds.MustSize()[1]\n\n\tinputIdsSize := inputIds.MustSize()\n\tflatInputIds := inputIds.MustView([]int64{-1, inputIdsSize[len(inputIdsSize)-1]}, false)\n\n\tflatPositionIds := ts.None\n\tif positionIds.MustDefined() {\n\t\tpositionIdsSize := positionIds.MustSize()\n\t\tflatPositionIds = positionIds.MustView([]int64{-1, positionIdsSize[len(positionIdsSize)-1]}, false)\n\t}\n\n\tflatTokenTypeIds := ts.None\n\tif tokenTypeIds.MustDefined() {\n\t\ttokenTypeIdsSize := tokenTypeIds.MustSize()\n\t\tflatTokenTypeIds = tokenTypeIds.MustView([]int64{-1, tokenTypeIdsSize[len(tokenTypeIdsSize)-1]}, false)\n\t}\n\n\tflatMask := ts.None\n\tif mask.MustDefined() {\n\t\tflatMaskSize := flatMask.MustSize()\n\t\tflatMask = mask.MustView([]int64{-1, flatMaskSize[len(flatMaskSize)-1]}, false)\n\t}\n\n\tvar pooledOutput *ts.Tensor\n\t_, pooledOutput, hiddenStates, attentions, err = mc.roberta.ForwardT(flatInputIds, flatMask, flatTokenTypeIds, flatPositionIds, ts.None, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := pooledOutput.ApplyT(mc.dropout, train)\n\tappliedCls := appliedDO.Apply(mc.classifier)\n\toutput = appliedCls.MustView([]int64{-1, numChoices}, true)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (resolver) Embeds(r *rule.Rule, from label.Label) []label.Label {\n\treturn nil\n}", "func (board *Board) HackerEmblemSeed() {\n\tboard.Cells[0][2].SetAlive(true)\n\tboard.Cells[1][0].SetAlive(true)\n\tboard.Cells[1][2].SetAlive(true)\n\tboard.Cells[2][1].SetAlive(true)\n\tboard.Cells[2][2].SetAlive(true)\n}", "func Embed(host Sequence, index int, guest Sequence) Sequence {\n\tinfo := host.Info()\n\tinfo = tryExpand(info, index, Len(guest))\n\thost = WithInfo(host, info)\n\n\tvar ff FeatureSlice\n\tfor _, f := range host.Features() {\n\t\tf.Loc = f.Loc.Expand(index, Len(guest))\n\t\tff = ff.Insert(f)\n\t}\n\tfor _, f := range guest.Features() {\n\t\tf.Loc = f.Loc.Expand(0, index)\n\t\tff = ff.Insert(f)\n\t}\n\thost = WithFeatures(host, ff)\n\n\tp := insert(host.Bytes(), index, guest.Bytes())\n\thost = WithBytes(host, p)\n\n\treturn host\n}", "func (nn *FeedForward) Update(inputs []*seal.Ciphertext) []*seal.Ciphertext {\n\tif len(inputs) != nn.NInputs-1 {\n\t\tlog.Fatal(\"Error: wrong number of inputs\")\n\t}\n\n\tfor i := 0; i < nn.NInputs-1; i++ {\n\t\tnn.InputActivations[i] = inputs[i]\n\t}\n\n\tfor i := 0; i < nn.NHiddens-1; i++ {\n\t\tvar sum *seal.Ciphertext\n\n\t\tfor j := 0; j < nn.NInputs; j++ {\n\t\t\telem := nn.Evaluator.Multiply(nn.InputActivations[j], nn.InputWeights[j][i])\n\t\t\tif sum == nil {\n\t\t\t\tsum = elem\n\t\t\t} else {\n\t\t\t\tnn.Evaluator.AddInplace(sum, elem)\n\t\t\t}\n\t\t}\n\n\t\t// compute contexts sum\n\t\tfor k := 0; k < len(nn.Contexts); k++ {\n\t\t\tfor j := 0; j < nn.NHiddens-1; j++ {\n\t\t\t\tnn.Evaluator.AddInplace(sum, nn.Contexts[k][j])\n\t\t\t}\n\t\t}\n\n\t\tnn.HiddenActivations[i] = nn.sigmoid(sum)\n\t}\n\n\tnn.HiddenActivations[nn.NHiddens-1] = nn.Encryptor.Encrypt(\n\t\tnn.Encoder.EncodeScale(0, nn.HiddenActivations[0].Scale()))\n\n\tfor i, ia := range nn.HiddenActivations {\n\t\tlog.Println(i, ia.Scale())\n\t}\n\n\t// update the contexts\n\tif len(nn.Contexts) > 0 {\n\t\tfor i := len(nn.Contexts) - 1; i > 0; i-- {\n\t\t\tnn.Contexts[i] = nn.Contexts[i-1]\n\t\t}\n\t\tnn.Contexts[0] = nn.HiddenActivations\n\t}\n\n\tfor i := 0; i < nn.NOutputs; i++ {\n\t\tvar sum *seal.Ciphertext\n\t\tfor j := 0; j < nn.NHiddens; j++ {\n\t\t\tactivation := nn.HiddenActivations[j]\n\t\t\toutput := nn.OutputWeights[j][i]\n\t\t\tlog.Println(i, j, output, activation)\n\t\t\tnn.Evaluator.RescaleToInplace(output, activation.ParmsID())\n\t\t\telem := nn.Evaluator.Multiply(activation, output)\n\t\t\tif sum == nil {\n\t\t\t\tsum = elem\n\t\t\t} else {\n\t\t\t\tlog.Println(sum.Scale(), elem.Scale())\n\t\t\t\tnn.Evaluator.RelinearizeInplace(elem, nn.RelinKeys)\n\t\t\t\tnn.Evaluator.RescaleToInplace(elem, sum.ParmsID())\n\t\t\t\tlog.Println(sum.Scale(), elem.Scale())\n\t\t\t\tnn.Evaluator.AddInplace(sum, elem)\n\t\t\t}\n\t\t}\n\n\t\tnn.OutputActivations[i] = nn.sigmoid(sum)\n\t}\n\n\treturn nn.OutputActivations\n}", "func (*visibilityExtension) Embeds(r *rule.Rule, from label.Label) []label.Label {\n\treturn nil\n}", "func (m *ItemTranslateExchangeIdsPostRequestBody) SetInputIds(value []string)() {\n err := m.GetBackingStore().Set(\"inputIds\", value)\n if err != nil {\n panic(err)\n }\n}", "func Softmax(scope *Scope, logits tf.Output) (softmax tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Softmax\",\n\t\tInput: []tf.Input{\n\t\t\tlogits,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (nn *FeedForward) Init(inputs, hiddens, outputs int) {\n\n\tnn.NInputs = inputs + 1 // +1 for bias\n\tnn.NHiddens = hiddens + 1 // +1 for bias\n\tnn.NOutputs = outputs\n\n\tnn.InputActivations = nn.vector(nn.NInputs, 1.0)\n\tnn.HiddenActivations = nn.vector(nn.NHiddens, 1.0)\n\tnn.OutputActivations = nn.vector(nn.NOutputs, 1.0)\n\n\tnn.InputWeights = nn.matrix(nn.NInputs, nn.NHiddens)\n\tnn.OutputWeights = nn.matrix(nn.NHiddens, nn.NOutputs)\n\n\tfor i := 0; i < nn.NInputs; i++ {\n\t\tfor j := 0; j < nn.NHiddens; j++ {\n\t\t\tnn.InputWeights[i][j] = nn.random(-1, 1)\n\t\t}\n\t}\n\n\tfor i := 0; i < nn.NHiddens; i++ {\n\t\tfor j := 0; j < nn.NOutputs; j++ {\n\t\t\tnn.OutputWeights[i][j] = nn.random(-1, 1)\n\t\t}\n\t}\n\n\tnn.InputChanges = nn.matrix(nn.NInputs, nn.NHiddens)\n\tnn.OutputChanges = nn.matrix(nn.NHiddens, nn.NOutputs)\n}", "func (o KubernetesClusterMaintenanceWindowPtrOutput) Alloweds() KubernetesClusterMaintenanceWindowAllowedArrayOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterMaintenanceWindow) []KubernetesClusterMaintenanceWindowAllowed {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Alloweds\n\t}).(KubernetesClusterMaintenanceWindowAllowedArrayOutput)\n}", "func IFFT(scope *Scope, input tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"IFFT\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func TrackEmbeddings(ex []*Embedding, o *gd.GradientDescent) {\n\tfor _, e := range ex {\n\t\to.Track(e)\n\t}\n}", "func VBROADCASTF32X4(ops ...operand.Op) { ctx.VBROADCASTF32X4(ops...) }", "func TestTFIDFVectorizerTransform(t *testing.T) {\n\tsamples := []struct {\n\t\tname string\n\t\tndocs int\n\t\tdoccount []uint\n\t\tmapping map[string]uint\n\t\tinput string\n\t\toutput []float64\n\t}{\n\t\t{\"basic_1\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"a a a c\", []float64{0.8194099510753755, 0, 0.5732079309279058}},\n\t\t{\"basic_2\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"a a\", []float64{1, 0, 0}},\n\t\t{\"basic_3\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"a a a\", []float64{1, 0, 0}},\n\t\t{\"basic_4\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"a a a a\", []float64{1, 0, 0}},\n\t\t{\"basic_5\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"a a a b b\", []float64{0.47330339145578754, 0.8808994832762984, 0}},\n\t\t{\"basic_6\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"a a a c c\", []float64{0.58149260706886, 0, 0.8135516873095773}},\n\t\t{\"not found\", 6, []uint{6, 1, 2}, map[string]uint{\"a\": 0, \"b\": 1, \"c\": 2}, \"dddd\", []float64{0, 0, 0}},\n\t\t{\"empty input\", 2, []uint{1, 2}, map[string]uint{\"a\": 0, \"b\": 1}, \" \", []float64{0, 0}},\n\t\t{\"empty vals\", 2, []uint{1, 2}, map[string]uint{}, \" b a \", []float64{}},\n\t\t{\"nil input\", 2, []uint{1, 2}, map[string]uint{}, \"\", []float64{}},\n\t}\n\n\tfor _, s := range samples {\n\t\tt.Run(s.name, func(t *testing.T) {\n\t\t\tencoder := TFIDFVectorizer{\n\t\t\t\tCountVectorizer: CountVectorizer{Mapping: s.mapping, Separator: \" \"},\n\t\t\t\tNumDocuments: s.ndocs,\n\t\t\t\tDocCount: s.doccount,\n\t\t\t}\n\t\t\tassert.Equal(t, s.output, encoder.Transform(s.input))\n\t\t})\n\n\t\tif len(s.output) > 0 {\n\t\t\tt.Run(s.name+\"_inplace\", func(t *testing.T) {\n\t\t\t\tencoder := TFIDFVectorizer{\n\t\t\t\t\tCountVectorizer: CountVectorizer{Mapping: s.mapping, Separator: \" \"},\n\t\t\t\t\tNumDocuments: s.ndocs,\n\t\t\t\t\tDocCount: s.doccount,\n\t\t\t\t}\n\n\t\t\t\tfeatures := make([]float64, encoder.NumFeatures())\n\t\t\t\tencoder.TransformInplace(features, s.input)\n\t\t\t\tassert.Equal(t, s.output, features)\n\n\t\t\t\t// note, values in copied range should be zero\n\t\t\t\tfeatures = make([]float64, encoder.NumFeatures()+100)\n\t\t\t\tfeatures[0] = 11223344556677\n\t\t\t\tfeatures[1] = 10101010110101\n\t\t\t\tfeatures[99] = 1231231231\n\n\t\t\t\texpected := make([]float64, len(features))\n\t\t\t\tcopy(expected, features)\n\t\t\t\tcopy(expected[10:], s.output)\n\n\t\t\t\tencoder.TransformInplace(features[10:10+encoder.NumFeatures()], s.input)\n\t\t\t\tassert.Equal(t, expected, features)\n\t\t\t})\n\t\t}\n\t}\n\n\tt.Run(\"inplace does not run when dest len is not equal num features\", func(t *testing.T) {\n\t\tencoder := TFIDFVectorizer{\n\t\t\tCountVectorizer: CountVectorizer{Mapping: map[string]uint{\"a\": 0, \"b\": 1}, Separator: \" \"},\n\t\t\tNumDocuments: 5,\n\t\t\tDocCount: []uint{2, 5},\n\t\t}\n\n\t\tfeatures := []float64{1, 2, 3, 4}\n\t\tencoder.TransformInplace(features, \"a b c d\")\n\t\tassert.Equal(t, []float64{1, 2, 3, 4}, features)\n\t})\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (b *broadcast) Run(ctx context.Context, params StageParams) {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tinCh = make([]chan Payload, len(b.fifos))\n\t)\n\tfor i := 0; i < len(b.fifos); i++ {\n\t\twg.Add(1)\n\t\tinCh[i] = make(chan Payload)\n\t\tgo func(fifoIndex int) {\n\t\t\tfifoParams := &workerParams{\n\t\t\t\tstage: params.StageIndex(),\n\t\t\t\tinCh: inCh[fifoIndex],\n\t\t\t\toutCh: params.Output(),\n\t\t\t\terrCh: params.Error(),\n\t\t\t}\n\t\t\tb.fifos[fifoIndex].Run(ctx, fifoParams)\n\t\t\twg.Done()\n\t\t}(i)\n\t}\ndone:\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tbreak done\n\t\tcase payload, ok := <-params.Input():\n\t\t\tif !ok {\n\t\t\t\tbreak done\n\t\t\t}\n\t\t\tfor i := len(b.fifos) - 1; i >= 0; i++ {\n\t\t\t\t// as each FIFO might modify the payload, to\n\t\t\t\t// avoid data race we need to copy of each payload\n\t\t\t\t// for all FiFO execpt the first one\n\t\t\t\tvar fifoPayload = payload\n\t\t\t\tif i != 0 {\n\t\t\t\t\tfifoPayload = payload.Clone()\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tbreak done\n\t\t\t\tcase inCh[i] <- fifoPayload:\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, ch := range inCh {\n\t\tclose(ch)\n\t}\n\twg.Wait()\n\n}", "func (fm *FieldModelFlagsSimple) FBEShift(size int) { fm.offset += size }", "func ExampleDeviceFarm_ListRuns_shared00() {\n\tsvc := devicefarm.New(session.New())\n\tinput := &devicefarm.ListRunsInput{\n\t\tArn: aws.String(\"arn:aws:devicefarm:us-west-2:123456789101:run:5e01a8c7-c861-4c0a-b1d5-5ec6e6c6dd23/0fcac17b-6122-44d7-ae5a-12345EXAMPLE\"),\n\t\tNextToken: aws.String(\"RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE\"),\n\t}\n\n\tresult, err := svc.ListRuns(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase devicefarm.ErrCodeArgumentException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeArgumentException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotFoundException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotFoundException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeServiceAccountException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeServiceAccountException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (*bzlLibraryLang) Embeds(r *rule.Rule, from label.Label) []label.Label { return nil }", "func CTCBeamSearchDecoder(scope *Scope, inputs tf.Output, sequence_length tf.Output, beam_width int64, top_paths int64, optional ...CTCBeamSearchDecoderAttr) (decoded_indices []tf.Output, decoded_values []tf.Output, decoded_shape []tf.Output, log_probability tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"beam_width\": beam_width, \"top_paths\": top_paths}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"CTCBeamSearchDecoder\",\n\t\tInput: []tf.Input{\n\t\t\tinputs, sequence_length,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tvar idx int\n\tvar err error\n\tif decoded_indices, idx, err = makeOutputList(op, idx, \"decoded_indices\"); err != nil {\n\t\tscope.UpdateErr(\"CTCBeamSearchDecoder\", err)\n\t\treturn\n\t}\n\tif decoded_values, idx, err = makeOutputList(op, idx, \"decoded_values\"); err != nil {\n\t\tscope.UpdateErr(\"CTCBeamSearchDecoder\", err)\n\t\treturn\n\t}\n\tif decoded_shape, idx, err = makeOutputList(op, idx, \"decoded_shape\"); err != nil {\n\t\tscope.UpdateErr(\"CTCBeamSearchDecoder\", err)\n\t\treturn\n\t}\n\tlog_probability = op.Output(idx)\n\treturn decoded_indices, decoded_values, decoded_shape, log_probability\n}", "func DMessageEmbeds(exec boil.Executor, mods ...qm.QueryMod) dMessageEmbedQuery {\n\tmods = append(mods, qm.From(\"\\\"d_message_embeds\\\"\"))\n\treturn dMessageEmbedQuery{NewQuery(exec, mods...)}\n}", "func VBROADCASTF64X4(ops ...operand.Op) { ctx.VBROADCASTF64X4(ops...) }", "func NewTransferWithSeedInstructionBuilder() *TransferWithSeed {\n\tnd := &TransferWithSeed{\n\t\tAccountMetaSlice: make(ag_solanago.AccountMetaSlice, 3),\n\t}\n\treturn nd\n}", "func NewListDCForSeedParams() *ListDCForSeedParams {\n\tvar ()\n\treturn &ListDCForSeedParams{\n\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (s *Model) Run(inputs [][]linalg.Vector) [][]linalg.Vector {\n\tvar resSequences [][]linalg.Vector\n\tfor _, sequence := range inputs {\n\t\tstate := stochnet.ConstBoolVec(make([]bool, s.StateSize))\n\t\tvar outSeq []linalg.Vector\n\t\tfor _, in := range sequence {\n\t\t\tjoinedIn := stochnet.Concat(state, floatsToBools(in))\n\t\t\tstate = s.StateLayer.Apply(joinedIn)\n\t\t\toutput := s.OutputLayer.Apply(state)\n\t\t\toutSeq = append(outSeq, boolsToFloats(output))\n\t\t}\n\t\tresSequences = append(resSequences, outSeq)\n\t}\n\treturn resSequences\n}", "func Pad(scope *Scope, input tf.Output, paddings tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Pad\",\n\t\tInput: []tf.Input{\n\t\t\tinput, paddings,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func FusionFromDetections(ds []*pb.AnnotatedDetection, outDir string) (fusion *pb.Fusion, err error) {\n\tif len(ds) == 0 {\n\t\treturn nil, errors.New(\"no detections given for fusion\")\n\t}\n\n\tfusion = new(pb.Fusion)\n\n\tfirstDet := ds[0].GetDetection()\n\tswitch val := firstDet.GetRequest().(type) {\n\tcase *pb.Detection_ImgManipReq:\n\t\tfusion.Request = &pb.Fusion_ImgManipReq{\n\t\t\tImgManipReq: &pb.FuseImageManipulationRequest{\n\t\t\t\tImgManipReq: firstDet.GetImgManipReq(),\n\t\t\t},\n\t\t}\n\t\tfreq := fusion.GetImgManipReq()\n\t\tfreq.OutDir = outDir\n\t\tfor _, d := range ds {\n\t\t\t// TODO: check that none of the requests differ materially from the first one.\n\t\t\tid, ver, err := medifor.IDVersionFromDetection(d)\n\t\t\t// If using combined ID_Version format\n\t\t\t// id = fmt.Sprintf(\"%v_%v\", id, ver)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"detection id/version\")\n\t\t\t}\n\t\t\tfreq.ImgManip = append(freq.ImgManip, &pb.AnnotatedImageManipulation{\n\t\t\t\tId: id,\n\t\t\t\tVersion: ver,\n\t\t\t\tData: d.GetDetection().GetImgManip(),\n\t\t\t})\n\t\t}\n\t\t//TODO Splice and Video\n\tcase *pb.Detection_VidManipReq:\n\t\tfusion.Request = &pb.Fusion_VidManipReq{\n\t\t\tVidManipReq: &pb.FuseVideoManipulationRequest{\n\t\t\t\tVidManipReq: firstDet.GetVidManipReq(),\n\t\t\t},\n\t\t}\n\t\tfreq := fusion.GetVidManipReq()\n\t\tfreq.OutDir = outDir\n\t\tfor _, d := range ds {\n\t\t\tid, ver, err := medifor.IDVersionFromDetection(d)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"detection id/version for vid fusion\")\n\t\t\t}\n\t\t\tfreq.VidManip = append(freq.VidManip, &pb.AnnotatedVideoManipulation{\n\t\t\t\tId: id,\n\t\t\t\tVersion: ver,\n\t\t\t\tData: d.GetDetection().GetVidManip(),\n\t\t\t})\n\t\t}\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unknown fusion request type %T\", val)\n\t}\n\n\treturn fusion, nil\n}", "func (*AutoMlForecastingInputs) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_aiplatform_v1_schema_trainingjob_definition_automl_time_series_forecasting_proto_rawDescGZIP(), []int{1}\n}", "func (sm *SoftMax) Input(varNm string, di int) {\n\toff := 0\n\tfor _, ly := range sm.Layers {\n\t\ttsr := sm.ValsTsr(ly.Name())\n\t\tly.UnitValsTensor(tsr, varNm, di)\n\t\tfor j, v := range tsr.Values {\n\t\t\tsm.Inputs[off+j] = v\n\t\t}\n\t\toff += ly.Shape().Len()\n\t}\n}", "func (o KubernetesClusterMaintenanceWindowOutput) Alloweds() KubernetesClusterMaintenanceWindowAllowedArrayOutput {\n\treturn o.ApplyT(func(v KubernetesClusterMaintenanceWindow) []KubernetesClusterMaintenanceWindowAllowed {\n\t\treturn v.Alloweds\n\t}).(KubernetesClusterMaintenanceWindowAllowedArrayOutput)\n}", "func (h *host) Encode(ctx context.Context, ids ttnpb.EndDeviceIdentifiers, version *ttnpb.EndDeviceVersionIdentifiers, msg *ttnpb.ApplicationDownlink, script string) error {\n\tdefer trace.StartRegion(ctx, \"encode message\").End()\n\n\tdecoded := msg.DecodedPayload\n\tif decoded == nil {\n\t\treturn nil\n\t}\n\tm, err := gogoproto.Map(decoded)\n\tif err != nil {\n\t\treturn errInput.WithCause(err)\n\t}\n\tenv := h.createEnvironment(ids, version)\n\tenv[\"payload\"] = m\n\tenv[\"f_port\"] = msg.FPort\n\tscript = fmt.Sprintf(`\n\t\t%s\n\t\tEncoder(env.payload, env.f_port)\n\t`, script)\n\tvalue, err := h.engine.Run(ctx, script, env)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif value == nil || reflect.TypeOf(value).Kind() != reflect.Slice {\n\t\treturn errOutputType.New()\n\t}\n\tslice := reflect.ValueOf(value)\n\tfrmPayload := make([]byte, slice.Len())\n\tfor i := 0; i < slice.Len(); i++ {\n\t\tval := slice.Index(i).Interface()\n\t\tvar b int64\n\t\tswitch i := val.(type) {\n\t\tcase int:\n\t\t\tb = int64(i)\n\t\tcase int8:\n\t\t\tb = int64(i)\n\t\tcase int16:\n\t\t\tb = int64(i)\n\t\tcase int32:\n\t\t\tb = int64(i)\n\t\tcase int64:\n\t\t\tb = i\n\t\tcase uint8:\n\t\t\tb = int64(i)\n\t\tcase uint16:\n\t\t\tb = int64(i)\n\t\tcase uint32:\n\t\t\tb = int64(i)\n\t\tcase uint64:\n\t\t\tb = int64(i)\n\t\tdefault:\n\t\t\treturn errOutputType.WithAttributes(\"type\", fmt.Sprintf(\"%T\", i))\n\t\t}\n\t\tif b < 0x00 || b > 0xFF {\n\t\t\treturn errOutputRange.WithAttributes(\n\t\t\t\t\"value\", b,\n\t\t\t\t\"low\", 0x00,\n\t\t\t\t\"high\", 0xFF,\n\t\t\t)\n\t\t}\n\t\tfrmPayload[i] = byte(b)\n\t}\n\tmsg.FRMPayload = frmPayload\n\treturn nil\n}", "func (fm *FieldModelMapInt32OptionalBytes) FBEShift(size int) { fm.offset += size }", "func (turnbull *turnbull) buildScaffoldUsecaseInteractor(entity model.Entity) (error){\n\n\tif len(entity.Repositories) > 0 && len(entity.Presenters) > 0 {\n\n\t\t// Build\n\t\tbuf := &bytes.Buffer{}\n\t\terr := turnbull.generator.ScaffoldUsecaseInteractor(entity, buf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// File Name\n\t\tfileName, err := turnbull.formatter.OutputScaffoldUsecaseInteractorFile(entity)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// File\n\t\tfile, err := os.Create(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\n\t\t// Write\n\t\t_, err = file.WriteString(buf.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\t\t\n\treturn nil\n}", "func (turnbull *turnbull) buildScaffoldInterfaceController(driver string, entity model.Entity) (error){\n\n\t// Build\n\tbuf := &bytes.Buffer{}\n\terr := turnbull.generator.ScaffoldInterfaceController(driver, entity, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// File Name\n\tfileName, err := turnbull.formatter.OutputScaffoldInterfaceControllerFile(driver, entity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ensure\n\tdirName := filepath.Dir(fileName)\n\tif _, serr := os.Stat(dirName); serr != nil {\n\t\tmerr := os.MkdirAll(dirName, os.ModePerm)\n\t\tif merr != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// File\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t// Write\n\t_, err = file.WriteString(buf.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (fb *FlowBuilder) Build(ID string) flow.Operation {\n\tif fb.Err != nil {\n\t\top := fb.flow.ErrOp(fb.Err)\n\t\treturn op\n\t}\n\tf := fb.flow\n\tr := fb.registry\n\tdoc := fb.Doc\n\n\tif _, ok := fb.nodeTrack[ID]; ok {\n\t\tfb.Err = ErrLoop //fmt.Errorf(\"[%v] Looping through nodes is disabled:\", ID)\n\t\top := fb.flow.ErrOp(fb.Err)\n\t\treturn op\n\t}\n\t// loop detector\n\tfb.nodeTrack[ID] = true\n\tdefer delete(fb.nodeTrack, ID)\n\n\t// If flow already has ID just return\n\tif op, ok := fb.OperationMap[ID]; ok {\n\t\treturn op\n\t}\n\n\tnode := fb.Doc.FetchNodeByID(ID)\n\tif node == nil {\n\t\top := fb.flow.ErrOp(fmt.Errorf(\"node not found [%v]\", ID))\n\t\treturn op\n\t}\n\n\tvar op flow.Operation\n\tvar inputs []reflect.Type\n\n\tswitch node.Src {\n\tcase \"Portal From\":\n\t\tnID := node.Prop[\"portal from\"]\n\t\tn := doc.FetchNodeByID(nID)\n\t\tif n == nil {\n\t\t\treturn f.ErrOp(fmt.Errorf(\"Invalid portal, id: %v\", nID))\n\t\t}\n\t\t// Fetch existing or build new\n\t\top = fb.Build(nID)\n\t\tfb.OperationMap[node.ID] = op\n\t\treturn op\n\tcase \"Input\":\n\t\tinputID, err := strconv.Atoi(node.Prop[\"input\"])\n\t\tif err != nil {\n\t\t\top := f.ErrOp(errors.New(\"Invalid inputID value, must be a number\"))\n\t\t\tfb.OperationMap[node.ID] = op\n\t\t\treturn op\n\t\t}\n\t\top := f.In(inputID) // By id perhaps\n\t\tfb.OperationMap[node.ID] = op\n\t\treturn op\n\tcase \"Var\":\n\t\tlog.Println(\"Source is a variable\")\n\t\tvar t interface{}\n\t\tinputs = []reflect.Type{reflect.TypeOf(t)}\n\tcase \"SetVar\":\n\t\tlog.Println(\"Source is a setvariable\")\n\t\tvar t interface{}\n\t\tinputs = []reflect.Type{reflect.TypeOf(t)}\n\tdefault:\n\t\tlog.Println(\"Loading entry:\", node.Src)\n\t\tentry, err := r.Entry(node.Src)\n\t\tif err != nil {\n\t\t\top = f.ErrOp(err)\n\t\t\tfb.OperationMap[node.ID] = op\n\t\t\treturn op\n\t\t}\n\t\tinputs = entry.Inputs\n\n\t}\n\n\t//// Build inputs ////\n\tparam := make([]flow.Data, len(inputs))\n\tfor i := range param {\n\t\tl := doc.FetchLinkTo(node.ID, i)\n\t\tif l == nil { // No link we fetch the value inserted\n\t\t\t// Direct input entries\n\t\t\tv, err := parseValue(inputs[i], node.DefaultInputs[i])\n\t\t\tif err != nil {\n\t\t\t\tparam[i] = f.ErrOp(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tparam[i] = v\n\t\t\tcontinue\n\t\t}\n\t\tparam[i] = fb.Build(l.From)\n\t}\n\n\t//Switch again\n\tswitch node.Src {\n\tcase \"Var\":\n\t\top = f.Var(node.Prop[\"variable name\"], param[0])\n\tcase \"SetVar\":\n\t\top = f.SetVar(node.Prop[\"variable name\"], param[0])\n\tdefault:\n\t\top = f.Op(node.Src, param...)\n\t}\n\n\tfb.OperationMap[node.ID] = op\n\tfb.buildTriggersFor(node, op)\n\n\treturn op\n}", "func ExampleDeviceFarm_GetRun_shared00() {\n\tsvc := devicefarm.New(session.New())\n\tinput := &devicefarm.GetRunInput{\n\t\tArn: aws.String(\"arn:aws:devicefarm:us-west-2:123456789101:run:5e01a8c7-c861-4c0a-b1d5-5ec6e6c6dd23/0fcac17b-6122-44d7-ae5a-12345EXAMPLE\"),\n\t}\n\n\tresult, err := svc.GetRun(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase devicefarm.ErrCodeArgumentException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeArgumentException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotFoundException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotFoundException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeServiceAccountException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeServiceAccountException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (client *IstioDiscoveryClient) doDiscover() ([]*proto.FlowDTO, error) {\n\tvar flows []*proto.FlowDTO\n\tmetrics := client.metricHandler.GetMetrics()\n\tfor _, m := range metrics {\n\t\t// We simulate the destination port\n\t\tflow, err := builder.NewFlowDTOBuilder().\n\t\t\tSource(m.src).\n\t\t\tDestination(m.dst, DEFAULT_DESTINATION_PORT).\n\t\t\tProtocol(builder.TCP).\n\t\t\tReceived(m.rx).\n\t\t\tTransmitted(m.tx).\n\t\t\tFlowAmount((m.amount / float64(m.duration)) / KBPS).Create()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tflows = append(flows, flow)\n\t}\n\treturn flows, nil\n}", "func DoFn7x0[I0, I1, I2, I3, I4, I5, I6 any](doFn genericDoFn7x0[I0, I1, I2, I3, I4, I5, I6]) {\n\tregisterDoFnTypes(doFn)\n\tregisterDoFn7x0StructWrappersAndFuncs[I0, I1, I2, I3, I4, I5, I6](doFn)\n}", "func ExampleDeviceFarm_ListOfferings_shared00() {\n\tsvc := devicefarm.New(session.New())\n\tinput := &devicefarm.ListOfferingsInput{\n\t\tNextToken: aws.String(\"RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE=\"),\n\t}\n\n\tresult, err := svc.ListOfferings(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase devicefarm.ErrCodeArgumentException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeArgumentException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotFoundException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotFoundException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotEligibleException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotEligibleException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeServiceAccountException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeServiceAccountException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func handleNat44InterfaceOutputFeature(ifIdx uint32, isInside, isAdd bool, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\tdefer func(t time.Time) {\n\t\tstopwatch.TimeLog(nat.Nat44InterfaceAddDelOutputFeature{}).LogTimeEntry(time.Since(t))\n\t}(time.Now())\n\n\treq := &nat.Nat44InterfaceAddDelOutputFeature{\n\t\tSwIfIndex: ifIdx,\n\t\tIsInside: boolToUint(isInside),\n\t\tIsAdd: boolToUint(isAdd),\n\t}\n\n\treply := &nat.Nat44InterfaceAddDelOutputFeatureReply{}\n\tif err := vppChan.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t}\n\tif reply.Retval != 0 {\n\t\treturn fmt.Errorf(\"%s returned %d\", reply.GetMessageName(), reply.Retval)\n\t}\n\n\treturn nil\n}", "func (turnbull *turnbull) buildInterfaceControllerEntity(driver string, entity model.Entity) (error){\n\n\t// Build\n\tbuf := &bytes.Buffer{}\n\terr := turnbull.generator.InterfaceControllerEntity(driver, entity, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(buf.String()) > 0 {\n\n\t\t// File Name\n\t\tfileName, err := turnbull.formatter.OutputInterfaceControllerEntityFile(driver, entity)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Ensure\n\t\tdirName := filepath.Dir(fileName)\n\t\tif _, serr := os.Stat(dirName); serr != nil {\n\t\t\tmerr := os.MkdirAll(dirName, os.ModePerm)\n\t\t\tif merr != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// File\n\t\tfile, err := os.Create(fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\n\t\t// Write\n\t\t_, err = file.WriteString(buf.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Build Embedded\n\tfor _, field := range entity.Fields {\n\t\tif field.Embedded {\n\t\t\terr := turnbull.buildInterfaceControllerEntity(driver, field.Entity)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func TPUEmbeddingActivations(scope *Scope, embedding_variable tf.Output, sliced_activations tf.Output, table_id int64, lookup_id int64) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"table_id\": table_id, \"lookup_id\": lookup_id}\n\topspec := tf.OpSpec{\n\t\tType: \"TPUEmbeddingActivations\",\n\t\tInput: []tf.Input{\n\t\t\tembedding_variable, sliced_activations,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (_obj *DataService) AddLikeOneWayWithContext(tarsCtx context.Context, message_id string, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_string(message_id, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 1, \"addLike\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}", "func (m *Embeddings) Encode(words []string) []ag.Node {\n\tencoded := make([]ag.Node, len(words))\n\twordEmbeddings := m.getWordEmbeddings(words)\n\tsequenceIndex := 0\n\tfor i := 0; i < len(words); i++ {\n\t\tencoded[i] = wordEmbeddings[i]\n\t\tencoded[i] = m.Graph().Add(encoded[i], m.Graph().NewWrap(m.Position[i]))\n\t\tencoded[i] = m.Graph().Add(encoded[i], m.TokenType[sequenceIndex])\n\t\tif words[i] == wordpiecetokenizer.DefaultSequenceSeparator {\n\t\t\tsequenceIndex++\n\t\t}\n\t}\n\treturn m.useProjection(m.Norm.Forward(encoded...))\n}", "func (o *FemData) RunFEM(Enabled []int, Areas []float64, draw int, debug bool) (mobility, failed, weight, umax, smax, errU, errS float64) {\n\n\t// check for NaNs\n\tdefer func() {\n\t\tif math.IsNaN(mobility) || math.IsNaN(failed) || math.IsNaN(weight) || math.IsNaN(umax) || math.IsNaN(smax) || math.IsNaN(errU) || math.IsNaN(errS) {\n\t\t\tio.PfRed(\"enabled := %+#v\\n\", Enabled)\n\t\t\tio.PfRed(\"areas := %+#v\\n\", Areas)\n\t\t\tchk.Panic(\"NaN: mobility=%v failed=%v weight=%v umax=%v smax=%v errU=%v errS=%v\\n\", mobility, failed, weight, umax, smax, errU, errS)\n\t\t}\n\t}()\n\n\t// set connectivity\n\tif o.Opt.BinInt {\n\t\tfor cid, ena := range Enabled {\n\t\t\to.Dom.Msh.Cells[cid].Disabled = true\n\t\t\tif ena == 1 {\n\t\t\t\to.Dom.Msh.Cells[cid].Disabled = false\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor _, cell := range o.Dom.Msh.Cells {\n\t\t\tcid := cell.Id\n\t\t\txid := o.Cid2xid[cid]\n\t\t\to.Dom.Msh.Cells[cid].Disabled = true\n\t\t\tif Areas[xid] >= o.Opt.aEps {\n\t\t\t\to.Dom.Msh.Cells[cid].Disabled = false\n\t\t\t}\n\t\t}\n\t}\n\n\t// set stage\n\to.Analysis.SetStage(0)\n\n\t// check for required vertices\n\tnnod := len(o.Dom.Nodes)\n\tfor _, vid := range o.ReqVids {\n\t\tif o.Dom.Vid2node[vid] == nil {\n\t\t\t//io.Pforan(\"required vertex (%d) missing\\n\", vid)\n\t\t\tmobility, failed, errU, errS = float64(1+2*nnod), 1, 1, 1\n\t\t\treturn\n\t\t}\n\t}\n\n\t// compute mobility\n\tif o.Opt.Mobility {\n\t\tm := len(o.Dom.Elems)\n\t\td := len(o.Dom.EssenBcs.Bcs)\n\t\tM := 2*nnod - m - d\n\t\tif M > 0 {\n\t\t\t//io.Pforan(\"full mobility: M=%v\\n\", M)\n\t\t\tmobility, failed, errU, errS = float64(M), 1, 1, 1\n\t\t\treturn\n\t\t}\n\t}\n\n\t// set elements' cross-sectional areas and compute weight\n\tfor _, elem := range o.Dom.Elems {\n\t\tele := elem.(*solid.ElastRod)\n\t\tcid := ele.Cell.Id\n\t\txid := o.Cid2xid[cid]\n\t\tele.Mdl.A = Areas[xid]\n\t\tele.Recompute(false)\n\t\tweight += ele.Mdl.Rho * ele.Mdl.A * ele.L\n\t}\n\n\t// run FE analysis\n\terr := o.Analysis.SolveOneStage(0, true)\n\tif err != nil {\n\t\t//io.Pforan(\"analysis failed\\n\")\n\t\tmobility, failed, errU, errS = 0, 1, 1, 1\n\t\treturn\n\t}\n\n\t// find maximum deflection\n\t// Note that sometimes a mechanism can happen that makes the tip to move upwards\n\tif o.VidU >= 0 {\n\t\teq := o.Dom.Vid2node[o.VidU].GetEq(\"uy\")\n\t\tuy := o.Dom.Sol.Y[eq]\n\t\tumax = math.Abs(uy)\n\t} else {\n\t\tfor _, nod := range o.Dom.Nodes {\n\t\t\teq := nod.GetEq(\"uy\")\n\t\t\tuy := o.Dom.Sol.Y[eq]\n\t\t\tumax = utl.Max(umax, math.Abs(uy))\n\t\t}\n\t}\n\terrU = fun.Ramp(umax - o.Opt.Uawd)\n\n\t// find max stress\n\tfor _, elem := range o.Dom.Elems {\n\t\tele := elem.(*solid.ElastRod)\n\t\ttag := ele.Cell.Tag\n\t\tsig := ele.CalcSig(o.Dom.Sol)\n\t\tsmax = utl.Max(smax, math.Abs(sig))\n\t\terrS = utl.Max(errS, o.Opt.CalcErrSig(tag, sig))\n\t}\n\terrS = fun.Ramp(errS)\n\n\t// draw\n\tif draw > 0 {\n\t\targs := make(map[int]*plt.A)\n\t\tfor _, elem := range o.Dom.Elems {\n\t\t\tele := elem.(*solid.ElastRod)\n\t\t\tcid := ele.Cell.Id\n\t\t\targs[cid] = &plt.A{C: \"#004cc9\", Lw: 0.3 + ele.Mdl.A/15.0}\n\t\t}\n\t\to.Dom.Msh.Draw2d(true, false, false, nil, args, nil)\n\t}\n\n\t// debug\n\tif false && (umax > 0 && errS < 1e-10) {\n\t\tio.PfYel(\"enabled := %+#v\\n\", Enabled)\n\t\tio.Pf(\"areas := %+#v\\n\", Areas)\n\t\tio.Pf(\"weight = %v\\n\", weight)\n\t\tio.Pf(\"umax = %v\\n\", umax)\n\t\tio.Pf(\"smax = %v\\n\", smax)\n\t\tio.Pf(\"errU = %v\\n\", errU)\n\t\tio.Pf(\"errS = %v\\n\", errS)\n\n\t\t// post-processing\n\t\tmsh := o.Dom.Msh\n\t\tvid := msh.VertTag2verts[-4][0].Id\n\t\tnod := o.Dom.Vid2node[vid]\n\t\teqy := nod.GetEq(\"uy\")\n\t\tuy := o.Dom.Sol.Y[eqy]\n\t\tio.Pfblue2(\"%2d : uy = %g\\n\", vid, uy)\n\t}\n\treturn\n}", "func expand(seed string, idxs []int) string {\n\tvar out [100]byte\n\tkdf := kdf_tor_new([]byte(seed))\n\tdone := 0\n\tfor _, i := range idxs {\n\t\tif i >= done && i <= 100 {\n\t\t\t_, err := io.ReadFull(kdf, out[done:i])\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdone = i\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%x\", out)\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func TfModelLoadAndEval_work_tagger() {\n\tconst max_sentence_len_ int = 199\n\tvar input = []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\tinput_data := make([][]int32, 2)\n\tinput_tokens := make([]int32, max_sentence_len_)\n\tvar lengthInput = len(input)\n\tif lengthInput < max_sentence_len_ {\n\t\tfor i := 0; i < lengthInput; i++ {\n\t\t\tinput_tokens[i] = input[i]\n\t\t}\n\t\tfor i := lengthInput; i < max_sentence_len_; i++ {\n\t\t\tinput_tokens[i] = 0\n\t\t}\n\t}\n\tinput_data[0] = input_tokens\n\tinput_data[1] = input_tokens\n\n\tdropOutTensor, _ := tf.NewTensor(float32(0.0))\n\tinput_tensors, _ := tf.NewTensor(input_data)\n\tvar ab_length = make([]int32, 2)\n\tab_length[0] = int32(max_sentence_len_)\n\tab_length[1] = int32(max_sentence_len_)\n\tab_length_tensor, _ := tf.NewTensor(ab_length)\n\t// passed\n\t/**\n\tmodel := InitModel(\"idmg/matching/models\", \"work.pbtxt\")\n\tresult, err := model.Eval([]*tf.Tensor{input_tensors}, []string{\"sentence\"}, \"inference_final\", nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error running the session with input, err: %s \", err.Error())\n\t\treturn\n\t}\n\t*/\n\t// passed\n\tmodel := Init(\"/Users/devops/Downloads/github/models/tf_serving/work_tagger/1\", []string{\"serve\"})\n\tresult, err := model.Eval([]*tf.Tensor{input_tensors, dropOutTensor, ab_length_tensor}, []string{\"sentence\", \"dropout\", \"ab_length\"}, \"inference_final\", nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error running the session with input, err: %s \\n\", err.Error())\n\t\treturn\n\t}\n\tvalue := result[0].Value().([][]float32)\n\tfmt.Printf(\"Result value length:%v\\n\", len(value[0]))\n}", "func (o *PostAutoDiscoveryPingsweepParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\tif o.ClearExistingSchedule != nil {\n\n\t\t// form param clear_existing_schedule\n\t\tvar frClearExistingSchedule string\n\t\tif o.ClearExistingSchedule != nil {\n\t\t\tfrClearExistingSchedule = *o.ClearExistingSchedule\n\t\t}\n\t\tfClearExistingSchedule := frClearExistingSchedule\n\t\tif fClearExistingSchedule != \"\" {\n\t\t\tif err := r.SetFormParam(\"clear_existing_schedule\", fClearExistingSchedule); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.CreateNewSubnet != nil {\n\n\t\t// form param create_new_subnet\n\t\tvar frCreateNewSubnet string\n\t\tif o.CreateNewSubnet != nil {\n\t\t\tfrCreateNewSubnet = *o.CreateNewSubnet\n\t\t}\n\t\tfCreateNewSubnet := frCreateNewSubnet\n\t\tif fCreateNewSubnet != \"\" {\n\t\t\tif err := r.SetFormParam(\"create_new_subnet\", fCreateNewSubnet); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.DebugLevel != nil {\n\n\t\t// form param debug_level\n\t\tvar frDebugLevel string\n\t\tif o.DebugLevel != nil {\n\t\t\tfrDebugLevel = *o.DebugLevel\n\t\t}\n\t\tfDebugLevel := frDebugLevel\n\t\tif fDebugLevel != \"\" {\n\t\t\tif err := r.SetFormParam(\"debug_level\", fDebugLevel); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// form param name\n\tfrName := o.Name\n\tfName := frName\n\tif fName != \"\" {\n\t\tif err := r.SetFormParam(\"name\", fName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif o.Networks != nil {\n\n\t\t// form param networks\n\t\tvar frNetworks string\n\t\tif o.Networks != nil {\n\t\t\tfrNetworks = *o.Networks\n\t\t}\n\t\tfNetworks := frNetworks\n\t\tif fNetworks != \"\" {\n\t\t\tif err := r.SetFormParam(\"networks\", fNetworks); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.OverwriteSubnetCategories != nil {\n\n\t\t// form param overwrite_subnet_categories\n\t\tvar frOverwriteSubnetCategories string\n\t\tif o.OverwriteSubnetCategories != nil {\n\t\t\tfrOverwriteSubnetCategories = *o.OverwriteSubnetCategories\n\t\t}\n\t\tfOverwriteSubnetCategories := frOverwriteSubnetCategories\n\t\tif fOverwriteSubnetCategories != \"\" {\n\t\t\tif err := r.SetFormParam(\"overwrite_subnet_categories\", fOverwriteSubnetCategories); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.RemoteCollectorID != nil {\n\n\t\t// form param remote_collector_id\n\t\tvar frRemoteCollectorID int64\n\t\tif o.RemoteCollectorID != nil {\n\t\t\tfrRemoteCollectorID = *o.RemoteCollectorID\n\t\t}\n\t\tfRemoteCollectorID := swag.FormatInt64(frRemoteCollectorID)\n\t\tif fRemoteCollectorID != \"\" {\n\t\t\tif err := r.SetFormParam(\"remote_collector_id\", fRemoteCollectorID); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.ReverseDNS != nil {\n\n\t\t// form param reverse_dns\n\t\tvar frReverseDNS string\n\t\tif o.ReverseDNS != nil {\n\t\t\tfrReverseDNS = *o.ReverseDNS\n\t\t}\n\t\tfReverseDNS := frReverseDNS\n\t\tif fReverseDNS != \"\" {\n\t\t\tif err := r.SetFormParam(\"reverse_dns\", fReverseDNS); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.StripDomainSuffix != nil {\n\n\t\t// form param strip_domain_suffix\n\t\tvar frStripDomainSuffix string\n\t\tif o.StripDomainSuffix != nil {\n\t\t\tfrStripDomainSuffix = *o.StripDomainSuffix\n\t\t}\n\t\tfStripDomainSuffix := frStripDomainSuffix\n\t\tif fStripDomainSuffix != \"\" {\n\t\t\tif err := r.SetFormParam(\"strip_domain_suffix\", fStripDomainSuffix); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.SubnetCategory != nil {\n\n\t\t// form param subnet_category\n\t\tvar frSubnetCategory string\n\t\tif o.SubnetCategory != nil {\n\t\t\tfrSubnetCategory = *o.SubnetCategory\n\t\t}\n\t\tfSubnetCategory := frSubnetCategory\n\t\tif fSubnetCategory != \"\" {\n\t\t\tif err := r.SetFormParam(\"subnet_category\", fSubnetCategory); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.Tags != nil {\n\n\t\t// form param tags\n\t\tvar frTags string\n\t\tif o.Tags != nil {\n\t\t\tfrTags = *o.Tags\n\t\t}\n\t\tfTags := frTags\n\t\tif fTags != \"\" {\n\t\t\tif err := r.SetFormParam(\"tags\", fTags); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.TagsRemove != nil {\n\n\t\t// form param tags_remove\n\t\tvar frTagsRemove string\n\t\tif o.TagsRemove != nil {\n\t\t\tfrTagsRemove = *o.TagsRemove\n\t\t}\n\t\tfTagsRemove := frTagsRemove\n\t\tif fTagsRemove != \"\" {\n\t\t\tif err := r.SetFormParam(\"tags_remove\", fTagsRemove); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.Type != nil {\n\n\t\t// form param type\n\t\tvar frType string\n\t\tif o.Type != nil {\n\t\t\tfrType = *o.Type\n\t\t}\n\t\tfType := frType\n\t\tif fType != \"\" {\n\t\t\tif err := r.SetFormParam(\"type\", fType); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif o.Vrfgroup != nil {\n\n\t\t// form param vrfgroup\n\t\tvar frVrfgroup string\n\t\tif o.Vrfgroup != nil {\n\t\t\tfrVrfgroup = *o.Vrfgroup\n\t\t}\n\t\tfVrfgroup := frVrfgroup\n\t\tif fVrfgroup != \"\" {\n\t\t\tif err := r.SetFormParam(\"vrfgroup\", fVrfgroup); err != nil {\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}", "func computeFwd(_ context.Context, n *node) stateFn {\n\tv, err := n.op.Do(n.inputValues...)\n\tif err != nil {\n\t\tn.err = err\n\t\treturn nil\n\t}\n\tn.output = v\n\treturn emitOutput\n}", "func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *CetChainApp) (\n\ttesting.TB, io.Writer, *baseapp.BaseApp, simulation.AppStateFn, int64,\n\tsimulation.WeightedOperations, sdk.Invariants, int, int, int, int, string,\n\tbool, bool, bool, bool, bool, map[string]bool) {\n\n\texportParams := exportParamsPath != \"\"\n\n\treturn tb, w, app.BaseApp, appStateFn, seed,\n\t\ttestAndRunTxs(app), invariants(app),\n\t\tinitialBlockHeight, numBlocks, exportParamsHeight, blockSize,\n\t\texportStatsPath, exportParams, commit, lean, onOperation, allInvariants, app.ModuleAccountAddrs()\n}", "func ExampleDeviceFarm_ListSamples_shared00() {\n\tsvc := devicefarm.New(session.New())\n\tinput := &devicefarm.ListSamplesInput{\n\t\tArn: aws.String(\"arn:aws:devicefarm:us-west-2:123456789101:project:EXAMPLE-GUID-123-456\"),\n\t\tNextToken: aws.String(\"RW5DdDJkMWYwZjM2MzM2VHVpOHJIUXlDUXlhc2QzRGViYnc9SEXAMPLE\"),\n\t}\n\n\tresult, err := svc.ListSamples(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase devicefarm.ErrCodeArgumentException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeArgumentException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotFoundException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotFoundException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeServiceAccountException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeServiceAccountException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (fm *FinalModelStructOptional) FBEShift(size int) { fm.offset += size }", "func And(dst, src1, src2 []byte) {\n\tdstLen := len(dst)\n\tif (len(src1) != dstLen) || (len(src2) != dstLen) {\n\t\tpanic(\"And() requires len(src1) == len(src2) == len(dst).\")\n\t}\n\tif dstLen < BytesPerWord {\n\t\tfor pos, src1Byte := range src1 {\n\t\t\tdst[pos] = src1Byte & src2[pos]\n\t\t}\n\t\treturn\n\t}\n\tsrc1Data := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&src1)).Data)\n\tsrc2Data := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&src2)).Data)\n\tdstData := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&dst)).Data)\n\tnWordMinus1 := (dstLen - 1) >> Log2BytesPerWord\n\n\tsrc1Iter := src1Data\n\tsrc2Iter := src2Data\n\tdstIter := dstData\n\tfor widx := 0; widx < nWordMinus1; widx++ {\n\t\tsrc1Word := *((*uintptr)(src1Iter))\n\t\tsrc2Word := *((*uintptr)(src2Iter))\n\t\t*((*uintptr)(dstIter)) = src1Word & src2Word\n\t\tsrc1Iter = unsafe.Add(src1Iter, BytesPerWord)\n\t\tsrc2Iter = unsafe.Add(src2Iter, BytesPerWord)\n\t\tdstIter = unsafe.Add(dstIter, BytesPerWord)\n\t}\n\t// No store-forwarding problem here.\n\tfinalOffset := uintptr(dstLen - BytesPerWord)\n\tsrc1Iter = unsafe.Add(src1Data, finalOffset)\n\tsrc2Iter = unsafe.Add(src2Data, finalOffset)\n\tdstIter = unsafe.Add(dstData, finalOffset)\n\tsrc1Word := *((*uintptr)(src1Iter))\n\tsrc2Word := *((*uintptr)(src2Iter))\n\t*((*uintptr)(dstIter)) = src1Word & src2Word\n}", "func ExampleLexModelBuildingService_PutBot_shared00() {\n\tsvc := lexmodelbuildingservice.New(session.New())\n\tinput := &lexmodelbuildingservice.PutBotInput{\n\t\tAbortStatement: &lexmodelbuildingservice.Statement{\n\t\t\tMessages: []*lexmodelbuildingservice.Message{\n\t\t\t\t{\n\t\t\t\t\tContent: aws.String(\"I don't understand. Can you try again?\"),\n\t\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tContent: aws.String(\"I'm sorry, I don't understand.\"),\n\t\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tChildDirected: aws.Bool(true),\n\t\tClarificationPrompt: &lexmodelbuildingservice.Prompt{\n\t\t\tMaxAttempts: aws.Int64(1),\n\t\t\tMessages: []*lexmodelbuildingservice.Message{\n\t\t\t\t{\n\t\t\t\t\tContent: aws.String(\"I'm sorry, I didn't hear that. Can you repeat what you just said?\"),\n\t\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tContent: aws.String(\"Can you say that again?\"),\n\t\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tDescription: aws.String(\"Orders a pizza from a local pizzeria.\"),\n\t\tIdleSessionTTLInSeconds: aws.Int64(300),\n\t\tIntents: []*lexmodelbuildingservice.Intent{\n\t\t\t{\n\t\t\t\tIntentName: aws.String(\"DocOrderPizza\"),\n\t\t\t\tIntentVersion: aws.String(\"$LATEST\"),\n\t\t\t},\n\t\t},\n\t\tLocale: aws.String(\"en-US\"),\n\t\tName: aws.String(\"DocOrderPizzaBot\"),\n\t\tProcessBehavior: aws.String(\"SAVE\"),\n\t}\n\n\tresult, err := svc.PutBot(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase lexmodelbuildingservice.ErrCodeConflictException:\n\t\t\t\tfmt.Println(lexmodelbuildingservice.ErrCodeConflictException, aerr.Error())\n\t\t\tcase lexmodelbuildingservice.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(lexmodelbuildingservice.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase lexmodelbuildingservice.ErrCodeInternalFailureException:\n\t\t\t\tfmt.Println(lexmodelbuildingservice.ErrCodeInternalFailureException, aerr.Error())\n\t\t\tcase lexmodelbuildingservice.ErrCodeBadRequestException:\n\t\t\t\tfmt.Println(lexmodelbuildingservice.ErrCodeBadRequestException, aerr.Error())\n\t\t\tcase lexmodelbuildingservice.ErrCodePreconditionFailedException:\n\t\t\t\tfmt.Println(lexmodelbuildingservice.ErrCodePreconditionFailedException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (s *AllowedInputTypes) SetAllowDTMFInput(v bool) *AllowedInputTypes {\n\ts.AllowDTMFInput = &v\n\treturn s\n}", "func IFFTND(scope *Scope, input tf.Output, fft_length tf.Output, axes tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"IFFTND\",\n\t\tInput: []tf.Input{\n\t\t\tinput, fft_length, axes,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func FAQTrainAll(w http.ResponseWriter) {\n\tlog.Info(\"Retraining all........\")\n\tisTraining = true\n\n\tfaqs, err := db.GetAllFAQs()\n\tif err != nil {\n\t\tlog.Error(\"failed to get FAQs: \", err)\n\t\treturn\n\t}\n\tvar ius []intent.IntentUtterance\n\n\tcounter := 0\n\tfor _, faq := range faqs {\n\t\tfor _, v := range faq.Questions {\n\t\t\tv.Question = strings.TrimSpace(v.Question)\n\t\t\tius = append(ius, intent.IntentUtterance{faq.IntentName, v.Question})\n\t\t\tlog.Infof(\"Add utterance #%d (%s, %s) \\n\", counter, faq.IntentName, v.Question)\n\t\t\tcounter = counter + 1\n\t\t}\n\t}\n\n\terr = intent.AddIntentUtterances(ius)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to insert %d utterance. Error: %+v\\n\", len(ius), err)\n\t\treturn\n\t}\n\n\tlog.Infof(\"Start training..\")\n\terr = intent.Train()\n\tif err != nil {\n\t\tlog.Error(\"Error in FAQ Retrain: \", err)\n\t\tisTraining = false\n\t\treturn\n\t}\n\t//time.Sleep(30 * time.Second) //TODO: Remove later hungnq: work around because lacking of checking training status api\n\tisTraining = false\n\tlog.Info(\"Done\")\n\n\tfmt.Fprintln(w, \"Done\")\n}", "func BuilderFromProto(in *insightV1.SearchMessagesRequest) (*Builder, error) {\n\tb := NewFilter()\n\n\tif in.GetServiceType() != \"\" {\n\t\tb.WithServiceType(in.GetServiceType())\n\t}\n\n\tif in.GetService() != \"\" {\n\t\tb.WithService(in.GetService())\n\t}\n\n\tif in.GetIdentity() != \"\" {\n\t\tb.WithIdentity(in.GetIdentity())\n\t}\n\n\t// FIXME\n\tif in.GetSeverity() != insightV1.SeverityLevel_DEBUG {\n\t\tb.WithSeverity(in.GetSeverity())\n\t}\n\n\tif in.GetDetails() != nil {\n\t\td := utils.ValueMapFrom(in.GetDetails())\n\n\t\tb.WithDetails(d)\n\t}\n\n\tif in.GetBefore() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetBefore())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithBefore(ts)\n\t}\n\n\tif in.GetNotBefore() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetNotBefore())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithNotBefore(ts)\n\t}\n\n\tif in.GetAfter() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetAfter())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithAfter(ts)\n\t}\n\n\tif in.GetNotAfter() != nil {\n\t\tts, err := ptypes.Timestamp(in.GetNotAfter())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tb.WithNotAfter(ts)\n\t}\n\n\treturn b, nil\n}", "func (c *Client) EditEmbeds(\n\tchannelID discord.ChannelID,\n\tmessageID discord.MessageID, embeds ...discord.Embed) (*discord.Message, error) {\n\n\treturn c.EditMessageComplex(channelID, messageID, EditMessageData{\n\t\tEmbeds: &embeds,\n\t})\n}", "func (s *studentState) writeTrainhmmInput() (string, error) {\n\ttd, err := ioutil.TempDir(\"\", \"nits*\")\n\tif err != nil {\n\t\treturn td, err\n\t}\n\tvar buffer bytes.Buffer\n\n\t// One line per registered answer.\n\tfor _, a := range s.answers {\n\t\tcolumns := make([]string, 0)\n\t\tif a.correct {\n\t\t\tcolumns = append(columns, correct)\n\t\t} else {\n\t\t\tcolumns = append(columns, incorrect)\n\t\t}\n\t\tvar tag string\n\t\tif a.subQuestion == nil {\n\t\t\ttag = a.questionShortName\n\t\t} else {\n\t\t\ttag = fmt.Sprintf(\"%s#%s\", a.questionShortName, a.subQuestion.getTag())\n\t\t}\n\t\tcolumns = append(columns, \"student\", tag)\n\t\tnames := make([]string, 0)\n\t\tfor _, c := range a.question.getTrainingConcepts(a.subQuestion) {\n\t\t\tnames = append(names, c.shortName)\n\t\t}\n\t\tcolumns = append(columns, strings.Join(names, separator))\n\t\t_, err := buffer.WriteString(strings.Join(columns, \"\\t\"))\n\t\tif err != nil {\n\t\t\treturn td, err\n\t\t}\n\t\t_, err = buffer.WriteRune('\\n')\n\t\tif err != nil {\n\t\t\treturn td, err\n\t\t}\n\t}\n\n\terr = ioutil.WriteFile(path.Join(td, \"input\"), buffer.Bytes(), 0644)\n\treturn td, err\n}", "func (fm *FinalModelStructBytes) FBEShift(size int) { fm.offset += size }", "func (x *fastReflection_Input) Has(fd protoreflect.FieldDescriptor) bool {\n\tswitch fd.FullName() {\n\tcase \"cosmos.bank.v1beta1.Input.address\":\n\t\treturn x.Address != \"\"\n\tcase \"cosmos.bank.v1beta1.Input.coins\":\n\t\treturn len(x.Coins) != 0\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.bank.v1beta1.Input\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.bank.v1beta1.Input does not contain field %s\", fd.FullName()))\n\t}\n}", "func (k QKEKey) mask() {\n\tfor i := 0; i < len(k); i++ {\n\t\tk[i].SetValue(0)\n\t}\n}", "func (m *LearnedPositionalEncoder) Encode(positions []int) []ag.Node {\n\tg := m.Graph()\n\tembeddings := make([]ag.Node, len(positions))\n\tfor i, pos := range positions {\n\t\tembeddings[i] = g.NewWrap(m.Vectors[pos+m.Config.Offset])\n\t}\n\treturn embeddings\n}", "func NewFenBuilder() *FenBuilder {\n\treturn &FenBuilder{\n\t\telems: make([]string, 0),\n\t\tfile: 1,\n\t\trank: 8,\n\t}\n}", "func Run(\n\n\tctx context.Context,\n\n\t// options\n\taddr string,\n\tmeta Metadata,\n\topts lens.ConfigOpts,\n\tcfg config.TemporalConfig,\n\n\tlogger *zap.SugaredLogger,\n\n) error {\n\t// instantiate ipfs connection\n\tipfsAPI := fmt.Sprintf(\"%s:%s\", cfg.IPFS.APIConnection.Host, cfg.IPFS.APIConnection.Port)\n\tlogger.Infow(\"instantiating IPFS connection\",\n\t\t\"ipfs.api\", ipfsAPI)\n\tmanager, err := rtfs.NewManager(ipfsAPI, \"\", 1*time.Minute)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to instantiate ipfs manager: %s\", err.Error())\n\t}\n\n\t// instantiate tensorflow wrappers\n\tlogger.Infow(\"instantiating tensorflow wrappers\",\n\t\t\"tensorflow.models\", opts.ModelsPath)\n\tia, err := images.NewAnalyzer(images.ConfigOpts{\n\t\tModelLocation: opts.ModelsPath,\n\t}, logger.Named(\"analyzer\").Named(\"images\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to instantiate image analyzer: %s\", err.Error())\n\t}\n\n\t// instantiate search service\n\tlogger.Infow(\"setting up search\",\n\t\t\"search.datastore\", opts.DataStorePath)\n\tss, err := search.NewService(opts.DataStorePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to instantiate search service: %s\", err.Error())\n\t}\n\tdefer ss.Close()\n\n\t// instantiate Lens proper\n\tlogger.Info(\"instantiating lens service\")\n\tservice, err := lens.NewServiceV1(opts, cfg, manager, ia, ss, logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create connection we will listen on\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// instantiate server settings\n\tserverOpts, err := options(\n\t\tcfg.Services.Lens.TLS.CertPath,\n\t\tcfg.Services.Lens.TLS.KeyFile,\n\t\tcfg.Services.Lens.AuthKey,\n\t\tlogger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// create a grpc server\n\tvar s = &API{\n\t\tmeta: meta,\n\t\tlens: service,\n\t\tl: logger,\n\t}\n\tgServer := grpc.NewServer(serverOpts...)\n\tpb.RegisterIndexerAPIServer(gServer, s)\n\n\t// interrupt server gracefully if context is cancelled\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogger.Info(\"shutting down server\")\n\t\t\t\tgServer.GracefulStop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t// spin up server\n\tlogger.Infow(\"spinning up server\",\n\t\t\"address\", addr)\n\tif err = gServer.Serve(lis); err != nil {\n\t\tlogger.Warn(\"shutting down server\",\n\t\t\t\"error\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (w Predicates) ApplyToFor(opts *ForInput) {\n\topts.predicates = w.predicates\n}", "func ExampleDeviceFarm_StopRun_shared00() {\n\tsvc := devicefarm.New(session.New())\n\tinput := &devicefarm.StopRunInput{\n\t\tArn: aws.String(\"arn:aws:devicefarm:us-west-2:123456789101:run:EXAMPLE-GUID-123-456\"),\n\t}\n\n\tresult, err := svc.StopRun(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase devicefarm.ErrCodeArgumentException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeArgumentException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeNotFoundException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeNotFoundException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeLimitExceededException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeLimitExceededException, aerr.Error())\n\t\t\tcase devicefarm.ErrCodeServiceAccountException:\n\t\t\t\tfmt.Println(devicefarm.ErrCodeServiceAccountException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func FusedPadConv2D(scope *Scope, input tf.Output, paddings tf.Output, filter tf.Output, mode string, strides []int64, padding string) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"mode\": mode, \"strides\": strides, \"padding\": padding}\n\topspec := tf.OpSpec{\n\t\tType: \"FusedPadConv2D\",\n\t\tInput: []tf.Input{\n\t\t\tinput, paddings, filter,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func GenerateFromWIF(wif string) (*Wallet, error) {\n\tvar priv btckey.PrivateKey\n\terr := priv.FromWIF(wif)\n\tif err != nil {\n\t\treturn &Wallet{}, err\n\t}\n\n\twallet := &Wallet{\n\t\tPublicKey: priv.PublicKey.ToBytes(),\n\t\tPrivateKey: priv.ToBytes(),\n\t\tAddress: priv.ToNeoAddress(),\n\t\tWIF: priv.ToWIFC(),\n\t\tHashedSignature: priv.ToNeoSignature(),\n\t}\n\treturn wallet, nil\n}", "func flush_word(wps *WavpackStream) {\n\n\tif wps.w.zeros_acc != 0 {\n\t\tvar cbits int = count_bits(wps.w.zeros_acc)\n\n\t\tfor cbits > 0 {\n\t\t\tputbit_1(wps)\n\t\t\tcbits--\n\t\t}\n\n\t\tputbit_0(wps)\n\n\t\tfor wps.w.zeros_acc > 1 {\n\t\t\tputbit(wps.w.zeros_acc&1, wps)\n\t\t\twps.w.zeros_acc >>= 1\n\t\t}\n\n\t\twps.w.zeros_acc = 0\n\t}\n\n\tif wps.w.holding_one != 0 {\n\t\tif wps.w.holding_one >= LIMIT_ONES {\n\t\t\tvar cbits int\n\n\t\t\tputbits((1<<LIMIT_ONES)-1, LIMIT_ONES+1, wps)\n\t\t\twps.w.holding_one -= LIMIT_ONES\n\t\t\tcbits = count_bits(wps.w.holding_one)\n\n\t\t\tfor cbits > 0 {\n\t\t\t\tputbit_1(wps)\n\t\t\t\tcbits--\n\t\t\t}\n\n\t\t\tputbit_0(wps)\n\n\t\t\tfor wps.w.holding_one > 1 {\n\t\t\t\tputbit(wps.w.holding_one&1, wps)\n\t\t\t\twps.w.holding_one >>= 1\n\t\t\t}\n\n\t\t\twps.w.holding_zero = 0\n\t\t} else {\n\t\t\tputbits(bitmask[(int)(wps.w.holding_one)], wps.w.holding_one, wps)\n\t\t}\n\n\t\twps.w.holding_one = 0\n\t}\n\n\tif wps.w.holding_zero != 0 {\n\t\tputbit_0(wps)\n\t\twps.w.holding_zero = 0\n\t}\n\n\tif wps.w.pend_count != 0 {\n\t\tputbits(wps.w.pend_data, wps.w.pend_count, wps)\n\t\twps.w.pend_count = 0\n\t\twps.w.pend_data = 0\n\t}\n}", "func (x *fastReflection_Input) Clear(fd protoreflect.FieldDescriptor) {\n\tswitch fd.FullName() {\n\tcase \"cosmos.bank.v1beta1.Input.address\":\n\t\tx.Address = \"\"\n\tcase \"cosmos.bank.v1beta1.Input.coins\":\n\t\tx.Coins = nil\n\tdefault:\n\t\tif fd.IsExtension() {\n\t\t\tpanic(fmt.Errorf(\"proto3 declared messages do not support extensions: cosmos.bank.v1beta1.Input\"))\n\t\t}\n\t\tpanic(fmt.Errorf(\"message cosmos.bank.v1beta1.Input does not contain field %s\", fd.FullName()))\n\t}\n}", "func run(input string) (interface{}, interface{}) {\n\thexaPositions := parse(input)\n\n\t// part 1\n\tm := twod.Map{}\n\tfor _, p := range hexaPositions {\n\t\tflip(m, p)\n\t}\n\tpart1 := len(m)\n\n\t// part 2\n\tfor i := 0; i < 100; i++ {\n\t\tblackCounts := make(twod.Map)\n\t\tfor pos := range m {\n\t\t\tfor _, dir := range hexaDirs {\n\t\t\t\t_, exist := blackCounts[pos+dir]\n\t\t\t\tif !exist {\n\t\t\t\t\tblackCounts[pos+dir] = 0\n\t\t\t\t}\n\t\t\t\tblackCounts[pos+dir] = blackCounts[pos+dir].(int) + 1\n\t\t\t}\n\t\t}\n\t\tnewM := make(twod.Map)\n\t\tfor pos := range m {\n\t\t\tcount, exist := blackCounts[pos]\n\t\t\tif !exist || count.(int) > 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnewM[pos] = '#'\n\t\t}\n\t\tfor pos, count := range blackCounts {\n\t\t\t_, exist := m[pos]\n\t\t\tif !exist && count == 2 {\n\t\t\t\tnewM[pos] = '#'\n\t\t\t}\n\t\t}\n\t\tm = newM\n\t}\n\tpart2 := len(m)\n\n\treturn part1, part2\n}", "func (fm *FinalModelEnumUInt32) FBEShift(size int) { fm.offset += size }", "func NewSeedFromWords(input string) (Seed, error) {\n\treturn walletseed.DecodeUserInput(input)\n\n}", "func IFFT3D(scope *Scope, input tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"IFFT3D\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func hiddenAPIEncodeDex(ctx android.ModuleContext, dexInput, flagsCSV android.Path, uncompressDex bool, outputDir android.OutputPath) android.OutputPath {\n\n\t// The output file has the same name as the input file and is in the output directory.\n\toutput := outputDir.Join(ctx, dexInput.Base())\n\n\t// Create a jar specific temporary directory in which to do the work just in case this is called\n\t// with the same output directory for multiple modules.\n\ttmpDir := outputDir.Join(ctx, dexInput.Base()+\"-tmp\")\n\n\t// If the input is uncompressed then generate the output of the encode rule to an intermediate\n\t// file as the final output will need further processing after encoding.\n\tsoongZipFlags := \"\"\n\tencodeRuleOutput := output\n\tif uncompressDex {\n\t\tsoongZipFlags = \"-L 0\"\n\t\tencodeRuleOutput = outputDir.Join(ctx, \"unaligned\", dexInput.Base())\n\t}\n\n\t// b/149353192: when a module is instrumented, jacoco adds synthetic members\n\t// $jacocoData and $jacocoInit. Since they don't exist when building the hidden API flags,\n\t// don't complain when we don't find hidden API flags for the synthetic members.\n\thiddenapiFlags := \"\"\n\tif j, ok := ctx.Module().(interface {\n\t\tshouldInstrument(android.BaseModuleContext) bool\n\t}); ok && j.shouldInstrument(ctx) {\n\t\thiddenapiFlags = \"--no-force-assign-all\"\n\t}\n\n\tctx.Build(pctx, android.BuildParams{\n\t\tRule: hiddenAPIEncodeDexRule,\n\t\tDescription: \"hiddenapi encode dex\",\n\t\tInput: dexInput,\n\t\tOutput: encodeRuleOutput,\n\t\tImplicit: flagsCSV,\n\t\tArgs: map[string]string{\n\t\t\t\"flagsCsv\": flagsCSV.String(),\n\t\t\t\"tmpDir\": tmpDir.String(),\n\t\t\t\"soongZipFlags\": soongZipFlags,\n\t\t\t\"hiddenapiFlags\": hiddenapiFlags,\n\t\t},\n\t})\n\n\tif uncompressDex {\n\t\tTransformZipAlign(ctx, output, encodeRuleOutput)\n\t}\n\n\treturn output\n}", "func (t *Tfhd) Write() []byte {\n\tbuf := new(bytes.Buffer)\n\tvar err error\n\t// Size\n\terr = binary.Write(buf, binary.BigEndian, t.Size)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Write failed:\", err)\n\t}\n\t// BoxType\n\terr = binary.Write(buf, binary.BigEndian, t.BoxType)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Write failed:\", err)\n\t}\n\t//version\n\terr = binary.Write(buf, binary.BigEndian, t.Version)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Write failed:\", err)\n\t}\n\t//flags\n\terr = binary.Write(buf, binary.BigEndian, t.Flags)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Write failed:\", err)\n\t}\n\t//trackID\n\terr = binary.Write(buf, binary.BigEndian, t.TrackID)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Write failed:\", err)\n\t}\n\tif t.BaseDataOffset != 0 {\n\t\terr = binary.Write(buf, binary.BigEndian, t.BaseDataOffset)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"binary.Write failed:\", err)\n\t\t}\n\t}\n\tif t.SampleDescriptionIndex != 0 {\n\t\terr = binary.Write(buf, binary.BigEndian, t.SampleDescriptionIndex)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"binary.Write failed:\", err)\n\t\t}\n\t}\n\tif t.DefaultSampleDuration != 0 {\n\t\terr = binary.Write(buf, binary.BigEndian, t.DefaultSampleDuration)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"binary.Write failed:\", err)\n\t\t}\n\t}\n\tif t.DefaultSampleSize != 0 {\n\t\terr = binary.Write(buf, binary.BigEndian, t.DefaultSampleSize)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"binary.Write failed:\", err)\n\t\t}\n\t}\n\tif t.DefaultSampleFlags != 0 {\n\t\terr = binary.Write(buf, binary.BigEndian, t.DefaultSampleFlags)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"binary.Write failed:\", err)\n\t\t}\n\t}\n\treturn buf.Bytes()\n}", "func (sm *SoftMax) Train(targ int) {\n\tsm.Target = targ\n\tsm.Back()\n}", "func (a *Activity) ShowSoftInput(flags int) {\n\tC.ANativeActivity_showSoftInput(a.cptr(), C.uint32_t(flags))\n}", "func DoFn0x0(doFn genericDoFn0x0) {\n\tregisterDoFnTypes(doFn)\n\tregisterDoFn0x0StructWrappersAndFuncs(doFn)\n}", "func (_m *ISession) ChannelMessageEditEmbeds(channelID string, messageID string, embeds []*discordgo.MessageEmbed, options ...discordgo.RequestOption) (*discordgo.Message, error) {\n\t_va := make([]interface{}, len(options))\n\tfor _i := range options {\n\t\t_va[_i] = options[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, channelID, messageID, embeds)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 *discordgo.Message\n\tvar r1 error\n\tif rf, ok := ret.Get(0).(func(string, string, []*discordgo.MessageEmbed, ...discordgo.RequestOption) (*discordgo.Message, error)); ok {\n\t\treturn rf(channelID, messageID, embeds, options...)\n\t}\n\tif rf, ok := ret.Get(0).(func(string, string, []*discordgo.MessageEmbed, ...discordgo.RequestOption) *discordgo.Message); ok {\n\t\tr0 = rf(channelID, messageID, embeds, options...)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*discordgo.Message)\n\t\t}\n\t}\n\n\tif rf, ok := ret.Get(1).(func(string, string, []*discordgo.MessageEmbed, ...discordgo.RequestOption) error); ok {\n\t\tr1 = rf(channelID, messageID, embeds, options...)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (turnbull *turnbull) buildScaffoldInterfacePresenter(driver string, entity model.Entity) (error){\n\n\t// Build\n\tbuf := &bytes.Buffer{}\n\terr := turnbull.generator.ScaffoldInterfacePresenter(driver, entity, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// File Name\n\tfileName, err := turnbull.formatter.OutputScaffoldInterfacePresenterFile(driver, entity)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Ensure\n\tdirName := filepath.Dir(fileName)\n\tif _, serr := os.Stat(dirName); serr != nil {\n\t\tmerr := os.MkdirAll(dirName, os.ModePerm)\n\t\tif merr != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// File\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t// Write\n\t_, err = file.WriteString(buf.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func HmmGenerate(length int, model *hmmModel, param *HmmGenerateOptionalParam) (*mat.Dense, *mat.Dense) {\n params := getParams(\"hmm_generate\")\n timers := getTimers()\n\n disableBacktrace()\n disableVerbose()\n // Detect if the parameter was passed; set if so.\n setParamInt(params, \"length\", length)\n setPassed(params, \"length\")\n\n // Detect if the parameter was passed; set if so.\n setHMMModel(params, \"model\", model)\n setPassed(params, \"model\")\n\n // Detect if the parameter was passed; set if so.\n if param.Seed != 0 {\n setParamInt(params, \"seed\", param.Seed)\n setPassed(params, \"seed\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.StartState != 0 {\n setParamInt(params, \"start_state\", param.StartState)\n setPassed(params, \"start_state\")\n }\n\n // Detect if the parameter was passed; set if so.\n if param.Verbose != false {\n setParamBool(params, \"verbose\", param.Verbose)\n setPassed(params, \"verbose\")\n enableVerbose()\n }\n\n // Mark all output options as passed.\n setPassed(params, \"output\")\n setPassed(params, \"state\")\n\n // Call the mlpack program.\n C.mlpackHmmGenerate(params.mem, timers.mem)\n\n // Initialize result variable and get output.\n var outputPtr mlpackArma\n output := outputPtr.armaToGonumMat(params, \"output\")\n var statePtr mlpackArma\n state := statePtr.armaToGonumUmat(params, \"state\")\n // Clean memory.\n cleanParams(params)\n cleanTimers(timers)\n // Return output(s).\n return output, state\n}", "func (f CreateIdxOptFunc) ApplyOn(opt *AddRecordOpt) {\n\tf(&opt.CreateIdxOpt)\n}", "func (m *DeviceManagementRequestBuilder) ImportedWindowsAutopilotDeviceIdentities()(*id29dcfda2bb98b4b7cf7bd4f6740f350afac6e45624c646636f5fc440f552695.ImportedWindowsAutopilotDeviceIdentitiesRequestBuilder) {\n return id29dcfda2bb98b4b7cf7bd4f6740f350afac6e45624c646636f5fc440f552695.NewImportedWindowsAutopilotDeviceIdentitiesRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (s *Model) Train(samples sgd.SampleSet) {\n\tindices := rand.Perm(samples.Len())\n\tfor _, i := range indices {\n\t\tsample := samples.GetSample(i).(seqtoseq.Sample)\n\t\tstate := stochnet.ConstBoolVec(make([]bool, s.StateSize))\n\t\tfor t, in := range sample.Inputs {\n\t\t\tout := floatsToBools(sample.Outputs[t]).Activations()\n\t\t\tjoinedIn := stochnet.Concat(state, floatsToBools(in))\n\t\t\tstate = s.StateLayer.Apply(joinedIn)\n\t\t\toutput := s.OutputLayer.Apply(state)\n\t\t\tchange := make([]bool, len(output.Activations()))\n\t\t\tfor j, o := range output.Activations() {\n\t\t\t\tchange[j] = (out[j] != o)\n\t\t\t}\n\t\t\toutput.Learn(change)\n\t\t}\n\t}\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (s Seed) EncodeWords() []string {\n\treturn walletseed.EncodeMnemonicSlice(s)\n}", "func main() {\n\targs := os.Args[1:]\n\tapi, err := fog05.NewFIMAPI(args[0], nil, nil)\n\tcheck(err)\n\n\tfmt.Printf(\"Nodes:\\n\")\n\tnodes, err := api.Node.List()\n\tcheck(err)\n\n\tfor _, n := range nodes {\n\t\tfmt.Printf(\"UUID: %s\\n\", n)\n\t}\n\n\tdata, err := ioutil.ReadFile(args[1])\n\tcheck(err)\n\n\tfduDescriptor := fog05.FDU{}\n\tjson.Unmarshal(data, &fduDescriptor)\n\n\tfmt.Printf(\"Press enter to onboard descriptor\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(5 * time.Second)\n\n\tfduD, err := api.FDU.Onboard(fduDescriptor)\n\tcheck(err)\n\tfmt.Printf(\"Result of onboarding\\n%+v\\n\", fduD)\n\n\tfID := *fduD.UUID\n\n\tfmt.Printf(\"Press enter to define\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\n\t// time.Sleep(5 * time.Second)\n\n\tfduR, err := api.FDU.Define(n1, fID)\n\tcheck(err)\n\tfmt.Printf(\"Result of define:\\n%+v\\n\", fduR)\n\n\tiID := fduR.UUID\n\n\tfmt.Printf(\"Press enter to configure\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(30 * time.Second)\n\t_, err = api.FDU.Configure(iID)\n\tcheck(err)\n\n\tfmt.Printf(\"Press enter to start\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(30 * time.Second)\n\t_, err = api.FDU.Start(iID)\n\tcheck(err)\n\n\tfmt.Printf(\"Press enter to get instance info\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(30 * time.Second)\n\tinfo, err := api.FDU.InstanceInfo(iID)\n\tcheck(err)\n\n\tfmt.Printf(\"Instance Info:\\n%+v\\n\", info)\n\n\tfmt.Printf(\"Press enter to stop\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(30 * time.Second)\n\t_, err = api.FDU.Stop(iID)\n\tcheck(err)\n\n\tfmt.Printf(\"Press enter to Clean\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(30 * time.Second)\n\t_, err = api.FDU.Clean(iID)\n\tcheck(err)\n\n\tfmt.Printf(\"Press enter to Remove\\n\")\n\tbufio.NewReader(os.Stdin).ReadBytes('\\n')\n\t// time.Sleep(30 * time.Second)\n\t_, err = api.FDU.Undefine(iID)\n\tcheck(err)\n\n\t_, err = api.FDU.Offload(fID)\n\tcheck(err)\n}", "func NewListDCForSeedParamsWithTimeout(timeout time.Duration) *ListDCForSeedParams {\n\tvar ()\n\treturn &ListDCForSeedParams{\n\n\t\ttimeout: timeout,\n\t}\n}", "func FusedResizeAndPadConv2D(scope *Scope, input tf.Output, size tf.Output, paddings tf.Output, filter tf.Output, mode string, strides []int64, padding string, optional ...FusedResizeAndPadConv2DAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"mode\": mode, \"strides\": strides, \"padding\": padding}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"FusedResizeAndPadConv2D\",\n\t\tInput: []tf.Input{\n\t\t\tinput, size, paddings, filter,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}" ]
[ "0.43194455", "0.41344866", "0.41018224", "0.40161535", "0.3945738", "0.391739", "0.37510443", "0.3740854", "0.36417305", "0.36374965", "0.35823515", "0.350722", "0.35027307", "0.3458461", "0.34578133", "0.3431309", "0.34074798", "0.33991477", "0.33961838", "0.33838093", "0.33614996", "0.33566073", "0.33488777", "0.33089116", "0.3308549", "0.33055034", "0.33033404", "0.33000866", "0.33000642", "0.32750094", "0.32731354", "0.32615122", "0.3258944", "0.32447693", "0.32326478", "0.32259157", "0.32148296", "0.3214342", "0.32027438", "0.31965345", "0.31959745", "0.318973", "0.3188883", "0.31834927", "0.31816494", "0.31775868", "0.3169955", "0.31462568", "0.3141848", "0.31393096", "0.31329757", "0.31296435", "0.3122039", "0.31213626", "0.3120729", "0.31183407", "0.31073058", "0.31017473", "0.30960676", "0.30946806", "0.3079696", "0.30724868", "0.3069084", "0.3060567", "0.30583116", "0.30573648", "0.305712", "0.30549225", "0.30459258", "0.30455294", "0.30448067", "0.30447268", "0.3037471", "0.30342835", "0.3032864", "0.30298263", "0.30296588", "0.30284858", "0.30271634", "0.30250138", "0.3024629", "0.30163175", "0.301243", "0.30120274", "0.30115417", "0.30094874", "0.3008924", "0.30057713", "0.30056992", "0.30035833", "0.30008885", "0.29990914", "0.29972857", "0.2996061", "0.29943433", "0.2987604", "0.29864845", "0.29837623", "0.29836008", "0.29829383" ]
0.43332857
0
NewRobertaClassificationHead create a new RobertaClassificationHead.
func NewRobertaClassificationHead(p *nn.Path, config *bert.BertConfig) *RobertaClassificationHead { dense := nn.NewLinear(p.Sub("dense"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig()) numLabels := int64(len(config.Id2Label)) outProj := nn.NewLinear(p.Sub("out_proj"), config.HiddenSize, numLabels, nn.DefaultLinearConfig()) dropout := util.NewDropout(config.HiddenDropoutProb) return &RobertaClassificationHead{ dense: dense, dropout: dropout, outProj: outProj, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\n\tlayerNormConfig := nn.DefaultLayerNormConfig()\n\tlayerNormConfig.Eps = 1e-12\n\tlayerNorm := nn.NewLayerNorm(p.Sub(\"layer_norm\"), []int64{config.HiddenSize}, layerNormConfig)\n\n\tdecoder := util.NewLinearNoBias(p.Sub(\"decoder\"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig())\n\n\tbias := p.NewVar(\"bias\", []int64{config.VocabSize}, nn.NewKaimingUniformInit())\n\n\treturn &RobertaLMHead{\n\t\tdense: dense,\n\t\tdecoder: decoder,\n\t\tlayerNorm: layerNorm,\n\t\tbias: bias,\n\t}\n}", "func newHead(vres *salesviews.HeadView) *Head {\n\tres := &Head{}\n\tif vres.ID != nil {\n\t\tres.ID = *vres.ID\n\t}\n\tif vres.Name != nil {\n\t\tres.Name = *vres.Name\n\t}\n\treturn res\n}", "func NewHead(children ...Element) Element {\n\treturn newWithChildren(\"head\", children)\n}", "func NewHeadTracker(orm *models.ORM) (*HeadTracker, error) {\n\tht := &HeadTracker{orm: orm}\n\tblockHeaders := []models.BlockHeader{}\n\terr := orm.AllByIndex(\"Number\", &blockHeaders, storm.Limit(1), storm.Reverse())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(blockHeaders) > 0 {\n\t\tht.blockHeader = &blockHeaders[0]\n\t}\n\treturn ht, nil\n}", "func NewRobertaForSequenceClassification(p *nn.Path, config *bert.BertConfig) *RobertaForSequenceClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tclassifier := NewRobertaClassificationHead(p.Sub(\"classifier\"), config)\n\n\treturn &RobertaForSequenceClassification{\n\t\troberta: roberta,\n\t\tclassifier: classifier,\n\t}\n}", "func NewHead(charset string, metas ...*Element) *Head {\n\th := new(Head)\n\th.Element = NewElement(\"head\")\n\tif charset != \"\" {\n\t\th.Charset = charset\n\t}\n\th.AddMetas(metas...)\n\treturn h\n}", "func newHeadView(res *Head) *salesviews.HeadView {\n\tvres := &salesviews.HeadView{\n\t\tID: &res.ID,\n\t\tName: &res.Name,\n\t}\n\treturn vres\n}", "func CreateHead(samples []*MetricSample, chunkRange int64, logger log.Logger) (*Head, error) {\n\thead, err := NewHead(nil, logger, nil, chunkRange)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapp := head.Appender()\n\tfor _, sample := range samples {\n\t\t_, err = app.Add(sample.Labels, sample.TimestampMs, sample.Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\terr = app.Commit()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn head, nil\n}", "func NewHeadline(val string) HeadlineField {\n\treturn HeadlineField{quickfix.FIXString(val)}\n}", "func New(questionsPath string, textPath string) *Truman {\n\tt := &Truman{}\n\n\tquestionsFilePath, _ := filepath.Abs(questionsPath)\n\ttextFilePath, _ := filepath.Abs(textPath)\n\n\tt.loadQuestions(questionsFilePath)\n\tt.loadText(textFilePath)\n\n\treturn t\n}", "func NewHeadline() *Headline {\n\treturn &Headline{}\n}", "func NewHeadBook(ds ds.TxnDatastore) core.HeadBook {\n\treturn &dsHeadBook{\n\t\tds: ds,\n\t}\n}", "func NewRobertaForTokenClassification(p *nn.Path, config *bert.BertConfig) *RobertaForTokenClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tnumLabels := int64(len(config.Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForTokenClassification{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewRoar(author string, text string) *Roar {\n return &Roar{Author: author, Text: text,\n CreationDate: time.LocalTime().Format(time.RFC1123)}\n}", "func (c *ClassificationsController) Create(ctx *app.CreateClassificationsContext) error {\n\t// ClassificationsController_Create: start_implement\n\tm, err := c.fm()\n\tif err != nil {\n\t\tgoa.ContextLogger(ctx).Error(`unable to get model`, `error`, err.Error())\n\t\treturn ctx.ServiceUnavailable()\n\t}\n\tdefer func() { m.Close() }()\n\n\t_, err = m.InsertClassification(ctx.SeriesID, ctx.Payload.ClassID)\n\tif err != nil {\n\t\tgoa.ContextLogger(ctx).Error(`failed to insert classification`, `error`, err.Error())\n\t\tswitch err {\n\t\tcase model.ErrDuplicateKey:\n\t\t\treturn ctx.UnprocessableEntity()\n\t\tcase model.ErrInvalidID:\n\t\t\treturn ctx.UnprocessableEntity()\n\t\tdefault:\n\t\t\treturn ctx.InternalServerError()\n\t\t}\n\t}\n\n\tctx.ResponseData.Header().Set(\"Location\", app.ClassificationsHref(ctx.SeriesID, ctx.Payload.ClassID))\n\treturn ctx.Created()\n\t// ClassificationsController_Create: end_implement\n}", "func (c Client) CreateRanker(name string, trainingData io.Reader) (Ranker, error) {\n\tbuf := &bytes.Buffer{}\n\tw := multipart.NewWriter(buf)\n\tpart, err := w.CreateFormFile(\"file\", \"training_data\")\n\tif err != nil {\n\t\treturn Ranker{}, err\n\t}\n\t_, err = io.Copy(part, trainingData)\n\tif err != nil {\n\t\treturn Ranker{}, err\n\t}\n\tvar meta struct {\n\t\tName string `json:\"name\"`\n\t}\n\tmeta.Name = name\n\tmeta_json, err := json.Marshal(meta)\n\tif err != nil {\n\t\treturn Ranker{}, err\n\t}\n\tw.WriteField(\"training_metadata\", string(meta_json))\n\tw.Close()\n\n\theaders := make(http.Header)\n\theaders.Set(\"Content-Type\", w.FormDataContentType())\n\theaders.Set(\"Accept\", \"application/json\")\n\n\tbody, err := c.watsonClient.MakeRequest(\"POST\", c.version+\"/rankers\", buf, headers)\n\tif err != nil {\n\t\treturn Ranker{}, err\n\t}\n\tvar response Ranker\n\terr = json.Unmarshal(body, &response)\n\treturn response, err\n}", "func CreateNewClass(c *gin.Context) {\n\n\t// // Initialize database connection\n\tdb := config.DatabaseConn()\n\n\t// Declare parameters\n\tIDClassroom := uuid.Must(uuid.NewV4())\n\tUUIDClassroom := uuid.Must(uuid.NewV4())\n\tClassroomName := c.Param(\"ClassroomName\")\n\tClassroomTime := c.Param(\"ClassroomTime\")\n\tRoom := c.Param(\"Room\")\n\tUUIDParticipants := c.Param(\"UUIDParticipants\")\n\n\t// Bind in one parameters\n\tcreateClassroomPayload := model.Classroom{\n\t\tIDClassroom: IDClassroom,\n\t\tUUIDClassroom: UUIDClassroom,\n\t\tClassroomName: ClassroomName,\n\t\tClassroomTime: ClassroomTime,\n\t\tRoom: Room,\n\t\tUUIDParticipants: UUIDParticipants}\n\n\t// Bind parameter as JSON Parameters\n\tc.BindJSON(&createClassroomPayload)\n\n\t// Save in database\n\tdb.Save(&createClassroomPayload)\n\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Inserted successfully\"})\n}", "func newPerson(name string,class string, nationality string ) *Person {\n\treturn &Person{name: name,job: class, nationality: nationality}\n\n}", "func NewHeadTracker(store *strpkg.Store, callbacks []strpkg.HeadTrackable, sleepers ...utils.Sleeper) *HeadTracker {\n\tvar sleeper utils.Sleeper\n\tif len(sleepers) > 0 {\n\t\tsleeper = sleepers[0]\n\t} else {\n\t\tsleeper = utils.NewBackoffSleeper()\n\t}\n\treturn &HeadTracker{\n\t\tstore: store,\n\t\tcallbacks: callbacks,\n\t\tsleeper: sleeper,\n\t}\n}", "func NewClassifier(ctx *pulumi.Context,\n\tname string, args *ClassifierArgs, opts ...pulumi.ResourceOption) (*Classifier, error) {\n\tif args == nil {\n\t\targs = &ClassifierArgs{}\n\t}\n\n\tvar resource Classifier\n\terr := ctx.RegisterResource(\"aws:glue/classifier:Classifier\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func New() *Classifier {\n\treturn &Classifier{\n\t\tNewFrequencyStorage(),\n\t}\n}", "func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (siotchain.Subscription, error) {\n\treturn ec.c.SiotSubscribe(ctx, ch, \"newHeads\", map[string]struct{}{})\n}", "func NewClassifierFromFile(path string) (Classifier, error) {\n\tclassifier := Classifier{}\n\n\tfl, err := os.Open(path)\n\tif err != nil {\n\t\treturn classifier, err\n\t}\n\tdefer fl.Close()\n\n\terr = gob.NewDecoder(fl).Decode(&classifier)\n\tif err != nil {\n\t\treturn classifier, err\n\t}\n\n\treturn classifier, err\n}", "func NewClassifier(model Model) Classifier {\n\treturn Classifier{\n\t\tModel: model,\n\t\tLearningResults: make(map[string]map[Class]int),\n\t\tPriorProbabilities: make(map[Class]float64),\n\t\tNDocumentByClass: make(map[Class]int),\n\t\tNFrequencyByClass: make(map[Class]int),\n\t}\n}", "func (b batchPredictor) NewPredictor() predHelp.Predictor {\n\treturn b\n}", "func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *rpcHeader) (ethereum.Subscription, error) {\n\treturn ec.c.EthSubscribe(ctx, ch, \"newHeads\")\n}", "func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {\n\tec.Send(generalCost)\n\treturn ec.c.SubscribeNewHead(ctx, ch)\n}", "func New(value interface{}, comparator comparator.Less) *RBTree {\n\treturn &RBTree{value: value, less: comparator, color: \"black\"}\n}", "func NewClassifierFromFile(name string) (c *Classifier, err error) {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %q: %w\", name, err)\n\t}\n\tdefer file.Close()\n\n\treturn NewClassifierFromReader(file)\n}", "func (KNN *KNNRegressor) New(name string, labels []float64, numbers []float64, x int, y int) {\n\n\tKNN.Data = *mat.MakeDenseMatrix(numbers, x, y)\n\tKNN.Name = name\n\tKNN.Labels = labels\n}", "func NewHeader(text []byte, r []*Reference) (*Header, error) {\n\tvar err error\n\tbh := &Header{\n\t\trefs: r,\n\t\tseenRefs: set{},\n\t\tseenGroups: set{},\n\t\tseenProgs: set{},\n\t}\n\tfor i, r := range bh.refs {\n\t\tif r.owner != nil || r.id >= 0 {\n\t\t\treturn nil, errUsedReference\n\t\t}\n\t\tr.owner = bh\n\t\tr.id = int32(i)\n\t}\n\tif text != nil {\n\t\terr = bh.UnmarshalText(text)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn bh, nil\n}", "func (fbo *folderBranchOps) SetInitialHeadToNew(\n\tctx context.Context, id tlf.ID, handle *tlfhandle.Handle) (err error) {\n\tstartTime, timer := fbo.startOp(ctx, \"SetInitialHeadToNew %s\", id)\n\tdefer func() {\n\t\tfbo.endOp(\n\t\t\tctx, startTime, timer, \"SetInitialHeadToNew %s done: %+v\", id, err)\n\t}()\n\n\trmd, err := makeInitialRootMetadata(\n\t\tfbo.config.MetadataVersion(), id, handle)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn runUnlessCanceled(ctx, func() error {\n\t\t// New heads can only be set for the MasterBranch.\n\t\tfb := data.FolderBranch{Tlf: rmd.TlfID(), Branch: data.MasterBranch}\n\t\tif fb != fbo.folderBranch {\n\t\t\treturn WrongOpsError{fbo.folderBranch, fb}\n\t\t}\n\n\t\t// Always identify first when trying to initialize the folder,\n\t\t// even if we turn out not to be a writer. (We can't rely on\n\t\t// the identifyOnce call in getMDLocked, because that isn't\n\t\t// called from the initialization code path when the local\n\t\t// user is not a valid writer.) Also, we want to make sure we\n\t\t// fail before we set the head, otherwise future calls will\n\t\t// succeed incorrectly.\n\t\terr = fbo.identifyOnce(ctx, rmd.ReadOnly())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlState := makeFBOLockState()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\treturn fbo.initMDLocked(ctx, lState, rmd)\n\t})\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func NewHeadListener(lggr logger.Logger, ethClient evmclient.Client, config Config, chStop chan struct{}) httypes.HeadListener {\n\treturn &headListener{\n\t\tconfig: config,\n\t\tethClient: ethClient,\n\t\tlogger: lggr.Named(logger.HeadListener),\n\t\tchStop: chStop,\n\t}\n}", "func NewChainHeadTracker(t mockConstructorTestingTNewChainHeadTracker) *ChainHeadTracker {\n\tmock := &ChainHeadTracker{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (hb *Horsebase) New() *Horsebase {\n\n\thb = &Horsebase{\n\t\tStdout: os.Stdout,\n\t\tStderr: os.Stderr,\n\t}\n\n\thb.dir = path.Dir(os.Args[0])\n\n\t_, err := toml.DecodeFile(hb.dir+\"/file/horsebase.toml\", &hb)\n\tif err != nil {\n\t\t_, err := toml.DecodeFile(\"./file/horsebase.toml\", &hb)\n\t\tif err != nil {\n\t\t\tPrintError(hb.Stderr, \"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\thb.Config.HorseHtmlPath = hb.dir + hb.Config.HorseHtmlPath\n\thb.Config.RaceHtmlPath = hb.dir + hb.Config.RaceHtmlPath\n\thb.Config.CardHtmlPath = hb.dir + hb.Config.CardHtmlPath\n\n\treturn hb\n}", "func (t *OpenconfigQos_Qos_Classifiers) NewClassifier(Name string) (*OpenconfigQos_Qos_Classifiers_Classifier, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Classifier == nil {\n\t\tt.Classifier = make(map[string]*OpenconfigQos_Qos_Classifiers_Classifier)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Classifier[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Classifier\", key)\n\t}\n\n\tt.Classifier[key] = &OpenconfigQos_Qos_Classifiers_Classifier{\n\t\tName: &Name,\n\t}\n\n\treturn t.Classifier[key], nil\n}", "func NewHeader(t, subject, issuer string) (*ClaimHeader, string, error) {\n\tch := &ClaimHeader{\n\t\tType: t,\n\t\tSubject: subject,\n\t\tIssuer: issuer,\n\t}\n\treturn ch, ch.ID(), ch.Set()\n}", "func CreateClassification(params types.ContextParams, clientSet apimachinery.ClientSetInterface, clsItems []metadata.Classification) []Classification {\n\tresults := make([]Classification, 0)\n\tfor _, cls := range clsItems {\n\n\t\tresults = append(results, &classification{\n\t\t\tcls: cls,\n\t\t\tparams: params,\n\t\t\tclientSet: clientSet,\n\t\t})\n\t}\n\n\treturn results\n}", "func NewClassifierFromReader(r io.Reader) (c *Classifier, err error) {\n\tdec := gob.NewDecoder(r)\n\tw := new(Classifier)\n\terr = dec.Decode(w)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode as Classifier: %w\", err)\n\t}\n\n\treturn w, nil\n}", "func CreateHCN(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar newHCN mymodels.HCN\n\treqBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, err.Error())\n\t\treturn\n\t}\n\tjson.Unmarshal(reqBody, &newHCN)\n\n\t// Fields validation\n\tstructFields := []string{\"TeacherID\", \"MongoID\"} // struct fields to check\n\t_, err = newHCN.ValidateFields(structFields)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, err.Error())\n\t\treturn\n\t}\n\n\t// Data insertion into db\n\t_, err = dbHelper.Insert(newHCN)\n\tif err != nil {\n\t\tif strings.Split(err.Error(), \":\")[0] == \"(db 2) Error 1062\" {\n\t\t\tw.WriteHeader(http.StatusConflict)\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\tfmt.Fprintf(w, err.Error())\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusCreated)\n\treturn\n}", "func New(s *species.Species, c *culture.Culture, logger Logger) *Being {\n\treturn &Being{\n\t\tName: &Name{},\n\t\tSpeciesID: s.GetID(),\n\t\tCultureID: c.GetID(),\n\t\tSpecies: s,\n\t\tCulture: c,\n\t\tChromosome: genetics.RandomChromosome(30),\n\t\tGender: inhabitants.Asexual,\n\t\tlogger: logger,\n\t}\n}", "func NewRHT() *RHT {\n\treturn &RHT{\n\t\telementQueueMapByKey: make(map[string]*PriorityQueue),\n\t\titemMapByCreatedAt: make(map[string]*PQItem),\n\t}\n}", "func NewHead(url string) *Request { return NewRequest(\"HEAD\", url) }", "func (g *GitLab) BranchHead(ctx context.Context, u *model.User, r *model.Repo, branch string) (string, error) {\n\ttoken := common.UserToken(ctx, r, u)\n\tclient, err := newClient(g.url, token, g.SkipVerify)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_repo, err := g.getProject(ctx, client, r.Owner, r.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb, _, err := client.Branches.GetBranch(_repo.ID, branch, gitlab.WithContext(ctx))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn b.Commit.ID, nil\n}", "func NewTitle(c *http.Client, id string) (*Title, error) {\n\tif !ttRE.MatchString(id) {\n\t\treturn nil, ErrInvalidID\n\t}\n\tresp, err := c.Get(fmt.Sprintf(titleURL, id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tif resp.StatusCode == http.StatusForbidden {\n\t\t\treturn nil, errors.New(\"forbidden (e.g. denied by AWS WAF)\")\n\t\t}\n\t\treturn nil, fmt.Errorf(\"imdb: status not ok: %v\", resp.Status)\n\t}\n\tpage, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := Title{}\n\tif err := t.Parse(page); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &t, nil\n}", "func (s *topoService) CreateClassification(params types.ContextParams, pathParams, queryParams ParamsGetter, data frtypes.MapStr) (interface{}, error) {\n\n\tcls, err := s.core.ClassificationOperation().CreateClassification(params, data)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\treturn cls.ToMapStr()\n}", "func NewClass(r *http.Request) (class Class, err error) {\n\terr = r.ParseMultipartForm(utilities.MAX_STORAGE)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&class, r.PostForm)\n\treturn\n}", "func NewBranch() policydef.Policy {\n\tvar b Branch\n\treturn b\n}", "func NewCARBODY(config configuration_pkg.CONFIGURATION) *CARBODY_IMPL {\r\n client := new(CARBODY_IMPL)\r\n client.config = config\r\n return client\r\n}", "func NewClassificationsController(service *goa.Service, fm Fmodeler) *ClassificationsController {\n\treturn &ClassificationsController{\n\t\tController: service.NewController(\"ClassificationsController\"),\n\t\tfm: fm,\n\t}\n}", "func NewTableHeader() TableHeader {\n\treturn TableHeader{}\n}", "func New(genesisHeader util.BlockHeader, db database.ChainStore) (*BlockChain, error) {\n\t// Init genesis header\n\t_, err := db.Headers().GetBest()\n\tif err != nil {\n\t\tstoreHeader := &util.Header{BlockHeader: genesisHeader, TotalWork: new(big.Int)}\n\t\tif err := db.Headers().Put(storeHeader, true); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &BlockChain{db: db}, nil\n}", "func (r *MockRepoManager) CreateNewRoll(ctx context.Context, from, to string, emails []string, cqExtraTrybots string, dryRun bool) (int64, error) {\n\tr.mtx.RLock()\n\tdefer r.mtx.RUnlock()\n\treturn r.mockIssueNumber, nil\n}", "func NewHeader(color color.Color, labels ...string) *Header {\n\th := &Header{widget.BaseWidget{}, labels, color}\n\th.ExtendBaseWidget(h)\n\treturn h\n}", "func NewClassificationRepo(client *clientv3.Client) *ClassificationRepo {\n\treturn &ClassificationRepo{\n\t\tclient: client,\n\t}\n}", "func New(ringWeight int) LoadBalancer {\n\t// TODO: Implement this!\n\tnewLB := new(loadBalancer)\n\tnewLB.sortedNames = make([]MMENode, 0)\n\tnewLB.weight = ringWeight\n\tnewLB.hashRing = NewRing()\n\tif 7 == 2 {\n\t\tfmt.Println(ringWeight)\n\t}\n\treturn newLB\n}", "func (m Molpro) MakeHead() []string {\n\treturn []string{\"memory,1125,m\",\n\t\t\"gthresh,energy=1.d-10,zero=1.d-16,oneint=1.d-16,twoint=1.d-16;\",\n\t\t\"gthresh,optgrad=1.d-8,optstep=1.d-8;\",\n\t\t\"nocompress\",\n\t\t\"geomtyp=xyz\",\n\t\t\"angstrom\",\n\t\t\"geometry={\"}\n}", "func New(name, helptext string) Creator {\n\tif ctorImpl == nil {\n\t\treturn &noop{}\n\t} else {\n\t\treturn ctorImpl(name, helptext)\n\t}\n}", "func TestHead(t *testing.T) {\n\ttf.UnitTest(t)\n\n\tctx := context.TODO()\n\tbuilder := chain.NewBuilder(t, address.Undef)\n\tgenTS := builder.Genesis()\n\tr := builder.Repo()\n\tbs := builder.BlockStore()\n\tcs := chain.NewStore(r.ChainDatastore(), bs, genTS.At(0).Cid(), chain.NewMockCirculatingSupplyCalculator())\n\tcboreStore := &CborBlockStore{\n\t\tStore: chain.NewStore(r.ChainDatastore(), bs, genTS.At(0).Cid(), chain.NewMockCirculatingSupplyCalculator()),\n\t}\n\t// Construct test chain data\n\tlink1 := builder.AppendOn(ctx, genTS, 2)\n\tlink2 := builder.AppendOn(ctx, link1, 3)\n\tlink3 := builder.AppendOn(ctx, link2, 1)\n\tlink4 := builder.BuildOn(ctx, link3, 2, func(bb *chain.BlockBuilder, i int) { bb.IncHeight(2) })\n\n\t// Head starts as an empty cid set\n\tassert.Equal(t, types.UndefTipSet, cs.GetHead())\n\n\t// Set Head\n\tassertSetHead(t, cboreStore, genTS)\n\tassert.ObjectsAreEqualValues(genTS.Key(), cs.GetHead())\n\n\t// Move head forward\n\tassertSetHead(t, cboreStore, link4)\n\tassert.ObjectsAreEqualValues(link4.Key(), cs.GetHead())\n\n\t// Move head back\n\tassertSetHead(t, cboreStore, link1)\n\tassert.ObjectsAreEqualValues(link1.Key(), cs.GetHead())\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func NewClassifier(graphPath, labelPath string) (*Classifier, error) {\n\treturn NewClassifierWithConfig(graphPath, labelPath, DefaultConfig)\n}", "func NewTitle(text string) *Title {\n\treturn &Title{text: text, uliner: TitleUnderliner}\n}", "func BBMake(l, t, r, b Float) (BB) { \n return BB{L: l, B: b, R: r, T: t}\n}", "func NewWorkbookChartTitle()(*WorkbookChartTitle) {\n m := &WorkbookChartTitle{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewWorkbookChartTitle()(*WorkbookChartTitle) {\n m := &WorkbookChartTitle{\n Entity: *NewEntity(),\n }\n return m\n}", "func New() *Nitro {\n\treturn NewWithConfig(DefaultConfig())\n}", "func NewEncodedHeadline(val string) EncodedHeadlineField {\n\treturn EncodedHeadlineField{quickfix.FIXString(val)}\n}", "func (b *Impl) Create(compare func(interface{}, interface{}) int) RedBlackTree {\n\tresult := Impl{head: nil, compare: compare}\n\n\treturn &result\n}", "func (this *HeaderRepository) CreateOne(request *mrequest.HeaderCreate) (*mongo.InsertOneResult, error) {\n\n\treturn this.Headers.InsertOne(context.Background(), request)\n}", "func newRC(rsName string, replicas int32, rcPodLabels map[string]string, spec v1.PodSpec) *v1.ReplicationController {\n\treturn &v1.ReplicationController{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rsName,\n\t\t},\n\t\tSpec: v1.ReplicationControllerSpec{\n\t\t\tReplicas: func(i int32) *int32 { return &i }(replicas),\n\t\t\tTemplate: &v1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: rcPodLabels,\n\t\t\t\t},\n\t\t\t\tSpec: spec,\n\t\t\t},\n\t\t},\n\t}\n}", "func NewLabelDef(name string, nodeSolver config.RextNodeSolver) *LabelDef {\n\treturn &LabelDef{\n\t\tname: name,\n\t\tnodeSolver: nodeSolver,\n\t}\n}", "func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tlmHead := NewRobertaLMHead(p.Sub(\"lm_head\"), config)\n\n\treturn &RobertaForMaskedLM{\n\t\troberta: roberta,\n\t\tlmHead: lmHead,\n\t}\n}", "func NewHclFirmware(classId string, objectType string) *HclFirmware {\n\tthis := HclFirmware{}\n\tthis.ClassId = classId\n\tthis.ObjectType = objectType\n\treturn &this\n}", "func newMaxentClassifier(\n\tweights []float64,\n\tmapping map[string]int,\n\tlabels []string) *binaryMaxentClassifier {\n\n\tset := mapset.NewSet()\n\tfor label := range mapping {\n\t\tset.Add(strings.Split(label, \"-\")[0])\n\t}\n\n\treturn &binaryMaxentClassifier{\n\t\tset.Cardinality() + 1,\n\t\tlabels,\n\t\tmapping,\n\t\tweights}\n}", "func (n Noun) Head() Noun { return n.cell[0] }", "func NewHeader() *Headers {\n\treturn &Headers{\n\t\tentities: map[string]string{},\n\t}\n}", "func (c Companion) CreateCompanion(name string, hunger, tiredness, happiness, intellectualPotential float32, userID uint) Companion {\n\tdb := db.GetDb()\n\n\tcompanion := Companion{\n\t\tName: name,\n\t\tHunger: hunger,\n\t\tTiredness: tiredness,\n\t\tHappiness: happiness,\n\t\tIntellectPotential: intellectualPotential,\n\t\tUserID: userID,\n\t}\n\tdb.Create(&companion)\n\n\treturn companion\n}", "func (c *Client) CreateClass(request *CreateClassRequest) (response *CreateClassResponse, err error) {\n if request == nil {\n request = NewCreateClassRequest()\n }\n response = NewCreateClassResponse()\n err = c.Send(request, response)\n return\n}", "func (r RGASS) Head() *Node {\n\treturn r.Model.Head()\n}", "func NewRBNode(value int) *RBNode {\n\treturn &RBNode{color: Red, value: value}\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers) NewClassifier(Type E_OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Config_Type) (*OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Classifier == nil {\n\t\tt.Classifier = make(map[E_OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Config_Type]*OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier)\n\t}\n\n\tkey := Type\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Classifier[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Classifier\", key)\n\t}\n\n\tt.Classifier[key] = &OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier{\n\t\tType: Type,\n\t}\n\n\treturn t.Classifier[key], nil\n}", "func New(hash hash.Hash, data [][]byte) *MerkleTree {\n\tvar n int\n\n\tif data == nil || len(data) == 0 {\n\t\treturn nil\n\t}\n\tif n = len(data); n == 0 {\n\t\treturn nil\n\t}\n\tr := &MerkleTree{\n\t\thash: hash,\n\t}\n\tr.tree = r.mkMerkleTreeRoot(n, data)\n\treturn r\n}", "func New(hashFunc func(i interface{}) int64) *rbTree {\n\treturn &rbTree{hashFunc: hashFunc}\n}", "func New(quality func(c *Chromosome) (float64, error)) Genetic {\n\treturn &facebook{\n\t\tdistribution: generateRandom,\n\t\tquality: quality,\n\t\tfitness: standardFitness,\n\t\tselection: standardSelection,\n\t}\n}", "func New() *RBTree {\n\treturn &RBTree{\n\t\tlock: sync.RWMutex{},\n\t\tNode: nil,\n\t\tstack: newStack(nil),\n\t}\n}", "func (v HashtagsResource) New(c buffalo.Context) error {\n\t// Make hashtag available inside the html template\n\tc.Set(\"hashtag\", &models.Hashtag{})\n\treturn c.Render(200, r.HTML(\"hashtags/new.html\"))\n}", "func (fbo *folderBranchOps) setNewInitialHeadLocked(ctx context.Context,\n\tlState *kbfssync.LockState, md ImmutableRootMetadata) error {\n\tfbo.mdWriterLock.AssertLocked(lState)\n\tfbo.headLock.AssertLocked(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\treturn errors.New(\"Unexpected non-nil head in setNewInitialHeadLocked\")\n\t}\n\tif md.Revision() != kbfsmd.RevisionInitial {\n\t\treturn errors.Errorf(\"setNewInitialHeadLocked unexpectedly called with revision %d\", md.Revision())\n\t}\n\treturn fbo.setHeadLocked(ctx, lState, md, headTrusted, mdToCommitType(md))\n}", "func (p *FakeProvider) SetHead(head block.TipSetKey) {\n\t_, e := p.GetTipSet(head)\n\trequire.NoError(p.t, e)\n\tp.head = head\n}", "func NewHeader() *Header {\n\tvar result Header\n\tresult.File.ID = 0x46464952\n\tresult.File.Format = 0x45564157\n\tresult.Format.ID = 0x20746d66\n\tresult.Format.Size = 0x10\n\tresult.Format.AudioFormat = 1\n\tresult.Data.ID = 0x61746164\n\treturn &result\n}", "func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {\n if len(config.HeaderName) == 0 {\n return nil, fmt.Errorf(\"HeaderName cannot be empty\")\n }\n\n return &CNCFDemo{\n headerName: config.HeaderName,\n next: next,\n name: name,\n }, nil\n}", "func newStatus(source *goharborv1.HarborCluster) *status {\n\t// New with default status and conditions\n\ts := &status{\n\t\tcr: source,\n\t\tlocker: &sync.Mutex{},\n\t\tdata: &goharborv1.HarborClusterStatus{\n\t\t\tStatus: goharborv1.StatusProvisioning,\n\t\t\tRevision: time.Now().UnixNano(),\n\t\t\tConditions: make([]goharborv1.HarborClusterCondition, 0),\n\t\t},\n\t\tcollection: lcm.NewCRStatusCollection(),\n\t}\n\n\tif source != nil {\n\t\ts.data.Operator = source.Status.Operator\n\t}\n\n\t// Copy source status if it has been set before\n\tif source != nil && len(source.Status.Status) > 0 {\n\t\ts.data.Status = source.Status.Status\n\t\ts.data.Revision = source.Status.Revision\n\t\ts.data.Conditions = append(s.data.Conditions, source.Status.Conditions...)\n\t\ts.sourceRevision = source.Status.Revision // for comparison later\n\t}\n\n\treturn s\n}", "func (app *App) createClass(w http.ResponseWriter, r *http.Request) {\n\tclassPayload := decodeClass(r)\n\tmongoResult := app.getById(\"classes\", []byte(classPayload.ClassId))\n\tif mongoResult.Err() != nil {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tresult := app.insertOne(\"classes\", classPayload)\n\t\tjson.NewEncoder(w).Encode(&result)\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencodeError(w, \"A Class With That ID Already Exists.\")\n\t}\n}", "func New(p []Comparable, effort int, src rand.Source) (t *Tree, err error) {\n\tvar intn func(int) int\n\tvar shuf func(n int, swap func(i, j int))\n\tif src == nil {\n\t\tintn = rand.Intn\n\t\tshuf = rand.Shuffle\n\t} else {\n\t\trnd := rand.New(src)\n\t\tintn = rnd.Intn\n\t\tshuf = rnd.Shuffle\n\t}\n\tb := builder{work: make([]float64, len(p)), intn: intn, shuf: shuf}\n\n\tdefer func() {\n\t\tswitch r := recover(); r {\n\t\tcase nil:\n\t\tcase pointAtInfinity:\n\t\t\tt = nil\n\t\t\terr = pointAtInfinity\n\t\tdefault:\n\t\t\tpanic(r)\n\t\t}\n\t}()\n\n\tt = &Tree{\n\t\tRoot: b.build(p, effort),\n\t\tCount: len(p),\n\t}\n\treturn t, nil\n}", "func NewCreateNewtrader(ctx *middleware.Context, handler CreateNewtraderHandler) *CreateNewtrader {\n\treturn &CreateNewtrader{Context: ctx, Handler: handler}\n}", "func NewCorporation() Corporation {\n\tc := Corporation{\n\t\tName: corpTable.name.Roll(),\n\t\tOrganization: corpTable.organization.Roll(),\n\t\tBusiness: corpTable.business.Roll(),\n\t\tReputationAndRumor: corpTable.reputation.Roll(),\n\t}\n\treturn c\n}", "func SetHead(ref string) error {\n\terr := ioutil.WriteFile(UGIT_DIR+\"/\"+HEAD_PATH, []byte(ref), 0777)\n\treturn err\n}", "func New(conf *Config) Rclone {\n\treturn Rclone{config: conf}\n}", "func (a *Agent) LabelCreate(name string, color LabelColor) (labelId string, err error) {\n\tcolorName, ok := labelColorMap[color]\n\tif !ok {\n\t\tcolorName = api.LabelColorBlank\n\t}\n\tspec := (&api.LabelCreateSpec{}).Init(\n\t\tname, colorName,\n\t)\n\tif err = a.pc.ExecuteApi(spec); err != nil {\n\t\treturn\n\t}\n\tif len(spec.Result) > 0 {\n\t\tlabelId = spec.Result[0].Id\n\t}\n\treturn\n}", "func NewH1(text string) Element {\n\treturn NewHeader(1, text)\n}" ]
[ "0.6364758", "0.5719456", "0.54601485", "0.51877445", "0.51676345", "0.5114384", "0.5104612", "0.5007022", "0.49942425", "0.49633253", "0.485414", "0.48249248", "0.4803933", "0.48032835", "0.4742509", "0.47365102", "0.47250208", "0.47056574", "0.46969962", "0.46928912", "0.46807542", "0.4643524", "0.46264112", "0.4618064", "0.46027476", "0.45960248", "0.45945612", "0.45888117", "0.45718044", "0.45699066", "0.45580682", "0.455337", "0.4531153", "0.45261255", "0.45255592", "0.45164612", "0.44788423", "0.44722638", "0.44564274", "0.44557106", "0.4451095", "0.4418208", "0.4414081", "0.4389497", "0.4377995", "0.43339306", "0.43253705", "0.4315533", "0.4313502", "0.43078855", "0.4292345", "0.4276503", "0.4264557", "0.4257469", "0.42466953", "0.42419925", "0.42339677", "0.4229098", "0.4227808", "0.4226048", "0.4223828", "0.42156395", "0.4204597", "0.42043546", "0.4193169", "0.4193169", "0.4191697", "0.41895485", "0.4181932", "0.41815436", "0.41794512", "0.41647303", "0.41580868", "0.41560677", "0.41441157", "0.41377842", "0.41355878", "0.4134606", "0.41333854", "0.4127343", "0.4123492", "0.41175467", "0.4116937", "0.411609", "0.41113412", "0.4111158", "0.41033334", "0.41004398", "0.40958908", "0.40938094", "0.40909377", "0.4084896", "0.40826842", "0.40821102", "0.40660167", "0.4065574", "0.40599638", "0.40590867", "0.40530932", "0.40522948" ]
0.8124905
0
ForwardT forwards pass through model.
func (ch *RobertaClassificationHead) ForwardT(hiddenStates *ts.Tensor, train bool) *ts.Tensor { appliedDO1 := hiddenStates.MustSelect(1, 0, false).ApplyT(ch.dropout, train) appliedDense := appliedDO1.Apply(ch.dense) tanhTs := appliedDense.MustTanh(false) appliedDO2 := tanhTs.ApplyT(ch.dropout, train) retVal := appliedDO2.Apply(ch.outProj) appliedDO1.MustDrop() appliedDense.MustDrop() tanhTs.MustDrop() appliedDO2.MustDrop() return retVal }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mod *backendModule) Forward(f *gatepb.Forward) error {\n\treturn mod.send(proto.Type(f.Typ), f)\n}", "func (m *Model) Forward(qkv attention.QKV) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: m.Key.Forward(qkv.Keys...),\n\t\tValues: m.Value.Forward(qkv.Values...),\n\t}\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (m *Model) Forward(x *Node, states States) (rv *Node, err error) {\n\trv = x\n\tfor _, l := range m.Layers {\n\t\tif rv, err = l.Forward(rv, states); err != nil {\n\t\t\treturn nil, errors.Wrap(err, l.Name())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\th := nn.Affine(g, m.B, m.W, x)\n\tif yPrev != nil {\n\t\th = g.Add(h, g.Prod(m.WRec, yPrev))\n\t}\n\ts.Y = g.Invoke(m.Activation, h)\n\treturn\n}", "func (obj *Doc) Forward(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"Forward\", nil)\n\treturn err\n}", "func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Ensure our request client does not follow redirects\n\thttpClient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tif config.TLS != nil {\n\t\ttlsConfig, err := config.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\ttracing.SetErrorAndDebugLog(r, \"Unable to configure TLS to call %s. Cause %s\", config.Address, err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(http.MethodGet, config.Address, http.NoBody)\n\ttracing.LogRequest(tracing.GetSpan(r), forwardReq)\n\tif err != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause %s\", config.Address, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteHeader(r, forwardReq, config.TrustForwardHeader)\n\n\ttracing.InjectRequestHeaders(forwardReq)\n\n\tforwardResponse, forwardErr := httpClient.Do(forwardReq)\n\tif forwardErr != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause: %s\", config.Address, forwardErr)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbody, readError := ioutil.ReadAll(forwardResponse.Body)\n\tif readError != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error reading body %s. Cause: %s\", config.Address, readError)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer forwardResponse.Body.Close()\n\n\t// Pass the forward response's body and selected headers if it\n\t// didn't return a response within the range of [200, 300).\n\tif forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {\n\t\tlog.Debugf(\"Remote error %s. StatusCode: %d\", config.Address, forwardResponse.StatusCode)\n\n\t\tutils.CopyHeaders(w.Header(), forwardResponse.Header)\n\t\tutils.RemoveHeaders(w.Header(), forward.HopHeaders...)\n\n\t\t// Grab the location header, if any.\n\t\tredirectURL, err := forwardResponse.Location()\n\n\t\tif err != nil {\n\t\t\tif err != http.ErrNoLocation {\n\t\t\t\ttracing.SetErrorAndDebugLog(r, \"Error reading response location header %s. Cause: %s\", config.Address, err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if redirectURL.String() != \"\" {\n\t\t\t// Set the location in our response if one was sent back.\n\t\t\tw.Header().Set(\"Location\", redirectURL.String())\n\t\t}\n\n\t\ttracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)\n\t\tw.WriteHeader(forwardResponse.StatusCode)\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tfor _, headerName := range config.AuthResponseHeaders {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tr.Header.Del(headerKey)\n\t\tif len(forwardResponse.Header[headerKey]) > 0 {\n\t\t\tr.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)\n\t\t}\n\t}\n\n\tr.RequestURI = r.URL.RequestURI()\n\tnext(w, r)\n}", "func (t *Type) ForwardType() *ForwardType", "func (f *Forwarder) Forward(data *call.CallData) {\n\tf.transferAgents.Range(func(key interface{}, value interface{}) bool {\n\t\tstreamId := key.(userid.ID)\n\t\tstream := value.(TransferAgent)\n\t\tif streamId == userid.ID(data.UserId) { // Don't need to forward data back to sender\n\t\t\treturn true\n\t\t}\n\n\t\tif err := stream.Send(data); err != nil {\n\t\t\tf.logger.Error(err)\n\t\t}\n\n\t\treturn true\n\t})\n}", "func (q *CQPU) forward(predicate []*pbUtils.AttributePredicate, streamRec *pbQPU.ResponseStreamRecord, streamOut pbQPU.QPU_QueryServer, seqID *int64, respond bool) error {\n\tif respond {\n\t\terr := streamOut.Send(\n\t\t\tprotoutils.ResponseStreamRecord(\n\t\t\t\t*seqID,\n\t\t\t\tstreamRec.GetType(),\n\t\t\t\tstreamRec.GetLogOp(),\n\t\t\t))\n\t\t(*seqID)++\n\t\treturn err\n\t}\n\treturn nil\n}", "func (rt *Router) forward() {\n\tfor i, v := range rt.InInterfaceL {\n\t\t//pktS := \"\"\n\n\t\t// TRYE\n\t\t// get packet from interface i\n\t\tif pktS, err := v.Get(); err == nil {\n\t\t\t//fmt.Println(\"in routher forward, packet from Get(): \", pktS)\n\t\t\t// if packet exists make a forwarding decision\n\t\t\tp, err := FromByteS(pktS)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not get packet\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// HERE you will need to implement a lookup into the\n\t\t\t// forwarding table to find the appropriate outgoing interface\n\t\t\t// for now we assume the outgoing interface is also i\n\t\t\tfmt.Printf(\"%s: forwarding packet %s from interface %d to %d with mtu %d\\n\", rt.Str(), p.Str(), i, i, rt.OutInterfaceL[i].Mtu)\n\n\t\t\tif err = rt.OutInterfaceL[i].Put(p.ToByteS(), false); err != nil {\n\t\t\t\t//log.Printf(\"Could not put packet %s in router %s, into outInterface %d. Error: %s\", p.str, rt.forward, i, err)\n\t\t\t\tlog.Printf(\"%s: packet '%s' lost on interface %d\\n\", rt.Str(), i)\n\t\t\t}\n\t\t}\n\t\t//log.Println(\"no packet to forard in router\")\n\t}\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func (a *provisionApp) forward(app *App, args ...interface{}) error {\n\tvar units uint\n\tif len(args) > 0 {\n\t\tswitch args[0].(type) {\n\t\tcase int:\n\t\t\tunits = uint(args[0].(int))\n\t\tcase int64:\n\t\t\tunits = uint(args[0].(int64))\n\t\tcase uint:\n\t\t\tunits = args[0].(uint)\n\t\tcase uint64:\n\t\t\tunits = uint(args[0].(uint64))\n\t\tdefault:\n\t\t\tunits = 1\n\t\t}\n\t}\n\terr := Provisioner.Provision(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif units > 1 {\n\t\t_, err = Provisioner.AddUnits(app, units-1)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ph *Handler) Forward() {\n\terr := recover()\n\tph.forward(err)\n}", "func (inst *instance) Forward(port int) (string, error) {\n\tvar reply proxyrpc.ForwardResult\n\terr := inst.ProxyApp.Call(\n\t\t\"ProxyVM.Forward\",\n\t\tproxyrpc.ForwardParams{\n\t\t\tID: inst.ID,\n\t\t\tPort: port,\n\t\t},\n\t\t&reply)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reply.ManagerAddress, nil\n}", "func (t *Transaction) forwardTransaction() {\n\tif t.tx == nil {\n\t\tpanic(\"tx is nil while forward was being called\")\n\t}\n\tselect {\n\tcase t.sendTxFound <- t.tx:\n\tcase <-t.shutdown:\n\t\treturn\n\t}\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\ts.InG = g.Sigmoid(nn.Affine(g, m.BIn, m.WIn, x, m.WInRec, yPrev))\n\ts.ForG = g.Sigmoid(nn.Affine(g, m.BFor, m.WFor, x, m.WForRec, yPrev))\n\ts.Cand = g.Tanh(g.Mul(m.WCand, x))\n\ts.Y = g.Prod(s.InG, s.Cand)\n\tif yPrev != nil {\n\t\ts.Y = g.Add(s.Y, g.Prod(g.Tanh(yPrev), s.ForG))\n\t}\n\treturn\n}", "func (req *RequestData) Forward(client *http.Client, config BasketConfig, basket string) (*http.Response, error) {\n\tforwardURL, err := url.ParseRequestURI(config.ForwardURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid forward URL: %s - %s\", config.ForwardURL, err)\n\t}\n\n\t// expand path\n\tif config.ExpandPath && len(req.Path) > len(basket)+1 {\n\t\tforwardURL.Path = expandURL(forwardURL.Path, req.Path, basket)\n\t}\n\n\t// append query\n\tif len(req.Query) > 0 {\n\t\tif len(forwardURL.RawQuery) > 0 {\n\t\t\tforwardURL.RawQuery += \"&\" + req.Query\n\t\t} else {\n\t\t\tforwardURL.RawQuery = req.Query\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(req.Method, forwardURL.String(), strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create forward request: %s\", err)\n\t}\n\n\t// copy headers\n\tfor header, vals := range req.Header {\n\t\tfor _, val := range vals {\n\t\t\tforwardReq.Header.Add(header, val)\n\t\t}\n\t}\n\t// headers cleanup\n\tforwardHeadersCleanup(forwardReq)\n\t// set do not forward header\n\tforwardReq.Header.Set(DoNotForwardHeader, \"1\")\n\n\t// forward request\n\tresponse, err := client.Do(forwardReq)\n\tif err != nil {\n\t\t// HTTP issue during forwarding - HTTP 502 Bad Gateway\n\t\tlog.Printf(\"[warn] failed to forward request for basket: %s - %s\", basket, err)\n\t\tbadGatewayResp := &http.Response{\n\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(\"Failed to forward request: %s\", err)))}\n\t\tbadGatewayResp.Header.Set(\"Content-Type\", \"text/plain\")\n\n\t\treturn badGatewayResp, nil\n\t}\n\n\treturn response, nil\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (tr *Peer) FastForward(ctx context.Context, target string,\n\treq *FastForwardRequest, resp *FastForwardResponse) error {\n\n\tif tr.isShutdown() {\n\t\treturn ErrTransportStopped\n\t}\n\n\ttr.wg.Add(1)\n\tdefer tr.wg.Done()\n\n\treturn tr.fastForward(ctx, target, req, resp)\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tg := m.Graph()\n\thalfSize := xs[0].Value().Size() / 2\n\n\tres := make([]ag.Node, len(xs))\n\tgate := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tres[i] = g.View(x, 0, 0, halfSize, 1)\n\t\tgate[i] = g.View(x, halfSize, 0, halfSize, 1)\n\t}\n\n\tgate = m.Norm.Forward(gate...)\n\tgate = m.Proj.Forward(gate...)\n\n\tif m.Act != nil {\n\t\tgate = m.Act.Forward(gate...)\n\t}\n\n\ty := make([]ag.Node, len(gate))\n\tfor i := range y {\n\t\ty[i] = g.Prod(gate[i], res[i])\n\t}\n\treturn y\n}", "func (o *OutboundDispatcher) Forward(msg interface{}, des *service.Destination) error {\n\tfor _, v := range o.outboundTransports {\n\t\tif !v.AcceptRecipient(des.RecipientKeys) {\n\t\t\tif !v.Accept(des.ServiceEndpoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treq, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed marshal to bytes: %w\", err)\n\t\t}\n\n\t\t_, err = v.Send(req, des)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send msg using outbound transport: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no outbound transport found for serviceEndpoint: %s\", des.ServiceEndpoint)\n}", "func (m *Model) Forward(cache Cache, q, x []mat.Tensor) ([]mat.Tensor, []mat.Tensor, Cache) {\n\tvar pk, pv mat.Tensor\n\n\tpq := m.Query.Forward(q...)\n\n\tif hasCache := cache.HasValues(); hasCache && m.IsCrossAttention {\n\t\tpk = cache[0]\n\t\tpv = cache[1]\n\t} else {\n\t\tk := m.Key.Forward(x...)\n\t\tv := m.Value.Forward(x...)\n\n\t\tif hasCache {\n\t\t\tpk = ag.AppendRows(cache[0], k...)\n\t\t\tpv = ag.AppendRows(cache[1], v...)\n\t\t} else {\n\t\t\tpk = ag.Stack(k...)\n\t\t\tpv = ag.Stack(v...)\n\t\t}\n\t}\n\n\tresult, weights := attention.ScaledDotProductAttention(pq, pk, pv, m.ScaleFactor, m.UseCausalMask)\n\n\treturn result, weights, Cache{pk, pv}\n}", "func (a *insertApp) forward(app *App, args ...interface{}) error {\n\tapp.State = \"pending\"\n\treturn db.Session.Apps().Insert(app)\n}", "func (tc *RobertaForTokenClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := tc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := hiddenState.ApplyT(tc.dropout, train)\n\toutput = appliedDO.Apply(tc.classifier)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (b *TestDriver) Forward(val int) error {\n\tlog.Printf(\"Forward: %d\", val)\n\n\treturn nil\n}", "func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train)\n\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tpredictionScores := mlm.lmHead.Forward(hiddenState)\n\n\treturn predictionScores, allHiddenStates, allAttentions, nil\n}", "func (r *Lachesis) FastForward(\n\treq *net.FastForwardRequest, resp *net.FastForwardResponse) error {\n\tresult, err := r.process(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, ok := result.(*net.FastForwardResponse)\n\tif !ok {\n\t\treturn ErrBadResult\n\t}\n\t*resp = *item\n\treturn nil\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func (c *ManetConnection) forward(bytes []byte) {\n\tincomingHeader := data.PacketHeaderFromBytes(bytes)\n\n\tcached := c.inCache(incomingHeader.SequenceNumber, incomingHeader.SendKey)\n\tfmt.Println(\"CACHE: \", incomingHeader.SequenceNumber, incomingHeader.SendKey, cached)\n\n\tif cached || incomingHeader.TTL <= 1 {\n\t\tfmt.Println(\"DROP!\")\n\t\treturn\n\t}\n\n\tc.cache[incomingHeader.SequenceNumber] = incomingHeader.SendKey\n\tdelete(c.cache, incomingHeader.SequenceNumber-cacheDepth)\n\n\toutgoingHeader := &data.PacketHeader{\n\t\tSourceAddress: incomingHeader.SourceAddress,\n\t\tDestinationAddress: incomingHeader.DestinationAddress,\n\t\tPreviousHop: GetMyAddress(),\n\t\tTTL: incomingHeader.TTL - 1,\n\t\tPacketType: incomingHeader.PacketType,\n\t\tSequenceNumber: incomingHeader.SequenceNumber,\n\t\tNumBytes: incomingHeader.NumBytes,\n\t\tSendKey: incomingHeader.SendKey,\n\t}\n\n\tfor i, b := range outgoingHeader.ToBytes() {\n\t\tbytes[i] = b\n\t}\n\n\tfor neighbor := range myNeighbors {\n\t\tif neighbor == incomingHeader.PreviousHop {\n\t\t\tcontinue\n\t\t}\n\t\traddr := ToUDPAddr(neighbor)\n\t\tfmt.Println(\"FORWARD to\", neighbor, \"DEST: \", incomingHeader.DestinationAddress, \"aka\", raddr)\n\t\tif _, err := c.conn.WriteToUDP(bytes, raddr); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tlabels = sc.classifier.ForwardT(hiddenState, train)\n\thiddenState.MustDrop()\n\n\treturn labels, hiddenStates, attentions, nil\n}", "func (b *BaseController) Forward(title, templateName string) {\n\tb.Layout = filepath.Join(prefixNg, \"layout.htm\")\n\tb.TplName = filepath.Join(prefixNg, templateName)\n\tb.Data[\"Title\"] = b.Tr(title)\n\tb.LayoutSections = make(map[string]string)\n\tb.LayoutSections[\"HeaderInclude\"] = filepath.Join(prefixNg, viewPath, \"header-include.htm\")\n\n\tif b.UseCompressedJS {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-min-include.htm\")\n\t} else {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-include.htm\")\n\t}\n\n\tlog.Debugf(\"Loaded HeaderScriptInclude file: %s\", b.LayoutSections[\"HeaderScriptInclude\"])\n\n\tb.LayoutSections[\"FooterInclude\"] = filepath.Join(prefixNg, viewPath, \"footer-include.htm\")\n\tb.LayoutSections[\"HeaderContent\"] = filepath.Join(prefixNg, viewPath, \"header-content.htm\")\n\tb.LayoutSections[\"FooterContent\"] = filepath.Join(prefixNg, viewPath, \"footer-content.htm\")\n\n}", "func (rh *RobertaLMHead) Forward(hiddenStates *ts.Tensor) *ts.Tensor {\n\tgelu := util.NewGelu()\n\tappliedDense := hiddenStates.Apply(rh.dense)\n\tgeluFwd := gelu.Fwd(appliedDense)\n\tappliedLN := geluFwd.Apply(rh.layerNorm)\n\tappliedDecoder := appliedLN.Apply(rh.decoder)\n\tappliedBias := appliedDecoder.MustAdd(rh.bias, true)\n\n\tgeluFwd.MustDrop()\n\tappliedDense.MustDrop()\n\tappliedLN.MustDrop()\n\n\treturn appliedBias\n}", "func (l *AffineLayer) Forward(x mat.Matrix) mat.Matrix {\n\t_, c := x.Dims()\n\tif c != l.dimIn {\n\t\tpanic(fmt.Sprintf(\"expect %d but got %d\", l.dimIn, c))\n\t}\n\tl.x = x\n\tvar ret mat.Dense\n\tret.Mul(x, l.Weight)\n\tret.Apply(func(i, j int, val float64) float64 {\n\t\treturn l.Bias.At(j, 0) + val\n\t}, &ret)\n\treturn &ret\n}", "func (n *Network) Forward() {\n\tif !n.constructed() {\n\t\tlog.Panic(\"Cannot run an emtpy Network\")\n\t}\n\n\tfor l := range n.layers {\n\t\tcandy.Must(parallel.For(0, len(n.layers[l]), 1, func(g int) {\n\t\t\tgate := n.layers[l][g]\n\t\t\tgate.forward(gate)\n\t\t}))\n\t}\n}", "func (s *Service) Forward(topicID, msgID, targetAddr, text string) error {\n\tpayload := map[string]interface{}{\n\t\t\"id\": msgID,\n\t\t\"address\": targetAddr,\n\t\t\"text\": text,\n\t}\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpf, err := s.client.Publish(topicID, b, 2, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pf.Wait(5 * time.Second)\n}", "func (s *Server) Forward(id int64, event api.Event) {\n\tif event.Type == \"logging\" {\n\t\t// Parse the message\n\t\tlogEntry := api.EventLogging{}\n\t\terr := json.Unmarshal(event.Metadata, &logEntry)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && logEntry.Level == \"dbug\" {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && !s.verbose && logEntry.Level == \"info\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := s.broadcast(event, true)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to forward event from member %d: %v\", id, err)\n\t}\n}", "func (m *Linear) Forward(x mat.Tensor) mat.Tensor {\n\treturn ag.Add(ag.Mul(m.W, x), m.B)\n}", "func (f *Forward) Forward(state request.Request) (*dns.Msg, error) {\n\tif f == nil {\n\t\treturn nil, ErrNoForward\n\t}\n\n\tfails := 0\n\tvar upstreamErr error\n\tfor _, proxy := range f.List() {\n\t\tif proxy.Down(f.maxfails) {\n\t\t\tfails++\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// All upstream proxies are dead, assume healtcheck is complete broken and randomly\n\t\t\t// select an upstream to connect to.\n\t\t\tproxy = f.List()[0]\n\t\t}\n\n\t\tret, err := proxy.Connect(context.Background(), state, f.opts)\n\n\t\tret, err = truncated(state, ret, err)\n\t\tupstreamErr = err\n\n\t\tif err != nil {\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if the reply is correct; if not return FormErr.\n\t\tif !state.Match(ret) {\n\t\t\treturn state.ErrorMessage(dns.RcodeFormatError), nil\n\t\t}\n\n\t\treturn ret, err\n\t}\n\n\tif upstreamErr != nil {\n\t\treturn nil, upstreamErr\n\t}\n\n\treturn nil, ErrNoHealthy\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func processForward(forward *chproto.ChangeForward) {\n\n\t// If we are already trying to forward a change forward message with\n\t// the same requesting node and request ID, discard this message.\n\tif _, exists := getForwardTimeout(uint16(*forward.Request.RequestNode),\n\t\t*forward.Request.RequestId); exists {\n\t\treturn\n\t}\n\n\t// Everything else in this function runs in a transaction.\n\t// We are read-only.\n\tstore.StartTransaction()\n\tdefer store.EndTransaction()\n\n\t// If this is a core node and this node stopped being leader less than\n\t// a Change Timeout Period ago, always add us to the ignore list.\n\tif config.IsCore() && !isIgnored(forward, config.Id()) {\n\t\tdiff := time.Now().Sub(store.StoppedLeading())\n\t\tif diff < config.CHANGE_TIMEOUT_PERIOD {\n\t\t\tforward.Ignores = append(forward.Ignores,\n\t\t\t\tuint32(config.Id()))\n\t\t}\n\t}\n\n\t// If all core node IDs are in the forward's ignore list, discard it.\n\tif len(forward.Ignores) == len(config.CoreNodes()) {\n\t\tlog.Print(\"shared/chrequest: dropped msg due to full ignores\")\n\t\treturn\n\t}\n\n\t// Otherwise, choose a potential leader node.\n\t// This is O(n^2) in the number of core nodes,\n\t// but we don't expect to have many.\n\tchosenNode := uint16(0)\n\t_, leader := store.Proposal()\n\tif leader != 0 && !isIgnored(forward, leader) {\n\t\tchosenNode = leader\n\t} else {\n\t\tfor _, node := range config.CoreNodes() {\n\t\t\tif !isIgnored(forward, node) {\n\t\t\t\tchosenNode = node\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif chosenNode == 0 {\n\t\t// Shouldn't happen.\n\t\tlog.Print(\"shared/chrequest: bug, \" +\n\t\t\t\"couldn't find candidate leader node\")\n\t\treturn\n\t}\n\n\t// If we are the selected leader, construct an external change request,\n\t// and send it on our change request channel.\n\tif chosenNode == config.Id() {\n\t\tintRequest := forward.Request\n\t\tchrequest := new(store.ChangeRequest)\n\t\tchrequest.RequestEntity = *intRequest.RequestEntity\n\t\tchrequest.RequestNode = uint16(*intRequest.RequestNode)\n\t\tchrequest.RequestId = *intRequest.RequestId\n\t\tchrequest.Changeset = make([]store.Change,\n\t\t\tlen(intRequest.Changeset))\n\n\t\tfor i, ch := range intRequest.Changeset {\n\t\t\tchrequest.Changeset[i].TargetEntity = *ch.TargetEntity\n\t\t\tchrequest.Changeset[i].Key = *ch.Key\n\t\t\tchrequest.Changeset[i].Value = *ch.Value\n\t\t}\n\n\t\tfor _, cb := range changeCallbacks {\n\t\t\tcb(chrequest)\n\t\t}\n\n\t\treturn\n\t}\n\n\t// Otherwise, we send it on to the selected leader,\n\t// add the selected leader to the ignore list,\n\t// and set a timeout to retry.\n\tsendForward(chosenNode, forward)\n\tforward.Ignores = append(forward.Ignores, uint32(chosenNode))\n\taddForwardTimeout(forward)\n}", "func (lay *Layer) Forward(x *mat.Dense) (a *mat.Dense) {\n\t// x is (n x in )\n\trow, _ := x.Dims()\n\n\txx := new(mat.Dense)\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\tz.Apply(func(i, j int, v float64) float64 { return lay.act.f(v) }, z)\n\treturn z\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func httpForward(store *ForwardStore) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tkey := mux.Vars(r)[\"uid\"]\n\t\tif key == \"\" {\n\t\t\tkey = \"0\"\n\t\t}\n\t\tforward, _ := store.get(key)\n\t\thttp.Redirect(w, r, forward.URL, 302)\n\t}\n}", "func (r *RotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := Rotate(fx, r.angle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (a *createBucketIam) forward(app *App, args ...interface{}) error {\n\tenv, err := createBucket(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _ := config.GetString(\"host\")\n\tenvVars := []bind.EnvVar{\n\t\t{Name: \"APPNAME\", Value: app.Name},\n\t\t{Name: \"TSURU_HOST\", Value: host},\n\t}\n\tvariables := map[string]string{\n\t\t\"ENDPOINT\": env.endpoint,\n\t\t\"LOCATIONCONSTRAINT\": strconv.FormatBool(env.locationConstraint),\n\t\t\"ACCESS_KEY_ID\": env.AccessKey,\n\t\t\"SECRET_KEY\": env.SecretKey,\n\t\t\"BUCKET\": env.bucket,\n\t}\n\tfor name, value := range variables {\n\t\tenvVars = append(envVars, bind.EnvVar{\n\t\t\tName: fmt.Sprintf(\"TSURU_S3_%s\", name),\n\t\t\tValue: value,\n\t\t\tInstanceName: s3InstanceName,\n\t\t})\n\t}\n\tapp.SetEnvsToApp(envVars, false, true)\n\treturn nil\n}", "func (r *Redirect) Forward(conn net.Conn) {\n\tif conn == nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\trequest = []byte{}\n\t\trequestTmp = make([]byte, 1024)\n\t)\n\n\tfor {\n\t\tn, err := conn.Read(requestTmp)\n\t\tif err != nil {\n\t\t\tr.reply(conn, nil, \"\", err)\n\t\t\treturn\n\t\t}\n\t\trequest = append(request, requestTmp[:n]...)\n\t\tif n < 1024 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(request)))\n\n\tif err != nil {\n\t\tr.reply(conn, nil, \"\", err)\n\t\treturn\n\t}\n\n\tu, err := url.Parse(string(req.RequestURI[1:]))\n\tif err != nil {\n\t\tr.reply(conn, req, \"\", err)\n\t\treturn\n\t}\n\treq.URL = u\n\treq.Host = u.Host\n\n\treq.RequestURI = \"\"\n\trequestObj := r.requestPool.Get().(*RequestWrapper)\n\trequestObj.CreatedTime = time.Now()\n\trequestObj.request = req\n\trequestObj.TryCount = 0\n\trequestObj.ID = r.makeID()\n\n\tif !r.putTask(requestObj, false) {\n\t\tr.reply(conn, req, \"\", errors.New(\"request put into buffer timeout\"))\n\t\treturn\n\t}\n\n\tr.reply(conn, req, requestObj.ID, nil)\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tys := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = m.forward(x)\n\t}\n\treturn ys\n}", "func (r *LeakyReLU[O]) Forward() (mat.Tensor, error) {\n\treturn r.x.Value().(mat.Matrix).ApplyWithAlpha(leakyReLU, r.alpha.Value().Item().F64()), nil\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (g *game) forward() {\n\tg.player.Parse(g.input)\n\n\tif g.player.IsQuitting() {\n\t\tg.next = g.newMenu()\n\t}\n}", "func (fl *follow) forward(r io.Reader) (cont bool) {\n\tfl.Decoder.Reset(r)\n\treturn fl.Forwarder.Do(fl.Watcher, fl.Decoder)\n}", "func (b *RequiredArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) ArgumentNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (m *Model) StepForward(ns Nodes) (rv Nodes, err error) {\n\tstates := States{}\n\tvar tmp *Node\n\tfor _, x := range ns {\n\t\tif tmp, err = m.Forward(x, states); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trv = append(rv, tmp)\n\t}\n\treturn rv, nil\n}", "func (m *EventItemRequestBuilder) Forward()(*i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.ForwardRequestBuilder) {\n return i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.NewForwardRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func Forward(bus EventBus) EventHandler {\n\treturn Handler(func(evt Event) error {\n\t\tbus.Publish(evt)\n\t\treturn nil\n\t})\n}", "func (ti *TimeIndex) iterForward(t time.Time) index.Iter {\n i := ti.IndexNear(t)\n return &forwardIter{\n at: i,\n ti: ti,\n }\n}", "func Forward() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\terr := recover() // Have to do recover directly in deferred function\n\tinternalPanicHandler.forward(err)\n}", "func (s *Service) forwardToLeader(w http.ResponseWriter, req *http.Request) {\n\turl, err := url.Parse(s.RaftConfig.RaftNodeConfig.NodeProtocol + req.RequestURI)\n\tif err != nil {\n\t\tpanic(\"parse leader host url failed: \" + err.Error())\n\t}\n\turl.Host = s.raftNode.GetLeaderHost()\n\n\t// without leader, then return special error\n\tif url.Host == \"\" {\n\t\trpc.ReplyErr(w, apierrors.CodeNoLeader, apierrors.ErrNoLeader.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"forward url: %v\", url)\n\n\tproxy := httpproxy.ReverseProxy{\n\t\tDirector: func(request *http.Request) {\n\t\t\trequest.URL = url\n\t\t},\n\t}\n\n\tproxy.ServeHTTP(w, req)\n}", "func (mc *RobertaForMultipleChoice) ForwardT(inputIds, mask, tokenTypeIds, positionIds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\tnumChoices := inputIds.MustSize()[1]\n\n\tinputIdsSize := inputIds.MustSize()\n\tflatInputIds := inputIds.MustView([]int64{-1, inputIdsSize[len(inputIdsSize)-1]}, false)\n\n\tflatPositionIds := ts.None\n\tif positionIds.MustDefined() {\n\t\tpositionIdsSize := positionIds.MustSize()\n\t\tflatPositionIds = positionIds.MustView([]int64{-1, positionIdsSize[len(positionIdsSize)-1]}, false)\n\t}\n\n\tflatTokenTypeIds := ts.None\n\tif tokenTypeIds.MustDefined() {\n\t\ttokenTypeIdsSize := tokenTypeIds.MustSize()\n\t\tflatTokenTypeIds = tokenTypeIds.MustView([]int64{-1, tokenTypeIdsSize[len(tokenTypeIdsSize)-1]}, false)\n\t}\n\n\tflatMask := ts.None\n\tif mask.MustDefined() {\n\t\tflatMaskSize := flatMask.MustSize()\n\t\tflatMask = mask.MustView([]int64{-1, flatMaskSize[len(flatMaskSize)-1]}, false)\n\t}\n\n\tvar pooledOutput *ts.Tensor\n\t_, pooledOutput, hiddenStates, attentions, err = mc.roberta.ForwardT(flatInputIds, flatMask, flatTokenTypeIds, flatPositionIds, ts.None, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := pooledOutput.ApplyT(mc.dropout, train)\n\tappliedCls := appliedDO.Apply(mc.classifier)\n\toutput = appliedCls.MustView([]int64{-1, numChoices}, true)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func httpSetForward(store *ForwardStore) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tf := &Forward{}\n\n\t\tif r.Body == nil {\n\t\t\thttp.Error(w, \"No Post body\", 400)\n\t\t\treturn\n\t\t}\n\n\t\terr := json.NewDecoder(r.Body).Decode(f)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\n\t\tnewForward := store.set(f)\n\t\tjson.NewEncoder(w).Encode(newForward)\n\t}\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tif p.RequiresFullSeq() {\n\t\treturn p.fullSeqForward(xs)\n\t}\n\treturn p.incrementalForward(xs)\n}", "func forwardBox(ctx *Context, t *Tuple, w Writer) error {\n\tw.Write(ctx, t)\n\treturn nil\n}", "func (la *Lattice) Forward(m TokenizeMode) {\n\tfor i, size := 1, len(la.list); i < size; i++ {\n\t\tcurrentList := la.list[i]\n\t\tfor index, target := range currentList {\n\t\t\tprevList := la.list[target.Start]\n\t\t\tif len(prevList) == 0 {\n\t\t\t\tla.list[i][index].Cost = maximumCost\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j, n := range prevList {\n\t\t\t\tvar c int16\n\t\t\t\tif n.Class != USER && target.Class != USER {\n\t\t\t\t\tc = la.dic.Connection.At(int(n.Right), int(target.Left))\n\t\t\t\t}\n\t\t\t\ttotalCost := int64(c) + int64(target.Weight) + int64(n.Cost)\n\t\t\t\tif m != Normal {\n\t\t\t\t\ttotalCost += int64(additionalCost(n))\n\t\t\t\t}\n\t\t\t\tif totalCost > maximumCost {\n\t\t\t\t\ttotalCost = maximumCost\n\t\t\t\t}\n\t\t\t\tif j == 0 || int32(totalCost) < la.list[i][index].Cost {\n\t\t\t\t\tla.list[i][index].Cost = int32(totalCost)\n\t\t\t\t\tla.list[i][index].prev = la.list[target.Start][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func Forward(in, out Link) rules.Rule {\n\treturn rules.Rule(fmt.Sprintf(\n\t\t\"-t filter -A fw-interfaces -j ACCEPT -i %v -o %v\",\n\t\tin.Name(), out.Name()))\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tif len(xs) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tmean := ag.ReduceMean(x)\n\t\tdev := ag.SubScalar(x, mean)\n\t\tstdDev := ag.Sqrt(ag.Add(ag.ReduceMean(ag.Square(dev)), m.Eps))\n\t\tout[i] = ag.Add(ag.Prod(ag.DivScalar(dev, stdDev), m.W), m.B)\n\t}\n\treturn out\n}", "func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {\n\tlState := makeFBOLockState()\n\tfbo.headLock.RLock(lState)\n\tdefer fbo.headLock.RUnlock(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t// We're already up to date.\n\t\treturn\n\t}\n\tif !fbo.hasBeenCleared {\n\t\t// No reason to fast-forward here if it hasn't ever been\n\t\t// cleared.\n\t\treturn\n\t}\n\n\tfbo.forcedFastForwards.Add(1)\n\tfbo.goTracked(func() {\n\t\tdefer fbo.forcedFastForwards.Done()\n\t\tctx, cancelFunc := fbo.newCtxWithFBOID()\n\t\tdefer cancelFunc()\n\n\t\tfbo.log.CDebugf(ctx, \"Forcing a fast-forward\")\n\t\tvar currHead ImmutableRootMetadata\n\t\tvar err error\n\tgetMD:\n\t\tfor i := 0; ; i++ {\n\t\t\tcurrHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)\n\t\t\tswitch errors.Cause(err).(type) {\n\t\t\tcase nil:\n\t\t\t\tbreak getMD\n\t\t\tcase kbfsmd.ServerErrorUnauthorized:\n\t\t\t\t// The MD server connection might not be authorized\n\t\t\t\t// yet, so give it a few chances to go through.\n\t\t\t\tif i > 5 {\n\t\t\t\t\tfbo.log.CDebugf(ctx,\n\t\t\t\t\t\t\"Still unauthorized for TLF %s; giving up fast-forward\",\n\t\t\t\t\t\tfbo.id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i == 0 {\n\t\t\t\t\tfbo.log.CDebugf(\n\t\t\t\t\t\tctx, \"Got unauthorized error when fast-forwarding %s; \"+\n\t\t\t\t\t\t\t\"trying again after a delay\", fbo.id())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tdefault:\n\t\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif currHead == (ImmutableRootMetadata{}) {\n\t\t\tfbo.log.CDebugf(ctx, \"No MD yet\")\n\t\t\treturn\n\t\t}\n\t\tfbo.log.CDebugf(ctx, \"Current head is revision %d\", currHead.Revision())\n\n\t\tlState := makeFBOLockState()\n\t\t// Kick off partial prefetching once the latest merged\n\t\t// revision is set.\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tfbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)\n\t\t\t}\n\t\t}()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\tfbo.headLock.Lock(lState)\n\t\tdefer fbo.headLock.Unlock(lState)\n\n\t\tif !fbo.hasBeenCleared {\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t\tfbo.hasBeenCleared = false\n\t\t\t}\n\t\t}()\n\n\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t// We're already up to date.\n\t\t\tfbo.log.CDebugf(ctx, \"Already up-to-date: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = fbo.doFastForwardLocked(ctx, lState, currHead)\n\t\tif err != nil {\n\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %v\", err)\n\t\t}\n\t})\n}", "func (n *Node) Forward() FloatXX {\n\tif n.myoutCached {\n\t\treturn n.myout\n\t}\n\n\tif n.myType == InputNode {\n\t\tn.myout = n.inputValue\n\t} else {\n\t\tn.myout = FloatXX(0.0)\n\t\tfor index, otherNode := range n.inputNodes {\n\t\t\toutput := otherNode.Forward()\n\t\t\tn.inputs = append(n.inputs, output)\n\t\t\tn.myout += n.weights[index] * output\n\t\t}\n\t\tn.myout += n.biasValue * n.biasWeight\n\t\tmyoutActivated := n.activation(n.myout)\n\t\tn.myout = myoutActivated\n\t}\n\n\tn.myoutCached = true\n\treturn n.myout\n}", "func (r *Sub[O]) Forward() (mat.Tensor, error) {\n\treturn r.x1.Value().(mat.Matrix).Sub(r.x2.Value().(mat.Matrix)), nil\n}", "func (d *Dispatcher) HandleForward(address string, h ForwardDial) {\n\td.forwards[address] = h\n}", "func (p *Player) Forward() mgl32.Vec3 {\n\treturn p.Speed\n}", "func (m *NN) Forward(x *gorgonia.Node) (err error) {\n\tl := make([]*gorgonia.Node, len(m.W)+1)\n\tldot := make([]*gorgonia.Node, len(m.W))\n\tp := make([]*gorgonia.Node, len(m.W))\n\n\t// initial the first layer\n\tl[0] = x\n\n\t// W X + B\n\tfor i := 0; i < len(m.W); i++ {\n\t\tif len(m.B) != 0 && i < len(m.W) {\n\t\t\tL1, err := gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(l[i].Shape(), m.W[i].Shape())\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tldot[i], err = gorgonia.BroadcastAdd(L1, m.B[i], nil, []byte{0})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tldot[i], err = gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"mul wrong \", err)\n\t\t\t}\n\t\t}\n\n\t\t// Dropout\n\t\tp[i], err = gorgonia.Dropout(ldot[i], m.D[i])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Can't drop!\")\n\t\t}\n\n\t\t//activation function\n\t\tl[i+1] = gorgonia.Must(m.A[i](p[i]))\n\t}\n\n\tm.Pred = gorgonia.Must(m.A[len(m.A)-1](l[len(l)-1]))\n\tgorgonia.Read(m.Pred, &m.PredVal)\n\treturn\n}", "func (a *createRepository) forward(app *App, args ...interface{}) error {\n\tgUrl := repository.GitServerUri()\n\tvar users []string\n\tfor _, t := range app.GetTeams() {\n\t\tusers = append(users, t.Users...)\n\t}\n\tc := gandalf.Client{Endpoint: gUrl}\n\t_, err := c.NewRepository(app.Name, users, false)\n\treturn err\n}", "func forward(backend *Backend, local *net.TCPConn, remote *net.TCPConn) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tlogDebug(\"<%s> Start transfer %s to %s\", remote.RemoteAddr(), local.LocalAddr(), remote.LocalAddr())\n\tgo copy_half(backend, local, remote, &wg)\n\tgo copy_half(backend, remote, local, &wg)\n\twg.Wait()\n\tlogDebug(\"<%s> Finished transfer from %s to %s done\", remote.RemoteAddr(), local.LocalAddr(), remote.LocalAddr())\n}", "func (ms *MVCCStats) Forward(nowNanos int64) {\n\tif ms.LastUpdateNanos >= nowNanos {\n\t\treturn\n\t}\n\tms.AgeTo(nowNanos)\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func forwardTlcAck(gossiperPtr *core.Gossiper, ack *core.TLCAck) {\n\n\tif ack.HopLimit == 0 {\n\t\t// if we have reached the HopLimit, drop the message\n\t\treturn\n\t}\n\n\tgossiperPtr.DestinationTable.DsdvLock.Lock()\n\tforwardingAddress := gossiperPtr.DestinationTable.Dsdv[ack.Destination]\n\tgossiperPtr.DestinationTable.DsdvLock.Unlock()\n\t// If current node has no information about next hop to the destination in question\n\tif strings.Compare(forwardingAddress, \"\") == 0 {\n\t\t// TODO: What to do if there is no 'next hop' known when peer has to forward a private packet\n\t}\n\n\t// Decrement the HopLimit right before forwarding the packet\n\tack.HopLimit--\n\t// Encode and send packet\n\tpacketToSend := core.GossipPacket{Ack: ack}\n\tpacketBytes, err := protobuf.Encode(&packetToSend)\n\thelpers.HandleErrorFatal(err)\n\tcore.ConnectAndSend(forwardingAddress, gossiperPtr.Conn, packetBytes)\n}", "func (t *TimeLine) forward(num, denom uint32, runCallbacks bool) {\n\tend := t.cursor + t.Ticks(num, denom)\n\tif runCallbacks {\n\t\tt.lastDelta = t.runCallbacks(t.cursor, end)\n\t}\n\tt.cursor = end\n}", "func (qa *RobertaForQuestionAnswering) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (startScores, endScores *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := qa.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, ts.None, nil, nil, err\n\t}\n\n\tsequenceOutput := hiddenState.Apply(qa.qaOutputs)\n\tlogits := sequenceOutput.MustSplit(1, -1, true)\n\tstartScores = logits[0].MustSqueeze1(-1, false)\n\tendScores = logits[1].MustSqueeze1(-1, false)\n\n\tfor _, x := range logits {\n\t\tx.MustDrop()\n\t}\n\n\treturn startScores, endScores, hiddenStates, attentions, nil\n}", "func forwardRequest(originatorAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte, toNode Node) {\n\tif self.Addr.String() == toNode.Addr.String() {\n\t\tfmt.Println(\"Stop. Can't forward to self - \", toNode.Addr.String())\n\t\treturn\n\t}\n\n\tsendRequestToNode(msgID, reqPay, &toNode)\n}", "func (pf *PortForwarder) ForwardPort(ctx context.Context, req *waterfall_grpc.PortForwardRequest) (*empty_pb.Empty, error) {\n\tpf.sessionsMutex.Lock()\n\tdefer pf.sessionsMutex.Unlock()\n\n\tlog.Printf(\"Forwarding %s -> %s ...\\n\", req.Session.Src, req.Session.Dst)\n\n\tkind, addr, err := parseAddr(req.Session.Src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse dst even if we don't use it. No point in sending it the server if its malformed.\n\tif _, _, err := parseAddr(req.Session.Dst); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s, ok := pf.sessions[req.Session.Src]; ok {\n\t\tif !req.Rebind {\n\t\t\treturn nil, status.Errorf(codes.AlreadyExists, \"no-rebind specified, can't forward address: %s\", req.Session.Src)\n\t\t}\n\n\t\tdelete(pf.sessions, req.Session.Src)\n\n\t\tif err := s.lis.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlis, err := net.Listen(kind, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The context we create in this case is scoped to the duration of the forwarding\n\t// session, which outlives this request, therefore we can't propagate the request\n\t// context and are forced to create a new one.\n\tfCtx, cancel := context.WithCancel(context.Background())\n\n\tpf.sessions[req.Session.Src] = &forwardSession{src: req.Session.Src, dst: req.Session.Dst, lis: lis, cancel: cancel}\n\tgo func() {\n\t\tdefer cancel()\n\t\tdefer lis.Close()\n\t\tfor {\n\t\t\tconn, err := lis.Accept()\n\t\t\tif err != nil {\n\t\t\t\t// Theres really not much else we can do\n\t\t\t\tlog.Printf(\"Error accepting connection: %v\\n\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfwdr, err := makeForwarder(fCtx, pf.client, req.Session.Dst, conn)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error creating forwarder: %v\\n\", err)\n\t\t\t\tconn.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo fwdr.Forward()\n\t\t}\n\t}()\n\n\treturn &empty_pb.Empty{}, nil\n}", "func (m *ItemCalendarsItemCalendarViewEventItemRequestBuilder) Forward()(*ItemCalendarsItemCalendarViewItemForwardRequestBuilder) {\n return NewItemCalendarsItemCalendarViewItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (pf *PortForwarder) ForwardPort(ctx context.Context, req *waterfall_grpc_pb.PortForwardRequest) (*empty_pb.Empty, error) {\n\tpf.sessionsMutex.Lock()\n\tdefer pf.sessionsMutex.Unlock()\n\n\tlog.Printf(\"Forwarding %s -> %s ...\\n\", req.Session.Src, req.Session.Dst)\n\n\tkind, addr, err := parseAddr(req.Session.Src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse dst even if we don't use it. No point in sending it the server if its malformed.\n\tif _, _, err := parseAddr(req.Session.Dst); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif s, ok := pf.sessions[req.Session.Src]; ok {\n\t\tif !req.Rebind {\n\t\t\treturn nil, status.Errorf(codes.AlreadyExists, \"no-rebind specified, can't forward address: %s\", req.Session.Src)\n\t\t}\n\n\t\tdelete(pf.sessions, req.Session.Src)\n\n\t\tif err := s.lis.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tlis, err := net.Listen(kind, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The context we create in this case is scoped to the duration of the forwarding\n\t// session, which outlives this request, therefore we can't propagate the request\n\t// context and are forced to create a new one.\n\tfCtx, cancel := context.WithCancel(context.Background())\n\n\tpf.sessions[req.Session.Src] = &forwardSession{src: req.Session.Src, dst: req.Session.Dst, lis: lis, cancel: cancel}\n\tgo func() {\n\t\tdefer cancel()\n\t\tdefer lis.Close()\n\t\tfor {\n\t\t\tconn, err := lis.Accept()\n\t\t\tif err != nil {\n\t\t\t\t// Theres really not much else we can do\n\t\t\t\tlog.Printf(\"Error accepting connection: %v\\n\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfwdr, err := makeForwarder(fCtx, pf.client, req.Session.Dst, conn)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error creating forwarder: %v\\n\", err)\n\t\t\t\tconn.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo fwdr.Forward()\n\t\t}\n\t}()\n\n\treturn &empty_pb.Empty{}, nil\n}", "func (b *LiteralArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) LiteralNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (r *Threshold[O]) Forward() (mat.Tensor, error) {\n\ty := r.x.Value().(mat.Matrix).ApplyWithAlpha(\n\t\tthreshold,\n\t\tr.threshold.Value().Item().F64(),\n\t\tr.k.Value().Item().F64(),\n\t)\n\treturn y, nil\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (v *SourceSearchContext) Forward(iter *gtk.TextIter) (*gtk.TextIter, *gtk.TextIter, bool, bool) {\n\n\tstart, end := new(gtk.TextIter), new(gtk.TextIter)\n\tvar hasWrappedAround C.gboolean\n\n\tc := C.gtk_source_search_context_forward(\n\t\tv.native(),\n\t\tnativeTextIter(iter),\n\t\tnativeTextIter(start),\n\t\tnativeTextIter(end),\n\t\t&hasWrappedAround)\n\n\treturn start, end, gobool(hasWrappedAround), gobool(c)\n}", "func Forward(url string, w *http.ResponseWriter, r *http.Request, logger l.Logger) error {\n\tlogger.Info(r.Context(), fmt.Sprintf(\"proxy for %v\", url))\n\tvar body []byte\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\tlogger.Error(r.Context(), fmt.Sprintf(\"Could not read bytes %v\", err.Error()))\n\t\treturn fmt.Errorf(\"Could not read bytes %v\", err.Error())\n\t}\n\treq, err := http.NewRequest(r.Method, url, bytes.NewReader(body))\n\tif err != nil {\n\t\tlogger.Error(r.Context(), fmt.Sprintf(\"Could not create request for %v, %v\", url, err.Error()))\n\t\treturn fmt.Errorf(\"Could not create request for %v, %v\", url, err.Error())\n\t}\n\tclient := &http.Client{}\n\tfor k, v := range r.Header {\n\t\tfor _, header := range v {\n\t\t\treq.Header.Add(k, header)\n\t\t}\n\t}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\te := fmt.Errorf(\"Error from client %v, %v\", url, err.Error())\n\t\tlogger.Error(r.Context(), e.Error())\n\t\treturn e\n\t}\n\tlogger.Info(r.Context(), fmt.Sprintf(\"status from %v - %v\", url, res.StatusCode))\n\n\tfor k, v := range res.Header {\n\t\tfor _, header := range v {\n\t\t\t(*w).Header().Add(k, header)\n\t\t}\n\t}\n\tb, err := ioutil.ReadAll(res.Body)\n\tdefer res.Body.Close()\n\tif !(res.StatusCode >= 200 && res.StatusCode < 299) {\n\t\tlogger.Error(r.Context(), fmt.Sprintf(\"headers: %v\", res.Header))\n\t\ts, err := gunzipWrite(b)\n\t\tif err != nil {\n\t\t\ts = string(b)\n\t\t}\n\t\tlogger.Error(r.Context(), fmt.Sprintf(\"Error from cp: %v\", s))\n\t}\n\tif err != nil {\n\t\tlogger.Error(r.Context(), fmt.Sprintf(\"Error on reading cp response bytes %v\", err.Error()))\n\t\treturn fmt.Errorf(\"Error on reading cp response bytes %v\", err.Error())\n\t}\n\t(*w).WriteHeader(res.StatusCode)\n\t(*w).Write(b)\n\treturn nil\n}", "func (f *RemoteRuntime) PortForward(ctx context.Context, req *kubeapi.PortForwardRequest) (*kubeapi.PortForwardResponse, error) {\n\treturn f.RuntimeService.PortForward(ctx, req)\n}", "func forwardRequest(client *http.Client, request *utils.ForwardedRequest) error {\n\thttpRequest := request.Contents\n\tif *forwardUserID {\n\t\thttpRequest.Header.Add(utils.HeaderUserID, request.User)\n\t}\n\treverseProxy := httputil.NewSingleHostReverseProxy(&url.URL{\n\t\tScheme: \"http\",\n\t\tHost: *host,\n\t})\n\treverseProxy.FlushInterval = 100 * time.Millisecond\n\tresponseForwarder, err := utils.NewResponseForwarder(client, *proxy, request.BackendID, request.RequestID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treverseProxy.ServeHTTP(responseForwarder, httpRequest)\n\tif *debug {\n\t\tlog.Printf(\"Backend latency for request %s: %s\\n\", request.RequestID, time.Since(request.StartTime).String())\n\t}\n\treturn responseForwarder.Close()\n}", "func ResetForwardContext(ctx context.Context) context.Context {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\tlog.Error(\"failed to get forwarding metadata\")\n\t}\n\tmd.Set(ForwardMetadataKey, \"\")\n\treturn metadata.NewOutgoingContext(ctx, md)\n}", "func (xf *HttpEchoTransfer) Forward() (inbytes uint64, outbytes uint64, err error) {\n\txf.m.Lock()\n\tdefer xf.m.Unlock()\n\tif xf.forwarding {\n\t\terr = errors.New(\"already forwarding\")\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\t/*\n\t\t// CMsg\n\t\ttype CMsg struct {\n\t\t\tCode uint64\n\t\t\tId uint64\n\t\t\tMsg []byte\n\t\t\tErr error\n\t\t}\n\t*/\n\tvar msg *cmtp.CMsg\n\tvar rw *net.TCPConn\n\t/*\n\t\tnewrawio chan io.ReadWriteCloser\n\t\tlastIdx int\n\t\trawio []io.ReadWriteCloser\n\t\tidleslot *queues.LifoQ\n\t\tworkerMsg chan *cmtp.CMsg\n\t*/\n\tvar rwidx int\n\ttime.Sleep(1e9)\n\ttpf(\"HttpEchoTransfer forwarding ...\\n\")\n\tfor {\n\t\tselect {\n\t\tcase rw = <-xf.newrawio:\n\t\t\tidlecount := xf.idleslot.Pop()\n\t\t\tif idlecount == nil {\n\t\t\t\txf.lastIdx++\n\t\t\t\trwidx = xf.lastIdx\n\t\t\t\txf.rawio = append(xf.rawio, rw)\n\t\t\t} else {\n\t\t\t\trwidx = idlecount.(int)\n\t\t\t\txf.rawio[rwidx] = rw\n\t\t\t}\n\t\t\twg.Add(1)\n\t\t\tgo xf.echoserver(rwidx, &wg)\n\t\tcase msg = <-xf.workerMsg:\n\t\t\t//tpf(\"echoserver exit with msg %v\\n\", msg)\n\t\t\t//tpf(\"echoserver exit with msg %s\\n\", msg.String())\n\t\t\t//msg = <-xf.workerMsg\n\t\t\t//tpf(\"echoserver exit with msg2 %s\\n\", msg.String())\n\t\t\txf.rawio[msg.Id].Close()\n\t\t\txf.rawio[msg.Id] = nil\n\t\t\txf.idleslot.Push(int(msg.Id))\n\t\t\t// TODO: in/out bytes in msg.Msg\n\t\t}\n\t}\n\twg.Wait()\n\tclose(xf.closed)\n\treturn\n}", "func forwardMessage(originalConn net.Conn, msg *Message, excludeOriginal bool) {\n\tif msg.TTL <= 1 {\n\t\t// don't forward\n\t\treturn\n\t}\n\n\tmsg.TTL = msg.TTL - 1 // decrement ttl\n\tmsg.Hops = msg.Hops + 1 // increment hops\n\n\t// forward to all connected peers\n\tfor conn, _ := range conn2peer {\n\t\tif (conn == originalConn) == excludeOriginal {\n\t\t\tcontinue\n\t\t}\n\t\tsend(conn, msg)\n\t}\n}", "func (pf *PortForwarder) ReverseForwardPort(ctx context.Context, req *waterfall_grpc_pb.PortForwardRequest) (*empty_pb.Empty, error) {\n\tpf.reverseSessionsMutex.Lock()\n\tdefer pf.reverseSessionsMutex.Unlock()\n\n\tlog.Printf(\"Reverse forwarding %s -> %s ...\\n\", req.Session.Src, req.Session.Dst)\n\tif rs, ok := pf.reverseSessions[req.Session.Src]; ok {\n\t\tif !req.Rebind {\n\t\t\treturn nil, status.Errorf(codes.AlreadyExists, \"no-rebind specified, can't forward address: %s\", req.Session.Src)\n\t\t}\n\t\tif err := pf.stopReverseForwarding(ctx, rs); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tsrcKind, srcAddr, err := parseAddr(req.Session.Src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdstKind, dstAddr, err := parseAddr(req.Session.Dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrcNtwk, err := networkKind(srcKind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The context we create in this case is scoped to the duration of the forwarding\n\t// session, which outlives this request, therefore we can't propagate the request\n\t// context and are forced to create a new one.\n\tfCtx, cancel := context.WithCancel(context.Background())\n\n\t// 1) Ask the server to listen for connections on src\n\tncs, err := pf.client.StartReverseForward(\n\t\tfCtx,\n\t\t&waterfall_grpc_pb.ForwardMessage{\n\t\t\tOp: waterfall_grpc_pb.ForwardMessage_OPEN,\n\t\t\tKind: srcNtwk,\n\t\t\tAddr: srcAddr})\n\tif err != nil {\n\t\tlog.Printf(\"Failed to start reverse forwarding session (%s -> %s): %v\", req.Session.Src, req.Session.Dst, err)\n\t\treturn nil, err\n\t}\n\n\tss := &forwardSession{src: req.Session.Src, dst: req.Session.Dst, cancel: cancel}\n\tpf.reverseSessions[req.Session.Src] = ss\n\n\t// Listen for new connections on a different goroutine so we can return to the client\n\tgo func() {\n\t\tdefer pf.stopReverseForwarding(fCtx, ss)\n\t\tfor {\n\t\t\tlog.Print(\"Waiting for new connection to forward...\")\n\t\t\tfwd, err := ncs.Recv()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Waterfall server error when listening for reverse forwarding connections: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif fwd.Op != waterfall_grpc_pb.ForwardMessage_OPEN {\n\t\t\t\t// The only type of message the server can reply is with an OPEN message\n\t\t\t\tlog.Printf(\"Requested OP %v but only open is supported ...\\n\", fwd.Op)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// 2) Hand the server a stream to start forwarding the connection\n\t\t\tfs, err := pf.client.ReverseForward(fCtx)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to create new forwarding session: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tntwk := srcNtwk\n\t\t\taddr := srcAddr\n\t\t\tif fwd.GetKind() != waterfall_grpc_pb.ForwardMessage_UNSET && len(fwd.Addr) > 0 {\n\t\t\t\tntwk = fwd.Kind\n\t\t\t\taddr = fwd.Addr\n\t\t\t}\n\t\t\tif err := fs.Send(&waterfall_grpc_pb.ForwardMessage{\n\t\t\t\tOp: waterfall_grpc_pb.ForwardMessage_OPEN,\n\t\t\t\tKind: ntwk,\n\t\t\t\tAddr: addr,\n\t\t\t}); err != nil {\n\t\t\t\tlog.Printf(\"Failed to create new forwarding request: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconn, err := net.Dial(dstKind, dstAddr)\n\t\t\tif err != nil {\n\t\t\t\t// Ignore this error. The socket might not be open initially\n\t\t\t\t// but can be created after the forwarding session.\n\t\t\t\tlog.Printf(\"Failed to connect %s:%s: %v\", dstKind, dstAddr, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// 3) Forward the stream to the connection\n\t\t\tgo forward.NewStreamForwarder(fs, conn.(forward.HalfReadWriteCloser)).Forward()\n\t\t}\n\t}()\n\treturn &empty_pb.Empty{}, nil\n}", "func Forward(ctx context.Context, destination chan<- packet.Buf, source <-chan packet.Buf) {\n\tdefer contextack.Ack(ctx, ForwardDoneAck)\n\n\tvar p packet.Buf\n\n\tfor {\n\t\tvar (\n\t\t\tinput <-chan packet.Buf\n\t\t\toutput chan<- packet.Buf\n\t\t\tok bool\n\t\t)\n\n\t\tif p == nil {\n\t\t\tinput = source\n\t\t} else {\n\t\t\toutput = destination\n\t\t}\n\n\t\tselect {\n\t\tcase p, ok = <-input:\n\t\t\tif !ok {\n\t\t\t\t// EOF\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase output <- p:\n\t\t\t// ok\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *ProcType) FastForward(rev int64) *ProcType {\n\treturn p.Dir.Snapshot.fastForward(p, rev).(*ProcType)\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tlength := len(xs)\n\tqs := p.query.Forward(xs...)\n\tks := make([]ag.Node, length)\n\tvs := p.value.Forward(xs...)\n\tmapk := make(map[int]*IndexedNodes)\n\tmapv := make(map[int]*IndexedNodes)\n\n\t// TODO: can it be implemented in a concurrent fashion?\n\tfor i, q := range qs {\n\t\tnorm := p.Graph.Sqrt(p.Graph.ReduceSum(p.Graph.Pow(q, 2.0)))\n\t\tks[i] = p.Graph.DivScalar(q, norm) // Euclidean norm\n\t\th := p.getHash(ks[i].Value().(*mat.Dense))\n\t\tinsertNode(mapk, ks[i], i, h)\n\t\tinsertNode(mapv, vs[i], i, h)\n\t}\n\n\tcontext := make([]ag.Node, length)\n\tprob := make([]mat.Matrix, length)\n\tfor i, q := range qs {\n\t\tj := p.getHash(q.Value().(*mat.Dense))\n\t\tc, p := p.lshScaledDotProductAttention(p.Graph, q, mapk[j], mapv[j], length, p.scaleFactor)\n\t\tcontext[i], prob[i] = c, p\n\t}\n\n\tp.Attention = &ContextProb{\n\t\tcontext: context,\n\t\tprob: prob,\n\t}\n\treturn context\n}", "func (rr *RandRotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := RandomRotate(fx, rr.minAngle, rr.maxAngle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (matrix Matrix4) Forward() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[2][0],\n\t\tmatrix[2][1],\n\t\tmatrix[2][2],\n\t}.Unit()\n}" ]
[ "0.7021994", "0.6554831", "0.6494534", "0.6460856", "0.64138633", "0.62935233", "0.6266006", "0.6205411", "0.61404204", "0.6131823", "0.61229944", "0.6081643", "0.6071474", "0.60542464", "0.5995417", "0.59735703", "0.5953793", "0.5952972", "0.59456825", "0.5916433", "0.5840809", "0.5834047", "0.5824141", "0.5822762", "0.5814688", "0.5806252", "0.5802045", "0.5793296", "0.5781284", "0.57792765", "0.5776357", "0.5764789", "0.57578975", "0.57087106", "0.5698675", "0.56948453", "0.5692444", "0.5661456", "0.5651031", "0.5651031", "0.561484", "0.55967534", "0.559224", "0.55902374", "0.5576927", "0.5575251", "0.55661285", "0.5562041", "0.556015", "0.5553494", "0.55518436", "0.5546413", "0.5537088", "0.55337507", "0.55293685", "0.55271274", "0.55260706", "0.5514577", "0.55121416", "0.5510736", "0.54763883", "0.54474473", "0.54454505", "0.54141736", "0.54116905", "0.53992206", "0.53769636", "0.53702116", "0.5350268", "0.5349511", "0.5340738", "0.53328174", "0.5320688", "0.531624", "0.53015196", "0.530074", "0.5295355", "0.529069", "0.5273279", "0.5271892", "0.52708083", "0.527069", "0.52704", "0.526724", "0.526386", "0.52399117", "0.52399117", "0.5232421", "0.52215207", "0.5220331", "0.521371", "0.5213434", "0.5213048", "0.5190803", "0.5186339", "0.516464", "0.5141898", "0.5141585", "0.51387167", "0.5135343" ]
0.5994497
15
NewRobertaForSequenceClassification creates a new RobertaForSequenceClassification model.
func NewRobertaForSequenceClassification(p *nn.Path, config *bert.BertConfig) *RobertaForSequenceClassification { roberta := bert.NewBertModel(p.Sub("roberta"), config) classifier := NewRobertaClassificationHead(p.Sub("classifier"), config) return &RobertaForSequenceClassification{ roberta: roberta, classifier: classifier, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRobertaClassificationHead(p *nn.Path, config *bert.BertConfig) *RobertaClassificationHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\tnumLabels := int64(len(config.Id2Label))\n\toutProj := nn.NewLinear(p.Sub(\"out_proj\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\n\treturn &RobertaClassificationHead{\n\t\tdense: dense,\n\t\tdropout: dropout,\n\t\toutProj: outProj,\n\t}\n}", "func NewRobertaForTokenClassification(p *nn.Path, config *bert.BertConfig) *RobertaForTokenClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tnumLabels := int64(len(config.Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForTokenClassification{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewRobertaForMultipleChoice(p *nn.Path, config *bert.BertConfig) *RobertaForMultipleChoice {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, 1, nn.DefaultLinearConfig())\n\n\treturn &RobertaForMultipleChoice{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\n\tlayerNormConfig := nn.DefaultLayerNormConfig()\n\tlayerNormConfig.Eps = 1e-12\n\tlayerNorm := nn.NewLayerNorm(p.Sub(\"layer_norm\"), []int64{config.HiddenSize}, layerNormConfig)\n\n\tdecoder := util.NewLinearNoBias(p.Sub(\"decoder\"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig())\n\n\tbias := p.NewVar(\"bias\", []int64{config.VocabSize}, nn.NewKaimingUniformInit())\n\n\treturn &RobertaLMHead{\n\t\tdense: dense,\n\t\tdecoder: decoder,\n\t\tlayerNorm: layerNorm,\n\t\tbias: bias,\n\t}\n}", "func New(cfg *Config) *Sequence {\n\treturn &Sequence{\n\t\tcfg: cfg,\n\t}\n}", "func New(cfg *Config) *Sequence {\n\treturn &Sequence{\n\t\tcfg: cfg,\n\t}\n}", "func NewSequenceNode(nm string, node ...BTNode) *SequenceNode {\n\tx := SequenceNode{}\n\tx.Label = nm\n\tx.Type = reflect.TypeOf(x).Name()\n\tif len(node) > 0 {\n\t\tx.Nodes = append(x.Nodes, node...)\n\t}\n\treturn &x\n}", "func NewRobertaForQuestionAnswering(p *nn.Path, config *bert.BertConfig) *RobertaForQuestionAnswering {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForQuestionAnswering{\n\t\troberta: roberta,\n\t\tqaOutputs: qaOutputs,\n\t}\n}", "func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tlmHead := NewRobertaLMHead(p.Sub(\"lm_head\"), config)\n\n\treturn &RobertaForMaskedLM{\n\t\troberta: roberta,\n\t\tlmHead: lmHead,\n\t}\n}", "func (b batchPredictor) NewPredictor() predHelp.Predictor {\n\treturn b\n}", "func (sc *RobertaForSequenceClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tsc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tsc.classifier = NewRobertaClassificationHead(p.Sub(\"classifier\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewSequence() *Sequence {\n\tseq := &Sequence{}\n\tseq.TokenList = make([]*token.Token, 0, 5)\n\treturn seq\n}", "func NewSequence(name string) *Sequence {\n\treturn &Sequence{\n\t\tName: fmt.Sprintf(\"sequence%s%s\", KeyDelimiter, name),\n\t\tNumber: 0,\n\t\tlock: sync.Mutex{},\n\t}\n}", "func NewClassifier(model Model) Classifier {\n\treturn Classifier{\n\t\tModel: model,\n\t\tLearningResults: make(map[string]map[Class]int),\n\t\tPriorProbabilities: make(map[Class]float64),\n\t\tNDocumentByClass: make(map[Class]int),\n\t\tNFrequencyByClass: make(map[Class]int),\n\t}\n}", "func NewRoar(author string, text string) *Roar {\n return &Roar{Author: author, Text: text,\n CreationDate: time.LocalTime().Format(time.RFC1123)}\n}", "func New(backoff []time.Duration, class Classifier) *Retrier {\n\tif class == nil {\n\t\tclass = DefaultClassifier{}\n\t}\n\n\treturn &Retrier{\n\t\tbackoff: backoff,\n\t\tclass: class,\n\t\trand: rand.New(rand.NewSource(time.Now().UnixNano())),\n\t}\n}", "func NewSeq(s []byte) Seq {\n\treturn Seq{\n\t\tLength: len(s),\n\t\tSeq: contract(s),\n\t}\n}", "func NewRptSeq(val int) RptSeqField {\n\treturn RptSeqField{quickfix.FIXInt(val)}\n}", "func NewRBAC(address common.Address, backend bind.ContractBackend) (*RBAC, error) {\n\tcontract, err := bindRBAC(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBAC{RBACCaller: RBACCaller{contract: contract}, RBACTransactor: RBACTransactor{contract: contract}, RBACFilterer: RBACFilterer{contract: contract}}, nil\n}", "func NewSequenceReader(b []byte) io.Reader {\n\treturn &sequenceReader{b: b, o: 0}\n}", "func (b batchPredictor) NewPredictor() Predictor {\n\tprevOutput, tmpOutput := newPredictMemory(b.neurons)\n\treturn predictor{\n\t\tneurons: b.neurons,\n\t\tparameters: b.parameters,\n\t\ttmpOutput: tmpOutput,\n\t\tprevTmpOutput: prevOutput,\n\t\tinputDim: b.inputDim,\n\t\toutputDim: b.outputDim,\n\t}\n}", "func NewSequence(gid int, elements ...Element) *Sequence {\n\treturn &Sequence{\n\t\telement: element{gid},\n\t\telements: elements,\n\t}\n}", "func New[T float.DType](c Config) *RAdam[T] {\n\tadam := &RAdam[T]{\n\t\tConfig: c,\n\t\tRoMax: 2.0/(1.0-c.Beta2) - 1.0,\n\t\tTimeStep: 1.0,\n\t}\n\treturn adam\n}", "func NewSequence(n uint64) *Sequence {\n\treturn &Sequence{n: n}\n}", "func NewClassifierFromReader(r io.Reader) (c *Classifier, err error) {\n\tdec := gob.NewDecoder(r)\n\tw := new(Classifier)\n\terr = dec.Decode(w)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode as Classifier: %w\", err)\n\t}\n\n\treturn w, nil\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func New() *Classifier {\n\treturn &Classifier{\n\t\tNewFrequencyStorage(),\n\t}\n}", "func NewNewSeqNo(val int) NewSeqNoField {\n\treturn NewSeqNoField{quickfix.FIXInt(val)}\n}", "func NewTipsetSeq(initialEpoch abi.ChainEpoch) *TipsetSeq {\n\treturn &TipsetSeq{\n\t\tepochOffset: initialEpoch,\n\t\tmsgIdx: make(map[cid.Cid]*ApplicableMessage),\n\t}\n}", "func NewLearner(id int, nrOfNodes int, valueOut chan<- Value) *Learner {\n\t//TODO(student): Task 2 and 3 - algorithm and distributed implementation\n\treturn &Learner{}\n}", "func New(lms chan mysignals.LifeSignal) *Person {\n\t// create new Person\n\tp := Person{\n\t\tid: newPersonID(),\n\t\tage: Age{\n\t\t\tvalue: 15,\n\t\t\tlock: sync.Mutex{},\n\t\t\tmaxage: 40,\n\t\t},\n\t\tsmartphone: smartphone.New(),\n\t\tlifemsgs: lms,\n\t\tengaged: engaged{\n\t\t\tvalue: false,\n\t\t\tlock: sync.Mutex{},\n\t\t},\n\t\t// use &brain.Brain{}\n\t\t// instead of brain.Brain{}\n\t\t// because Brain implements the interface DecisionMaker{} using a pointer receiver\n\t\t// \t\t\t(b* Brain)Method(...)\n\t\t// instead of a value receiver\n\t\t// \t\t\t(b Brain)Method(...)\n\t\tbrain: &brain.Brain{},\n\t\t// sex is M or F\n\t\tsex: func() byte {\n\t\t\tif utils.NewRandomIntInRange(0, 1) == 0 {\n\t\t\t\treturn 'M'\n\t\t\t}\n\t\t\treturn 'F'\n\t\t}(),\n\t}\n\t// start listening for signals\n\tgo (&p).listenForSignals()\n\t// return Person information\n\treturn &p\n}", "func New() Model {\n\treturn Model{\n\t\tType: Arabic,\n\t\tPage: 0,\n\t\tPerPage: 1,\n\t\tTotalPages: 1,\n\t\tKeyMap: DefaultKeyMap,\n\t\tActiveDot: \"•\",\n\t\tInactiveDot: \"○\",\n\t\tArabicFormat: \"%d/%d\",\n\t}\n}", "func NewRBACTransactor(address common.Address, transactor bind.ContractTransactor) (*RBACTransactor, error) {\n\tcontract, err := bindRBAC(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBACTransactor{contract: contract}, nil\n}", "func NewRecognizer(modelDir string) (rec *Recognizer, err error) {\n\tcModelDir := C.CString(modelDir)\n\tdefer C.free(unsafe.Pointer(cModelDir))\n\tptr := C.facerec_init(cModelDir)\n\n\tif ptr.err_str != nil {\n\t\tdefer C.facerec_free(ptr)\n\t\tdefer C.free(unsafe.Pointer(ptr.err_str))\n\t\terr = makeError(C.GoString(ptr.err_str), int(ptr.err_code))\n\t\treturn\n\t}\n\n\trec = &Recognizer{ptr}\n\treturn\n}", "func (db GAEDatabase) NewTrainer(t pkmn.Trainer) database.Trainer {\n\treturn &GAETrainer{Trainer: t}\n}", "func New(questionsPath string, textPath string) *Truman {\n\tt := &Truman{}\n\n\tquestionsFilePath, _ := filepath.Abs(questionsPath)\n\ttextFilePath, _ := filepath.Abs(textPath)\n\n\tt.loadQuestions(questionsFilePath)\n\tt.loadText(textFilePath)\n\n\treturn t\n}", "func (llrb *LLRB) Setseqno(seqno uint64) {\n\tllrb.seqno = seqno\n}", "func NewRGASS() RGASS {\n\trgass := RGASS{Model: NewModel()}\n\treturn rgass\n}", "func NewClassifier(ctx *pulumi.Context,\n\tname string, args *ClassifierArgs, opts ...pulumi.ResourceOption) (*Classifier, error) {\n\tif args == nil {\n\t\targs = &ClassifierArgs{}\n\t}\n\n\tvar resource Classifier\n\terr := ctx.RegisterResource(\"aws:glue/classifier:Classifier\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewClass(r *http.Request) (class Class, err error) {\n\terr = r.ParseMultipartForm(utilities.MAX_STORAGE)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&class, r.PostForm)\n\treturn\n}", "func New() *RBTree {\n\treturn &RBTree{\n\t\tlock: sync.RWMutex{},\n\t\tNode: nil,\n\t\tstack: newStack(nil),\n\t}\n}", "func NewRR(backends ...Backend) *RR {\n\treturn &RR{backends, 0}\n}", "func NewRobot(mode RobotMode, format *audio.Format) Encoder {\n return &robotEncoder{\n mode: mode,\n format: format,\n }\n}", "func (t *OpenconfigQos_Qos_Classifiers) NewClassifier(Name string) (*OpenconfigQos_Qos_Classifiers_Classifier, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Classifier == nil {\n\t\tt.Classifier = make(map[string]*OpenconfigQos_Qos_Classifiers_Classifier)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Classifier[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Classifier\", key)\n\t}\n\n\tt.Classifier[key] = &OpenconfigQos_Qos_Classifiers_Classifier{\n\t\tName: &Name,\n\t}\n\n\treturn t.Classifier[key], nil\n}", "func New(randomized bool) *RF1R {\n\tres := RF1R{}\n\n\tif randomized {\n\t\tres.hasher1 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t\tres.hasher2 = func(b []byte) uint64 { return siphash.Hash(2, 3, b) }\n\t} else {\n\t\tres.hasher1 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t\tres.hasher2 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t}\n\n\treturn &res\n}", "func NewRoundRobin() consensus.LeaderRotation {\n\treturn &roundRobin{}\n}", "func NewRTGProtocol(n int, q, p []uint64, sigma float64) *RTGProtocol {\n\trtg := new(RTGProtocol)\n\trtg.ringQModCount = len(q)\n\trtg.ringPModulusBigint = big.NewInt(1)\n\tfor _, pi := range p {\n\t\trtg.ringPModulusBigint.Mul(rtg.ringPModulusBigint, new(big.Int).SetUint64(pi))\n\t}\n\trtg.alpha = len(p)\n\tif rtg.alpha != 0 {\n\t\trtg.beta = int(math.Ceil(float64(len(q)) / float64(len(p))))\n\t} else {\n\t\trtg.beta = 1\n\t}\n\tvar err error\n\trtg.ringQP, err = ring.NewRing(n, append(q, p...))\n\tif err != nil {\n\t\tpanic(err) // TODO error\n\t}\n\n\tprng, err := utils.NewPRNG()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trtg.gaussianSampler = ring.NewGaussianSampler(prng)\n\trtg.sigma = sigma\n\n\trtg.tmpPoly = [2]*ring.Poly{rtg.ringQP.NewPoly(), rtg.ringQP.NewPoly()}\n\n\treturn rtg\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func NewRole(client client.Client, role rbacv1.Role) (Role, error) {\n\tcreatedRole, err := client.Kubernetes.\n\t\tRbacV1().\n\t\tRoles(role.Namespace).\n\t\tCreate(client.Ctx, &role, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn Role{}, fmt.Errorf(\"failed to create role %s in namespace %s: %w\", role.Name, role.Namespace, err)\n\t}\n\n\treturn Role{\n\t\tRole: *createdRole,\n\t\tclient: client,\n\t}, nil\n}", "func FromRNA(rna string) ([]string, error) {\n\tvar result []string\n\tfor i := 0; i < len(rna)-2; i += 3 {\n\t\tcodon := rna[i : i+3]\n\t\tpro, present := codToPro[codon]\n\t\tif !present {\n\t\t\treturn result, ErrInvalidBase\n\t\t}\n\t\tif pro == \"STOP\" {\n\t\t\treturn result, nil\n\t\t}\n\t\tresult = append(result, pro)\n\t}\n\treturn result, nil\n}", "func NewRaid(inputPlanes ...Plane) (Raid, error) {\n\tif len(inputPlanes) == 0 {\n\t\treturn Raid{}, errors.New(\"no planes to launch\")\n\t}\n\tvar planes []Plane\n\tfor _, plane := range inputPlanes {\n\t\tplanes = append(planes, plane)\n\t}\n\treturn Raid{Planes: planes}, nil\n}", "func NewClassifierFromFile(path string) (Classifier, error) {\n\tclassifier := Classifier{}\n\n\tfl, err := os.Open(path)\n\tif err != nil {\n\t\treturn classifier, err\n\t}\n\tdefer fl.Close()\n\n\terr = gob.NewDecoder(fl).Decode(&classifier)\n\tif err != nil {\n\t\treturn classifier, err\n\t}\n\n\treturn classifier, err\n}", "func NewClassifierWithConfig(graphPath, labelPath string,\n\tconfig Config) (*Classifier, error) {\n\t// Read the passed inception model file\n\tbytes, err := ioutil.ReadFile(graphPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Populate a new graph using the read model\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(bytes, \"\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new execution session using the graph\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read all labels in the passed labelPath\n\tlabels, err := readLabels(labelPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Return a fully populated Classifier\n\treturn &Classifier{config: config, graph: graph, session: session,\n\t\tlabels: labels}, nil\n}", "func NewRBAC(config *RBACConfig) (rbac *RBAC, err error) {\n\tr := cache.NewRedis(config.Redis)\n\td, err := db.Init(config.Mgo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trbac = &RBAC{\n\t\tCache: cache.NewPermissionDao(r, d),\n\t\tPermission: db.NewPermissionDao(d),\n\t\tRole: db.NewRoleDao(d),\n\t\tUser: db.NewUserDao(d),\n\t}\n\treturn\n}", "func NewSerial() Tree {\n\tt := new(serial)\n\tt.Clear()\n\treturn t\n}", "func NewCaretaker() *Caretaker {\n\treturn &Caretaker{o: NewOriginator()}\n}", "func New(conf *Config) Rclone {\n\treturn Rclone{config: conf}\n}", "func New(value interface{}, comparator comparator.Less) *RBTree {\n\treturn &RBTree{value: value, less: comparator, color: \"black\"}\n}", "func (clf *ClfDef) getModel(stream chan base.TextDatapoint) *text.NaiveBayes {\n\tclassCount := uint8(len(clf.Labels))\n\tif clf.Typ == \"only_words_and_numbers\" {\n\t\t// OnlyWordsAndNumbers is a transform function that will only let 0-1a-zA-Z, and spaces through\n\t\t// https://godoc.org/github.com/cdipaolo/goml/base#OnlyWordsAndNumbers\n\t\treturn text.NewNaiveBayes(stream, classCount, base.OnlyWordsAndNumbers)\n\t}\n\t// OnlyWords is a transform function that will only let a-zA-Z, and spaces through\n\t// https://godoc.org/github.com/cdipaolo/goml/base#OnlyWords\n\treturn text.NewNaiveBayes(stream, classCount, base.OnlyWords)\n\n}", "func NewRbac(c *restclient.Config) (*RbacClient, error) {\n\tconfig := *c\n\tif err := setGroupDefaults(rbac.GroupName, &config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RbacClient{client}, nil\n}", "func NewRobo(pitches []mlpapi.Pitch, rules []mlpapi.Rule) (robo *RoboRooney) {\n\trobo = &RoboRooney{}\n\trobo.cred = readCredentials()\n\n\trobo.mlpClient = mlpapi.New()\n\trobo.tracker = NewTracker()\n\trobo.ticker = time.NewTicker(time.Minute * time.Duration(robo.cred.TickerInterval))\n\n\tif len(pitches) == 0 {\n\t\tlog.Fatal(\"Need atleast one pitch to check\")\n\t}\n\n\trobo.pitches = pitches\n\trobo.rules = rules\n\n\treturn robo\n}", "func New() *Tapa {\n\tvar t Tapa\n\tt.concurrency = 2\n\tt.rand = rand.New(rand.NewSource(time.Now().UnixNano()))\n\tt.WithClient(http.DefaultClient)\n\n\treturn &t\n}", "func NewSerialTCA(sio *deej.SerialIO, siu *SerialInUse, logger *zap.SugaredLogger) (*SerialTCA, error) {\n\tsdlogger := logger.Named(\"TCA9548A\")\n\tserTCA := &SerialTCA{\n\t\tsio: sio,\n\t\tsiu: siu,\n\t\tlogger: sdlogger,\n\t}\n\treturn serTCA, nil\n}", "func NewRadar(history int, fetch RadarImage) *Radar {\n\tq, err := queue.NewQueue(history)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tr := Radar{\n\t\tsync.Mutex{},\n\t\tq,\n\t\tnil,\n\t\tfalse,\n\t\tmake(chan struct{}),\n\t\tfetch,\n\t}\n\n\tr.populate()\n\treturn &r\n}", "func FromRNA(s string) ([]string, error) {\n\tvar proteins []string\n\tbases := []rune(s)\n\tfor i := 0; i < len(bases); i += 3 {\n\t\tp, err := FromCodon(string(bases[i : i+3]))\n\t\tswitch err {\n\t\tcase ErrStop:\n\t\t\treturn proteins, nil\n\t\tcase ErrInvalidBase:\n\t\t\treturn proteins, err\n\t\tdefault:\n\t\t\tproteins = append(proteins, p)\n\t\t}\n\t}\n\treturn proteins, nil\n}", "func NewTrainedModelAssignment() *TrainedModelAssignment {\n\tr := &TrainedModelAssignment{\n\t\tRoutingTable: make(map[string]TrainedModelAssignmentRoutingTable, 0),\n\t}\n\n\treturn r\n}", "func ToRNA(dna string) string {\n\tbyteDna := []byte(dna)\n\tfor i := 0; i < len(byteDna); i++ {\n\t\tswitch byteDna[i] {\n\t\tcase 'G':\n\t\t\tbyteDna[i] = 'C'\n\t\tcase 'C':\n\t\t\tbyteDna[i] = 'G'\n\t\tcase 'T':\n\t\t\tbyteDna[i] = 'A'\n\t\tcase 'A':\n\t\t\tbyteDna[i] = 'U'\n\t\t}\n\t}\n\treturn string(byteDna)\n}", "func NewBarrier(seqs ...Sequencer) Barrier {\n\tif len(seqs) == 0 {\n\t\tpanic(\"Barrier should contain at least one sequence\")\n\t}\n\n\toffsets := make([]uint32, 0, len(seqs))\n\tfor _, seq := range seqs {\n\t\toffsets = append(offsets, seq.offset)\n\t}\n\treturn Barrier{\n\t\toffsets: offsets,\n\t}\n}", "func New() *Nitro {\n\treturn NewWithConfig(DefaultConfig())\n}", "func NewClassifierFromFile(name string) (c *Classifier, err error) {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %q: %w\", name, err)\n\t}\n\tdefer file.Close()\n\n\treturn NewClassifierFromReader(file)\n}", "func NewNGram(n int, tokens []string, class string) nGram {\n\treturn nGram{n, tokens, genhash(tokens), map[string]int{class: 1}}\n}", "func NewCarol(t *testing.T, setup RoleSetup) *Carol {\n\tt.Helper()\n\treturn &Carol{\n\t\tResponder: *NewResponder(t, setup, malloryCarolNumStages),\n\t\tregistered: make(chan *channel.RegisteredEvent),\n\t}\n}", "func FromRNA(rna string) ([]string, error) {\n\tvar proteins = make([]string, 0, len(rna)/3)\n\n\tfor i := 0; i < len(rna); i += 3 {\n\t\tprotein, err := FromCodon(rna[i : i+3])\n\t\tif err == ErrStop {\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn proteins, err\n\t\t}\n\n\t\tproteins = append(proteins, protein)\n\t}\n\n\treturn proteins, nil\n}", "func FromRNA(rna string) (protein, error) {\n\tprotein := make([]aminoAcid, 0, len(rna)/3)\n\tbuf := make([]byte, 3)\n\tr := strings.NewReader(rna)\n\tfor {\n\t\t_, err := io.ReadFull(r, buf)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn protein, nil\n\t\t\t}\n\t\t\treturn protein, err\n\t\t}\n\t\tacid, err := FromCodon(string(buf))\n\t\tif err != nil {\n\t\t\tif err == ErrStop {\n\t\t\t\treturn protein, nil\n\t\t\t}\n\t\t\treturn protein, err\n\t\t}\n\t\tprotein = append(protein, acid)\n\t}\n}", "func NewRBNode(value int) *RBNode {\n\treturn &RBNode{color: Red, value: value}\n}", "func NewTokenizer(r io.Reader) (*Tokenizer, error) {\n\tinput := bufio.NewReader(r)\n\tclassifier := NewDefaultClassifier()\n\ttokenizer := &Tokenizer{\n\t\tinput: input,\n\t\tclassifier: classifier}\n\treturn tokenizer, nil\n}", "func CreateNewClass(c *gin.Context) {\n\n\t// // Initialize database connection\n\tdb := config.DatabaseConn()\n\n\t// Declare parameters\n\tIDClassroom := uuid.Must(uuid.NewV4())\n\tUUIDClassroom := uuid.Must(uuid.NewV4())\n\tClassroomName := c.Param(\"ClassroomName\")\n\tClassroomTime := c.Param(\"ClassroomTime\")\n\tRoom := c.Param(\"Room\")\n\tUUIDParticipants := c.Param(\"UUIDParticipants\")\n\n\t// Bind in one parameters\n\tcreateClassroomPayload := model.Classroom{\n\t\tIDClassroom: IDClassroom,\n\t\tUUIDClassroom: UUIDClassroom,\n\t\tClassroomName: ClassroomName,\n\t\tClassroomTime: ClassroomTime,\n\t\tRoom: Room,\n\t\tUUIDParticipants: UUIDParticipants}\n\n\t// Bind parameter as JSON Parameters\n\tc.BindJSON(&createClassroomPayload)\n\n\t// Save in database\n\tdb.Save(&createClassroomPayload)\n\n\tc.JSON(http.StatusOK, gin.H{\"message\": \"Inserted successfully\"})\n}", "func newBuildPipeline(t gaia.PipelineType) BuildPipeline {\n\tvar bP BuildPipeline\n\n\t// Create build pipeline for given pipeline type\n\tswitch t {\n\tcase gaia.PTypeGolang:\n\t\tbP = &BuildPipelineGolang{\n\t\t\tType: t,\n\t\t}\n\tcase gaia.PTypeJava:\n\t\tbP = &BuildPipelineJava{\n\t\t\tType: t,\n\t\t}\n\tcase gaia.PTypePython:\n\t\tbP = &BuildPipelinePython{\n\t\t\tType: t,\n\t\t}\n\tcase gaia.PTypeCpp:\n\t\tbP = &BuildPipelineCpp{\n\t\t\tType: t,\n\t\t}\n\tcase gaia.PTypeRuby:\n\t\tbP = &BuildPipelineRuby{\n\t\t\tType: t,\n\t\t}\n\tcase gaia.PTypeNodeJS:\n\t\tbP = &BuildPipelineNodeJS{\n\t\t\tType: t,\n\t\t}\n\t}\n\n\treturn bP\n}", "func NewSequenceValidator() ResourceValidator {\n\treturn &sequenceValidator{}\n}", "func NewRTU(slaveid byte) (*RTU, error) {\n\trtu := &RTU{}\n\trtu.SlaveId = slaveid\n\treturn rtu, nil\n}", "func (c RecommenderFactory) Make() Recommender {\n\trecommender := &recommender{\n\t\tclusterState: c.ClusterState,\n\t\tclusterStateFeeder: c.ClusterStateFeeder,\n\t\tcheckpointWriter: c.CheckpointWriter,\n\t\tcheckpointsGCInterval: c.CheckpointsGCInterval,\n\t\tcontrollerFetcher: c.ControllerFetcher,\n\t\tuseCheckpoints: c.UseCheckpoints,\n\t\tvpaClient: c.VpaClient,\n\t\tpodResourceRecommender: c.PodResourceRecommender,\n\t\trecommendationPostProcessor: c.RecommendationPostProcessors,\n\t\tlastAggregateContainerStateGC: time.Now(),\n\t\tlastCheckpointGC: time.Now(),\n\t}\n\tklog.V(3).Infof(\"New Recommender created %+v\", recommender)\n\treturn recommender\n}", "func ToRNA(dna string) string {\n\n\trna := \"\"\n\tfor _, c := range strings.Split(dna, \"\") {\n\n\t\tif c == \"G\" {\n\t\t\trna += \"C\"\n\t\t} else if c == \"C\" {\n\t\t\trna += \"G\"\n\t\t} else if c == \"T\" {\n\t\t\trna += \"A\"\n\t\t} else if c == \"A\" {\n\t\t\trna += \"U\"\n\t\t} else {\n\t\t\trna += c\n\t\t}\n\t}\n\n\treturn rna\n}", "func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tdropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tnumLabels := int64(len(config.(*bert.BertConfig).Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\ttc.roberta = roberta\n\ttc.dropout = dropout\n\ttc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewRPCCtx(embed Ctx) *RPCCtx {\n\tret := &RPCCtx{\n\t\tembed: embed,\n\t\tServices: finder.New(),\n\t\tLog: &ggt.VoidLog{},\n\t\tSession: &ggt.VoidSession{},\n\t\tUpload: &ggt.FileProvider{},\n\t}\n\tret.Log.Handle(nil, nil, nil, \"constructor\", \"RPCCtx\")\n\treturn ret\n}", "func newMaxentClassifier(\n\tweights []float64,\n\tmapping map[string]int,\n\tlabels []string) *binaryMaxentClassifier {\n\n\tset := mapset.NewSet()\n\tfor label := range mapping {\n\t\tset.Add(strings.Split(label, \"-\")[0])\n\t}\n\n\treturn &binaryMaxentClassifier{\n\t\tset.Cardinality() + 1,\n\t\tlabels,\n\t\tmapping,\n\t\tweights}\n}", "func NewRoundRobin[T any](things ...T) (LoadBalance[T], any) {\n\tif len(things) == 0 {\n\t\treturn nil, ErrNoArguments\n\t}\n\treturn &roundRobin[T]{things: things, next: 0}, nil\n}", "func NewTraining(bias float64, findC bool, cSpecified bool, solverSpecified bool, crossValidation bool, inputFile string, outputFile string, nrFold int, param *Parameter, problem *Problem) *Training {\n\treturn &Training{Bias: bias, FindC: findC, CSpecified: cSpecified, SolverSpecified: solverSpecified, CrossValidation: crossValidation, InputFilename: inputFile, ModelFilename: outputFile, NrFold: nrFold, Param: param, Prob: problem}\n}", "func New(info interface{}, table FeatureSlice, p []byte) BasicSequence {\n\treturn BasicSequence{info, table, p}\n}", "func (rm *ReceiptMaker) NewReceipt() types.MessageReceipt {\n\tseq := rm.seq\n\trm.seq++\n\treturn types.MessageReceipt{\n\t\tReturn: []byte(fmt.Sprintf(\"%d\", seq)),\n\t}\n}", "func NewRulerBuilder(e e2e.Environment, name string) *RulerBuilder {\n\tf := e.Runnable(fmt.Sprintf(\"rule-%s\", name)).\n\t\tWithPorts(map[string]int{\"http\": 8080, \"grpc\": 9091}).\n\t\tFuture()\n\treturn &RulerBuilder{\n\t\treplicaLabel: name,\n\t\tLinkable: f,\n\t\tf: f,\n\t\timage: DefaultImage(),\n\t}\n}", "func newProtobufFieldSequence(serialized bool) *protobufFieldSequence {\n\tif serialized {\n\t\treturn &protobufFieldSequence{\n\t\t\tgenericProtobufField: newGenericProtobufField(serializedSequenceOfFields),\n\t\t}\n\t}\n\treturn &protobufFieldSequence{\n\t\tgenericProtobufField: newGenericProtobufField(sequenceOfFields),\n\t}\n}", "func (t *MCTS) New(move int32, score float32) (retVal Naughty) {\n\tn := t.alloc()\n\tN := t.nodeFromNaughty(n)\n\tN.lock.Lock()\n\tdefer N.lock.Unlock()\n\tN.move = move\n\tN.visits = 1\n\tN.status = uint32(Active)\n\tN.qsa = 0\n\tN.psa = score\n\n\treturn n\n}", "func NewRBTree(less, more, equal func(a, b interface{}) bool) *RBTree {\n\trb := new(RBTree)\n\trb.root = nil\n\trb.size = 0\n\trb.less = less\n\trb.more = more\n\trb.equal = equal\n\treturn rb\n}", "func FromRNA(input string) ([]string, error) {\n\tvar output []string\n\tfor i := 0; i < len(input); i += 3 {\n\t\tc, err := FromCodon(input[i : i+3])\n\t\tif err != nil {\n\t\t\tif err == ErrStop {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn output, err\n\t\t}\n\t\toutput = append(output, c)\n\t}\n\n\treturn output, nil\n}", "func New(config Config) (*Rigel, error) {\n\tif config.Redis.Addr == \"\" {\n\t\tconfig.Redis.Addr = \"localhost:6379\"\n\t}\n\n\tif config.Namespace == \"\" {\n\t\tconfig.Namespace = \"rigel\"\n\t}\n\n\tif config.Concurrency == 0 {\n\t\tconfig.Concurrency = 1\n\t}\n\n\tif config.Hostname == \"\" {\n\t\tconfig.Hostname, _ = os.Hostname()\n\t}\n\n\topts := redis.Options(config.Redis)\n\tclient := redis.NewClient(&opts)\n\tif err := client.Ping().Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Rigel{\n\t\tredis: client,\n\t\tnamespace: config.Namespace,\n\t\thostname: config.Hostname,\n\t\thandlers: make(map[string]Handler),\n\t\tqueues: make(map[string]bool),\n\t\tconcurrency: config.Concurrency,\n\t\tquit: make(chan struct{}),\n\t}, nil\n}", "func FromRNA(rna string) ([]string, error) {\n\tvar proteins []string\n\trunes := []rune(rna)\n\tfor i := 0; i < len(runes); i = i + 3 {\n\t\tcodon := string(runes[i : i+3])\n\t\tprotein, err := FromCodon(codon)\n\t\tif err != nil && err == ErrStop {\n\t\t\treturn proteins, nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn proteins, err\n\t\t}\n\t\tproteins = append(proteins, protein)\n\t}\n\treturn proteins, nil\n}", "func NewClassificationsController(service *goa.Service, fm Fmodeler) *ClassificationsController {\n\treturn &ClassificationsController{\n\t\tController: service.NewController(\"ClassificationsController\"),\n\t\tfm: fm,\n\t}\n}", "func (KNN *KNNRegressor) New(name string, labels []float64, numbers []float64, x int, y int) {\n\n\tKNN.Data = *mat.MakeDenseMatrix(numbers, x, y)\n\tKNN.Name = name\n\tKNN.Labels = labels\n}", "func FromRNA(rna string) ([]string, error) {\n\tvar res []string\n\tvar b strings.Builder\n\tc := 0\n\tfor _, nucleotide := range rna {\n\t\tb.WriteRune(nucleotide)\n\t\tif c++; c == 3 {\n\t\t\tprotein, err := FromCodon(b.String())\n\t\t\tif err == nil {\n\t\t\t\tres = append(res, protein)\n\t\t\t} else if err == ErrStop {\n\t\t\t\treturn res, nil\n\t\t\t} else {\n\t\t\t\treturn res, ErrInvalidBase\n\t\t\t}\n\t\t\tb.Reset()\n\t\t\tc = 0\n\t\t}\n\t}\n\treturn res, nil\n}", "func (*scheduleSubjectR) NewStruct() *scheduleSubjectR {\n\treturn &scheduleSubjectR{}\n}" ]
[ "0.63030326", "0.6088201", "0.5573898", "0.5011184", "0.48697948", "0.48697948", "0.47858444", "0.47579253", "0.47444493", "0.46542457", "0.46195018", "0.4588383", "0.4547116", "0.4539084", "0.45093924", "0.44767594", "0.4411735", "0.43808696", "0.42963836", "0.4287047", "0.42863014", "0.42695495", "0.4265118", "0.4238272", "0.42344508", "0.4219336", "0.420797", "0.4190093", "0.4168892", "0.41459772", "0.41350996", "0.41181162", "0.41146305", "0.41126382", "0.4112386", "0.4110996", "0.41039887", "0.41032922", "0.4094645", "0.4093241", "0.40886432", "0.40587914", "0.40582255", "0.40546983", "0.4052893", "0.40364024", "0.4031786", "0.40147275", "0.4009007", "0.40035594", "0.39910585", "0.39875996", "0.39860123", "0.39822283", "0.39778328", "0.39528883", "0.3947042", "0.3937968", "0.39369524", "0.39277816", "0.3924029", "0.3916118", "0.39130995", "0.39118344", "0.39100093", "0.3908612", "0.39004534", "0.3890967", "0.38881737", "0.38877803", "0.38872898", "0.38846433", "0.3884623", "0.38829178", "0.3865446", "0.38544747", "0.3852885", "0.38527972", "0.38420236", "0.3832538", "0.38321438", "0.3827081", "0.38263303", "0.38231146", "0.38202178", "0.38189057", "0.3818714", "0.38178247", "0.3807414", "0.3800062", "0.3796677", "0.37943298", "0.37931216", "0.3790456", "0.37884134", "0.37835187", "0.37767735", "0.37659115", "0.37655756", "0.3764425" ]
0.78834176
0
Load loads model from file or model name. It also updates default configuration parameters if provided. This method implements `PretrainedModel` interface.
func (sc *RobertaForSequenceClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error { var urlOrFilename string // If modelName, infer to default configuration filename: if modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok { urlOrFilename = modelFile } else { // Otherwise, just take the input urlOrFilename = modelNameOrPath } cachedFile, err := util.CachedPath(urlOrFilename) if err != nil { return err } vs := nn.NewVarStore(device) p := vs.Root() sc.roberta = bert.NewBertModel(p.Sub("roberta"), config.(*bert.BertConfig)) sc.classifier = NewRobertaClassificationHead(p.Sub("classifier"), config.(*bert.BertConfig)) err = vs.Load(cachedFile) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load(fileName string, src interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tdecoder := gob.NewDecoder(file)\n\t\tif err = decoder.Decode(src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Restore parameters\n\tswitch src.(type) {\n\tcase Model:\n\t\tmodel := src.(Model)\n\t\tmodel.SetParams(model.GetParams())\n\tdefault:\n\t\treturn errors.New(\"the file is not a model dump\")\n\t}\n\treturn nil\n}", "func (mlm *RobertaForMaskedLM) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmlm.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmlm.lmHead = NewRobertaLMHead(p.Sub(\"lm_head\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mc *RobertaForMultipleChoice) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmc.dropout = util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, 1, nn.DefaultLinearConfig())\n\tmc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Model) Load(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\tif err := json.Unmarshal(data, m); err != nil {\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\treturn nil\n}", "func Load(modelArchive string, framework Framework, flags ModelFlags) (*Model, error) {\n\tf, _ := os.Open(modelArchive)\n\tdefer f.Close()\n\tvar outDir string\n\tif fi, err := f.Stat(); err == nil && fi.IsDir() {\n\t\toutDir = modelArchive\n\t} else if err == nil && !fi.IsDir() {\n\t\ttmpDir := os.TempDir()\n\t\toutDir = filepath.Join(tmpDir, utils.PseudoUuid())\n\t\tif err := utils.Unzip(modelArchive, outDir); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to extract model archive: %v\", err)\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s does not exist\", modelArchive)\n\t}\n\n\tmodelFilename := filepath.Join(outDir, \"saved_model.pb\")\n\tif _, err := os.Stat(modelFilename); err != nil {\n\t\t// This if is here for when we can read pbtxt files\n\t\tif _, err2 := os.Stat(modelFilename + \"txt\"); err2 == nil {\n\t\t\tmodelFilename = modelFilename + \"txt\"\n\t\t\treturn nil, errors.New(\"Currently loading saved_model.pbtxt is not supported\")\n\t\t\t//comment the return when we can read pbtxt\n\t\t} else {\n\t\t\treturn nil, errors.New(\"saved_model.pb does not exist\")\n\t\t}\n\t}\n\n\tflags.ModelPath = outDir\n\tflags.ModelFile = modelFilename\n\tvar model Model\n\terr := framework.Load(&model, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &model, nil\n}", "func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tdropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tnumLabels := int64(len(config.(*bert.BertConfig).Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\ttc.roberta = roberta\n\ttc.dropout = dropout\n\ttc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (am *AssetManager) LoadModel(name, iname string) {\n\tif strings.Contains(name, \".obj\") {\n\t\tam.Models[iname] = NewWavefrontModelFromFile(am.modelsDir + name)\n\t} else {\n\t\tlog.Fatal(\"cannot find \" + name)\n\t}\n}", "func (qa *RobertaForQuestionAnswering) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\tqa.roberta = roberta\n\tqa.qaOutputs = qaOutputs\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(model interface{}, provider Provider, strict bool) error {\n\treturn load(model, provider, strict)\n}", "func LoadModel(r io.Reader) (Model, error) {\n\tdec := json.NewDecoder(r)\n\tvar m Model\n\tif err := dec.Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\tm.setWeightVec()\n\treturn m, nil\n}", "func Load(modelName string) (r *pb.TextResponse, err error) {\n\tif modelName == \"\" {\n\t\tmodelName = defaultModel\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tr, err = grpcClient.LoadModel(ctx, &pb.TextRequest{Text: modelName})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}", "func (s *DataStore) Load() error {\n\tfile, err := os.Open(s.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = json.NewDecoder(file).Decode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadModelFile(path string) (Model, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fp.Close()\n\treturn LoadModel(fp)\n}", "func Load(filename string) (*SvmModel, error) {\n\n\tcfn := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cfn))\n\n\tmdl := C.svm_load_model(cfn)\n\tif mdl == nil {\n\t\treturn nil, SvmError{Message: fmt.Sprintf(\"unable to load model file: %s\", filename)}\n\t}\n\n\treturn &SvmModel{object: mdl}, nil\n}", "func (wrapper *TvmWrapper) LoadModel(modelParam *ModelParam) (*moduleInfo, error) {\n\tdefer runtime.GC()\n\n\t// debug model parameters\n\tfmt.Print(modelParam.DebugStr())\n\n\t// load module library\n\tfmt.Print(\"start to load module library...\\n\")\n\tmodLibP, err := gotvm.LoadModuleFromFile(modelParam.ModelLibPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// read module json file\n\tfmt.Print(\"start to read module json file...\\n\")\n\tbytes, err := ioutil.ReadFile(modelParam.ModelJSONPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tmodJsonStr := string(bytes)\n\n\t// create graph module of tvm\n\tfmt.Print(\"start to create graph module of tvm...\\n\")\n\tfuncp, err := gotvm.GetGlobalFunction(\"tvm.graph_runtime.create\")\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t\treturn nil, err\n\t}\n\t// graph_runtime.create\n\t// arg[0] : model json text\n\t// arg[1] : model library\n\t// arg[2] : device type (ex. KDLCPU, KDLGPU...)\n\t// arg[3] : device id\n\tgraphrt, err := funcp.Invoke(modJsonStr, modLibP, wrapper.config.DeviceType, (int64)(0))\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tgraphmod := graphrt.AsModule()\n\n\t// import params to graph module\n\tfmt.Print(\"start to import params to graph module...\\n\")\n\tbytes, err = ioutil.ReadFile(modelParam.ModelParamsPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tfuncp, err = graphmod.GetFunction(\"load_params\")\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\t_, err = funcp.Invoke(bytes)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// create module information\n\tfmt.Print(\"start to create module information...\\n\")\n\tinfo := newModuleInfo(graphmod, modelParam.InputShape, modelParam.OutputShape)\n\treturn info, nil\n}", "func loadModel(modelName string) (multilayer.MultiLayerPerceptron, error) {\n\tf, err := os.Open(\"models/\" + modelName + \".model.gob\")\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, fmt.Errorf(\"failed opening model: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\n\tnn := multilayer.MultiLayerPerceptron{}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\terr = nn.UnmarshalBinary(data)\n\treturn nn, err\n}", "func (t *TOMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif t.Reader != nil {\n\t\tr = t.Reader\n\t} else if t.Path != \"\" {\n\t\tfile, err := getConfig(t.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tif _, err := toml.DecodeReader(r, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (env *Environment) LoadExistingModel(m string) *text.NaiveBayes {\n\t// get the classifier definition to make sure it is well defined\n\tclf := env.GetClassifierDefinition(m)\n\tclf.panicErrors()\n\n\tstreamChan := make(chan base.TextDatapoint, clf.TextChannelSize)\n\tmodel := clf.getModel(streamChan)\n\terr := model.RestoreFromFile(env.baseModelPath(clf.ModelOut))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn model\n}", "func Load(fileName string) (*openapi3.Swagger, error) {\n\tmodel, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = model.Validate(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"Loaded OpenAPI 3 Specification file:\", fileName)\n\treturn model, nil\n}", "func Load(r io.Reader) error {\n\treturn DefaultInstance.Load(r)\n}", "func (l *OptionalTOMLLoader) Load(s interface{}) error {\n\tif _, err := os.Stat(l.Path); err == nil {\n\t\treturn l.TOMLLoader.Load(s)\n\t}\n\treturn nil\n}", "func (e *CachedEnforcer) LoadModel() error {\n\tif e.autoClear {\n\t\tdefer e.InvalidateCache()\n\t}\n\treturn e.base.LoadModel()\n}", "func (c *IntentClassifier) Load(filePath string) error {\n\tlog.Printf(\"Loading Classifier from %s...\", filePath)\n\tmeta := persist.Load(filePath)\n\t//get the classifier current meta data\n\tname, version := c.getMeta()\n\tif meta.Name != name {\n\t\treturn fmt.Errorf(\"This file doesn't contain a KNearestNeighbors classifier\")\n\t}\n\tif meta.Version != version {\n\t\treturn fmt.Errorf(\"Can't understand this file format\")\n\t}\n\n\tdecoder := gob.NewDecoder(bytes.NewBuffer(meta.Data))\n\terr := decoder.Decode(&c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding RNN checkpoint file: %s\", err)\n\t}\n\n\tcheckpointFile = filePath\n\treturn nil\n}", "func (k *KMP) Load(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(b, k)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid load format, %s\", format)\n\t}\n\treturn err\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(filename string) (*Params, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar params Params\n\tif err := json.Unmarshal(file, &params); err != nil {\n\t\tlog.Printf(\"failed to parse %s: %s\", file, string(file))\n\t\treturn nil, err\n\t}\n\treturn &params, nil\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func (lm *LocalMeta) Load() error {\n\t// initialize gset\n\tvar err error\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, \"\")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfile, err := os.Open(lm.filename)\n\tif err != nil && !os.IsNotExist(errors.Cause(err)) {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif os.IsNotExist(errors.Cause(err)) {\n\t\treturn nil\n\t}\n\tdefer file.Close()\n\n\t_, err = toml.DecodeReader(file, lm)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, lm.BinlogGTID)\n\treturn errors.Trace(err)\n}", "func InitModel(modelDir string, modelFile string) *TfModel {\n\tmodelpath := filepath.Join(modelDir, modelFile)\n\tmodel, err := ioutil.ReadFile(modelpath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Construct an in-memory graph from the serialized form.\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toperations := graph.Operations()\n\tfor _, op := range operations {\n\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t}\n\t// Create a session for inference over graph.\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &TfModel{Model: &tf.SavedModel{Graph: graph, Session: session}}\n}", "func (e *Definition) Load(path, entity string) error {\n\n\tfullPath := filepath.Join(path, entity)\n\n\tb, err := ioutil.ReadFile(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontent := string(b)\n\te.json = jsonutil.NewFromString(content)\n\te.byteRead = 0\n\n\ts, err := schema.Read(e)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read schema: %s\", err)\n\t\treturn err\n\t}\n\n\te.schema = s\n\tv := validator.New(s)\n\te.validator = v\n\treturn nil\n}", "func Load(reader io.Reader, configuration interface{}) error {\n\tif err := FromYAML(reader, configuration); err != nil {\n\t\treturn err\n\t}\n\treturn FromEnv(configuration)\n}", "func Init(path string, tags []string) *TfModel {\n\tmodel, err := tf.LoadSavedModel(path, tags, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading Saved Model:%v\\n\", err.Error())\n\t\treturn nil\n\t}\n\toperations := model.Graph.Operations()\n\tfor _, op := range operations {\n\t\tname := op.Name()\n\t\tif strings.HasPrefix(name, \"sentence\") || strings.HasPrefix(name, \"dropout\") || strings.HasPrefix(name, \"inference\") {\n\t\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t\t}\n\t}\n\tlog.Println(\"op loading finished\")\n\treturn &TfModel{Model: model}\n}", "func Load(filename string, v interface{}) {\n\tParse(read(filename), v)\n}", "func (trm *TrmConfig) Load(pathTrm, pathVoice string) {\n\tfmt.Println(\"trm config load\")\n\ttrm.OpenJSON(pathTrm)\n\ttrm.OpenJSON(pathVoice)\n}", "func Load() error {\n\treturn def.Load()\n}", "func LoadModel(args ...interface{}) (*WordModel, error) {\n\tvar arg interface{}\n\tif len(args) == 0 {\n\t\targ = \"https://raw.githubusercontent.com/go-ego/gse/master/data/dict/dictionary.txt\"\n\t} else {\n\t\targ = args[0]\n\t}\n\n\tr, err := readerFromAnything(arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodel := NewWordModel()\n\n\tscanner := bufio.NewScanner(r)\n\tvar words []WordFreq\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, errors.New(\"Error: not enough fields\")\n\t\t}\n\t\tword := fields[0]\n\t\tfreq, _ := strconv.ParseFloat(fields[1], 32)\n\t\tif len([]rune(word)) < 2 {\n\t\t\t//freq = 2\n\t\t}\n\t\twords = append(words, WordFreq{\n\t\t\tWord: word,\n\t\t\tLogProbability: float32((freq)),\n\t\t})\n\t}\n\n\tsort.Slice(words, func(a, b int) bool {\n\t\treturn words[a].Word < words[b].Word\n\t})\n\n\tprev := \"\"\n\tfor _, word := range words {\n\t\tif word.Word == prev {\n\t\t\tcontinue\n\t\t}\n\t\tprev = word.Word\n\t\tmodel.AddWord(word.Word, word.LogProbability)\n\t}\n\n\tmodel.Finish()\n\n\treturn model, nil\n}", "func (self *LSHforest) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn msgpack.Unmarshal(b, self)\n}", "func Load() models.Language {\n\tif models.ConfigFile != \"\" {\n\t\tlangFile = models.ConfigFile\n\t} else {\n\t\tmodels.ConfigFile = langFile\n\t}\n\n\tlang := language.LoadLanguages(langFile)\n\treturn lang\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func Load(config interface{}, configPath string) error {\n\tswitch fileExtension(configPath) {\n\tcase \"yaml\":\n\t\treturn loadYaml(config, configPath)\n\tcase \"json\":\n\t\treturn loadJson(config, configPath)\n\tdefault:\n\t\treturn ero.Newf(\"Can not support load file %s\", configPath)\n\t}\n}", "func (lf LoaderFunc) Load(serverType string) (Input, error) {\n\treturn lf(serverType)\n}", "func Load(v interface{}, loadFrom string) error {\n\tcfg, err := ini.Load(loadFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.NameMapper = ini.TitleUnderscore\n\n\treturn cfg.MapTo(v)\n}", "func Load(filePath string, t Tomler) error {\n\ttomlValue := t.TOMLValue()\n\tvar err error\n\tif _, err = toml.DecodeFile(filePath, tomlValue); err != nil {\n\t\treturn err\n\t}\n\treturn t.FromTOML(tomlValue)\n}", "func (p *BaseProvider) Load() error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (b *baseLoader) Load(ctx context.Context, src *url.URL) (*Schema, error) {\n\t// open IO\n\tvar r io.ReadCloser\n\tswitch src.Scheme {\n\tcase \"file\":\n\t\tvar err error\n\t\tif r, err = os.Open(src.Path); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q from %q: %w\", src.Path, src, err)\n\t\t}\n\tcase \"http\", \"https\":\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, src.String(), nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create request for %q: %w\", src, err)\n\t\t}\n\t\tresp, err := b.client.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed requesting %q: %w\", src, err)\n\t\t}\n\t\tr = resp.Body\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme: %v\", src.Scheme)\n\t}\n\tdefer func() {\n\t\t_ = r.Close()\n\t}()\n\n\t// read and init schema\n\tvar s Schema\n\tif err := json.NewDecoder(r).Decode(&s); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding %q failed: %w\", src, err)\n\t}\n\tif s.ID == nil {\n\t\treturn nil, fmt.Errorf(\"no ID set on %q\", src)\n\t}\n\ts.calculateID()\n\ts.setSrc(src)\n\n\treturn &s, nil\n}", "func Load(path string) (*OBJFile, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\treturn Decode(in)\n}", "func (dto *GetAdapterModelResponse) Load(data base.ModelInterface) error {\n\tm, ok := data.(*model.AdapterModel)\n\tif !ok {\n\t\tlog.Error(\"GetAdapterModelResponse.Load() failed, convert interface failed.\")\n\t\treturn base.ErrorDataConvert\n\t}\n\tdto.GetResponse.Load(&m.Model)\n\tdto.Name = m.Name\n\tdto.Type = m.Type\n\tdto.Capability.Load(m.Capability)\n\treturn nil\n}", "func (l *Loader) LoadObjModel(file string) models.RawModel {\n\tdat, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvertices := make([]mgl32.Vec3, 0)\n\ttextures := make([]mgl32.Vec2, 0)\n\tnormals := make([]mgl32.Vec3, 0)\n\tvar verticesArray []float32\n\tvar texturesArray []float32\n\tvar normalsArray []float32\n\tindicesArray := make([]uint32, 0)\n\tlines := strings.Split(string(dat), \"\\n\")\n\tvar fStart int\n\tfor i, line := range lines {\n\t\tsplited := strings.Split(line, \" \")\n\t\tif len(splited) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := splited[0]\n\t\tif t == \"v\" {\n\t\t\tvertices = append(vertices, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vn\" {\n\t\t\tnormals = append(normals, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vt\" {\n\t\t\ttextures = append(textures, mgl32.Vec2{toFloat(splited[1]), toFloat(splited[2])})\n\t\t}\n\t\tif t == \"f\" {\n\t\t\tfStart = i\n\t\t\ttexturesArray = make([]float32, len(vertices)*2)\n\t\t\tnormalsArray = make([]float32, len(vertices)*3)\n\t\t\tverticesArray = make([]float32, len(vertices)*3)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor i := fStart; i < len(lines); i++ {\n\t\tsplited := strings.Split(lines[i], \" \")\n\t\tif len(splited) == 0 || splited[0] != \"f\" {\n\t\t\tbreak\n\t\t}\n\t\tvertex1 := strings.Split(splited[1], \"/\")\n\t\tvertex2 := strings.Split(splited[2], \"/\")\n\t\tvertex3 := strings.Split(splited[3], \"/\")\n\t\tindicesArray = processVertex(vertex1, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex2, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex3, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t}\n\tcolors := make([]float32, len(normalsArray))\n\tfor i := range colors {\n\t\tcolors[i] = 1\n\t}\n\treturn l.LoadToVAO(verticesArray, texturesArray, indicesArray, normalsArray, colors)\n}", "func (f *Flow) Load(cacheDir string) (err error) {\n\tif f.FlowFile == \"\" {\n\t\treturn nil\n\t}\n\tvar content []byte\n\tswitch getURLType(f.FlowFile) {\n\tcase \"local\":\n\t\tcontent, err = ioutil.ReadFile(f.FlowFile)\n\tcase \"web\":\n\t\tcontent, err = get(cacheDir, f.FlowFile)\n\t// TODO git - including the branch\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognised floe file type: <%s>\", f.FlowFile)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal into a flow\n\tnewFlow := &Flow{}\n\terr = yaml.Unmarshal(content, &newFlow)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up the flow, and copy bits into this flow\n\terr = newFlow.zero()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(newFlow.Name) != 0 {\n\t\tf.Name = newFlow.Name\n\t}\n\tf.ReuseSpace = newFlow.ReuseSpace\n\tif len(newFlow.HostTags) != 0 {\n\t\tf.HostTags = newFlow.HostTags\n\t}\n\tif len(newFlow.ResourceTags) != 0 {\n\t\tf.ResourceTags = newFlow.ResourceTags\n\t}\n\tif len(newFlow.Env) != 0 {\n\t\tf.Env = newFlow.Env\n\t}\n\tif len(newFlow.Tasks) != 0 {\n\t\tf.Tasks = newFlow.Tasks\n\t}\n\t// Pointless overriding triggers - as they are what caused this load\n\treturn nil\n}", "func (s *CommandLineSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.callback != nil {\n\t\treturn s.koanf.Load(posflag.ProviderWithFlag(s.flags, \".\", s.koanf, s.callback), nil)\n\t}\n\n\treturn s.koanf.Load(posflag.Provider(s.flags, \".\", s.koanf), nil)\n}", "func (s *YAMLFileSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.path == \"\" {\n\t\treturn errors.New(\"invalid yaml path source configuration\")\n\t}\n\n\treturn s.koanf.Load(file.Provider(s.path), yaml.Parser())\n}", "func Load(p string) (Spec, error) {\n\tvar spec Spec\n\n\tbuf, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to read file: %s - %w\", p, err)\n\t}\n\n\terr = yaml.Unmarshal(buf, &spec)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to parse spec: %s - %w\", p, err)\n\t}\n\n\tspec.Path = p\n\n\treturn spec, nil\n}", "func Load(config *Config) error {\n\treturn NewLoader(config).Load()\n}", "func Load(path string, target interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn load(formatter, data, target)\n}", "func Load(filepath string, config interface{}) error {\n\tmagazine := make(map[string]interface{})\n\tfileBytes, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := yaml.Unmarshal(fileBytes, &magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagazine = flatten(magazine)\n\tif err := applyEnv(magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagBytes, err := yaml.Marshal(bellows.Expand(magazine))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(magBytes, config)\n}", "func (m *SynapsesPersist) Load() {\n\tdataPath, err := filepath.Abs(m.relativePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teFile, err := os.Open(dataPath + m.file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer eFile.Close()\n\n\tbytes, err := ioutil.ReadAll(eFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(bytes, &m.Synapses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (defaultStorage) Load() error {\n\tpanic(noConfigStorage)\n}", "func (function *Function) Load() (err error) {\n\tdefinition, err := ioutil.ReadFile(function.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfunction.Definition = string(definition)\n\n\treturn\n}", "func Load(state *state.State, driverName string, name string, config map[string]string, logger logger.Logger, volIDFunc func(volType VolumeType, volName string) (int64, error), commonRulesFunc func() map[string]func(string) error) (Driver, error) {\n\t// Locate the driver loader.\n\tdriverFunc, ok := drivers[driverName]\n\tif !ok {\n\t\treturn nil, ErrUnknownDriver\n\t}\n\n\td := driverFunc()\n\terr := d.init(state, name, config, logger, volIDFunc, commonRulesFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (vm *BFVM) LoadFromString(source string) error {\n\treturn vm.LoadFromStream(strings.NewReader(source))\n}", "func (appConf *AppConf) Load(filename string, forceReload bool) (*AppConf, error){\n\t// appConf is load and force reload is false return direction\n\tif isLoad && !forceReload{\n\t\treturn appConf, nil\n\t}\n\tfilename, err := appConf.getEnvConfigPath(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = toml.DecodeFile(filename, appConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"使用配置文件: %s\", filename)\n\t// mark appConf as loaded\n\tisLoad = true\n\treturn appConf, nil\n}", "func (d *Datastore) Load() (Object, error) {\n\td.localLock.Lock()\n\tdefer d.localLock.Unlock()\n\n\t// clear Object first, as mapstructure's decoder doesn't have ZeroFields set to true for merging purposes\n\td.meta.Object = d.meta.Object[:0]\n\n\terr := d.kv.LoadConfig(d.meta)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = d.meta.unmarshall()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.meta.object, nil\n}", "func (ctx *AppContext) Load(env string) {\n\tlog.Println(\"Load app context\")\n\n\t// Load env specific config\n\tenvConfig := viper.Sub(env)\n\tctx.Env = env\n\tctx.ProjectID = envConfig.GetString(\"project_id\")\n\tctx.SuffixOfKind = envConfig.GetString(\"datastore.kind_suffix\")\n\tctx.EtcdServers = envConfig.GetStringSlice(\"etcd\")\n\n\t// Load common config\n\tctx.CommonConfig = viper.Sub(\"common\")\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tif err == nil {\n\t\tdecoder := json.NewDecoder(file)\n\t\terr = decoder.Decode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func Load() {\n\tvar err error\n\n\tconfLen := len(FilePath)\n\tif confLen != 0 {\n\t\terr = readFromJSON(FilePath)\n\t}\n\tif err == nil {\n\t\terr = readFromENV()\n\t}\n\tif err != nil {\n\t\tpanic(`Configuration not found. Please specify configuration`)\n\t}\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func TestDnn_LoadModel(t *testing.T) {\n\t//MODEL_PARAM=tmodel.pb,input_1,reshape_3/Reshape\n\tparam := os.Getenv(\"MODEL_PARAM\")\n\tif param == \"\" {\n\t\tt.Skip(\"Skipping model loading test; no MODEL_PARAM set\")\n\t\t//t.Error(\"no MODEL_PARAM set\")\n\t}\n\tstr2dnnfilter := func(inp string) VideoProfile {\n\t\tdnnfilter := VideoProfile{}\n\t\tstrs := strings.Split(inp, \",\")\n\t\tif len(strs) != 3 {\n\t\t\treturn dnnfilter\n\t\t}\n\t\tdnnfilter.Detector.ModelPath = strs[0]\n\t\tdnnfilter.Detector.Input = strs[1]\n\t\tdnnfilter.Detector.Output = strs[2]\n\t\treturn dnnfilter\n\t}\n\n\t_, dir := setupTest(t)\n\tdefer os.RemoveAll(dir)\n\n\tdnncfg := str2dnnfilter(param)\n\n\tif len(dnncfg.Detector.ModelPath) <= 0 || len(dnncfg.Detector.Input) <= 0 || len(dnncfg.Detector.Output) <= 0 {\n\t\tt.Errorf(\"invalid MODEL_PARAM set %v\", param)\n\t}\n\n\tdnnfilter := NewDnnFilter()\n\tdnnfilter.dnncfg = dnncfg\n\tif dnnfilter.InitDnnFilter(dnncfg) != true {\n\t\tt.Errorf(\"Can not load model file %v\", dnncfg.Detector.ModelPath)\n\t}\n\tdnnfilter.StopDnnFilter()\n}", "func (p *Puck) Load(name ...string) error {\n\tcmd := []byte(\"load();\\n\")\n\terr := p.command(name, cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *tomlLoader) Load(out interface{}) error {\n\tif _, err := toml.DecodeReader(l.r, out); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load(key string, data []byte) Entity {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tentity Entity\n\t)\n\n\tbuffer.Write(data)\n\tdecoder := gob.NewDecoder(&buffer)\n\tentityType := strings.Split(key, \".\")[0]\n\n\tswitch entityType {\n\tcase \"player\":\n\t\tentity = new(Player)\n\tcase \"planet\":\n\t\tentity = new(Planet)\n\tcase \"mission\":\n\t\tentity = new(Mission)\n\tcase \"sun\":\n\t\tentity = new(Sun)\n\tcase \"ss\":\n\t\tentity = new(SolarSlot)\n\tcase \"spy_report\":\n\t\tentity = new(SpyReport)\n\tdefault:\n\t\treturn nil\n\t}\n\tdecoder.Decode(entity)\n\treturn entity\n}", "func Load(r io.Reader, v interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSONLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\tif j.Reader != nil {\n\t\tr = j.Reader\n\t} else if j.Path != \"\" {\n\t\tfile, err := getConfig(j.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\treturn json.NewDecoder(r).Decode(s)\n}", "func (y *YAMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif y.Reader != nil {\n\t\tr = y.Reader\n\t} else if y.Path != \"\" {\n\t\tfile, err := getConfig(y.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(data, s)\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func (m *Method) TrainModel(c *gin.Context) {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(c.Request.Body)\n\tJSONStr := buf.String()\n\tm.GoPython(`ml.py`, JSONStr)\n\n\tvar response Response = Response{Status: `model training started`}\n\tc.JSON(http.StatusOK, response)\n}", "func (tfl tiltfileLoader) Load(ctx context.Context, tf *corev1alpha1.Tiltfile, prevResult *TiltfileLoadResult) TiltfileLoadResult {\n\tstart := time.Now()\n\tfilename := tf.Spec.Path\n\tabsFilename, err := ospath.RealAbs(tf.Spec.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn TiltfileLoadResult{\n\t\t\t\tConfigFiles: []string{filename},\n\t\t\t\tError: fmt.Errorf(\"No Tiltfile found at paths '%s'. Check out https://docs.tilt.dev/tutorial.html\", filename),\n\t\t\t}\n\t\t}\n\t\tabsFilename, _ = filepath.Abs(filename)\n\t\treturn TiltfileLoadResult{\n\t\t\tConfigFiles: []string{absFilename},\n\t\t\tError: err,\n\t\t}\n\t}\n\n\ttiltignorePath := watch.TiltignorePath(absFilename)\n\ttlr := TiltfileLoadResult{\n\t\tConfigFiles: []string{absFilename, tiltignorePath},\n\t}\n\n\ttiltignore, err := watch.ReadTiltignore(tiltignorePath)\n\n\t// missing tiltignore is fine, but a filesystem error is not\n\tif err != nil {\n\t\ttlr.Error = err\n\t\treturn tlr\n\t}\n\n\ttlr.Tiltignore = tiltignore\n\n\ts := newTiltfileState(ctx, tfl.dcCli, tfl.webHost, tfl.execer, tfl.k8sContextPlugin, tfl.versionPlugin,\n\t\ttfl.configPlugin, tfl.extensionPlugin, tfl.ciSettingsPlugin, feature.FromDefaults(tfl.fDefaults))\n\n\tmanifests, result, err := s.loadManifests(tf)\n\n\ttlr.BuiltinCalls = result.BuiltinCalls\n\ttlr.DefaultRegistry = s.defaultReg\n\n\t// All data models are loaded with GetState. We ignore the error if the state\n\t// isn't properly loaded. This is necessary for handling partial Tiltfile\n\t// execution correctly, where some state is correctly assembled but other\n\t// state is not (and should be assumed empty).\n\tws, _ := watch.GetState(result)\n\ttlr.WatchSettings = ws\n\n\t// NOTE(maia): if/when add secret settings that affect the engine, add them to tlr here\n\tss, _ := secretsettings.GetState(result)\n\ts.secretSettings = ss\n\n\tioState, _ := io.GetState(result)\n\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, ioState.Paths...)\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, s.postExecReadFiles...)\n\ttlr.ConfigFiles = sliceutils.DedupedAndSorted(tlr.ConfigFiles)\n\n\tdps, _ := dockerprune.GetState(result)\n\ttlr.DockerPruneSettings = dps\n\n\taSettings, _ := tiltfileanalytics.GetState(result)\n\ttlr.AnalyticsOpt = aSettings.Opt\n\n\ttlr.Secrets = s.extractSecrets()\n\ttlr.FeatureFlags = s.features.ToEnabled()\n\ttlr.Error = err\n\ttlr.Manifests = manifests\n\ttlr.TeamID = s.teamID\n\n\tobjectSet, _ := v1alpha1.GetState(result)\n\ttlr.ObjectSet = objectSet\n\n\tvs, _ := version.GetState(result)\n\ttlr.VersionSettings = vs\n\n\ttelemetrySettings, _ := telemetry.GetState(result)\n\ttlr.TelemetrySettings = telemetrySettings\n\n\tus, _ := updatesettings.GetState(result)\n\ttlr.UpdateSettings = us\n\n\tci, _ := cisettings.GetState(result)\n\ttlr.CISettings = ci\n\n\tconfigSettings, _ := config.GetState(result)\n\tif tlr.Error == nil {\n\t\ttlr.EnabledManifests, tlr.Error = configSettings.EnabledResources(tf, manifests)\n\t}\n\n\tduration := time.Since(start)\n\tif tlr.Error == nil {\n\t\ts.logger.Infof(\"Successfully loaded Tiltfile (%s)\", duration)\n\t}\n\textState, _ := tiltextension.GetState(result)\n\thashState, _ := hasher.GetState(result)\n\n\tvar prevHashes hasher.Hashes\n\tif prevResult != nil {\n\t\tprevHashes = prevResult.Hashes\n\t}\n\ttlr.Hashes = hashState.GetHashes()\n\n\ttfl.reportTiltfileLoaded(s.builtinCallCounts, s.builtinArgCounts, duration,\n\t\textState.ExtsLoaded, prevHashes, tlr.Hashes)\n\n\tif len(aSettings.CustomTagsToReport) > 0 {\n\t\treportCustomTags(tfl.analytics, aSettings.CustomTagsToReport)\n\t}\n\n\treturn tlr\n}", "func (k *Kluster) Load() error {\n\tif err := k.LoadSummary(); err != nil {\n\t\treturn err\n\t}\n\n\t// DEBUG:\n\t// fmt.Printf(\"DEBUG: cluster %s config version: %s\\tMin: %s\\tMax: %s\\n\", k.Name, k.Version, MinSemVersion, SemVersion)\n\n\tver, err := version.NewSemVer(k.Version)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"the cluster version (%s) is not well formed or not SemVer compliance. %s\", k.Version, err)\n\t}\n\tif ver.LT(MinSemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is not supported by this KubeKit, the minimun version supported is %s\", k.Version, MinVersion)\n\t}\n\tif ver.GT(SemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is greater than the cluster version supported by this KubeKit (%s)\", k.Version, Version)\n\t}\n\n\tk.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tname := k.Platform()\n\tconfig := k.Platforms[name]\n\n\tcred, err := k.GetCredentials()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tplatform, err := provisioner.NewPlatform(name, k.Name, config, cred, k.ui, k.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.provisioner[name] = platform\n\n\treturn nil\n}", "func (c *Info) Load() error {\n\tb, err := ioutil.ReadFile(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Lock()\n\terr = json.Unmarshal(b, c)\n\tc.Unlock()\n\n\treturn err\n}", "func Load(filename string) (*Beam, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treader := bufio.NewReader(f)\n\tdecoder := json.NewDecoder(reader)\n\tdecoder.DisallowUnknownFields()\n\tcfg := new(Beam)\n\t// This **Beam double-pointer appears to be required to detect an invalid\n\t// input of \"null\". See Test_Load/file_contains_null test.\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding JSON value in %v: %v\", filename, err)\n\t}\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"loading %v resulted in nil config\", filename)\n\t}\n\tif decoder.More() {\n\t\treturn nil, fmt.Errorf(\"found unexpected data after config in %v\", filename)\n\t}\n\treturn cfg, nil\n}", "func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}", "func (s *Startup) Load() error {\n\n\t// TODO: parameterize startup config file name\n\tjsonFile, err := ioutil.ReadFile(\"startup.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(jsonFile, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil // no error\n}", "func (component *Component) Load(filename string) error {\n\treturn util.LoadYAML(filename, component)\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func (s *EnvironmentSource) Load(_ *schema.StructValidator) (err error) {\n\tkeyMap, ignoredKeys := getEnvConfigMap(schema.Keys, s.prefix, s.delimiter)\n\n\treturn s.koanf.Load(env.ProviderWithValue(s.prefix, constDelimiter, koanfEnvironmentCallback(keyMap, ignoredKeys, s.prefix, s.delimiter)), nil)\n}", "func Load(filename string, data any, validation bool) error {\n\tisJSON := strings.HasSuffix(filename, \".json\")\n\n\tbs, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif validation {\n\t\terr := validate(bs, data, isJSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn unmarshal(bs, data, isJSON)\n}", "func Load(env string) *Configuration {\n\t_, filePath, _, _ := runtime.Caller(0)\n\tconfigName := \"config.\" + env + \".yaml\"\n\tconfigPath := filePath[:len(filePath)-9] + \"files\" + string(filepath.Separator)\n\n\tviper.SetConfigName(configName)\n\tviper.AddConfigPath(configPath)\n\tviper.SetConfigType(\"yaml\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Configuration\n\tviper.Unmarshal(&config)\n\tsetGinMode(config.Server.Mode)\n\n\treturn &config\n}", "func Load(path string) (*LevelDB, error) {\n\treturn LoadWithOptions(path, DefaultOptions)\n}", "func Load(name string, data interface{}) error {\n\tp := jsonPath(name)\n\t// Don't load anything if the file doesn't exist\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"File %s didn't exist, loading with fresh data\\n\", p)\n\t\treturn nil\n\t}\n\n\t// Read and unmarshal the json\n\tif b, err := ioutil.ReadFile(p); err != nil {\n\t\treturn err\n\t} else if len(b) == 0 {\n\t\tlog.Printf(\"File %s was empty, loading with fresh data\\n\", p)\n\t\treturn nil\n\t} else if err := json.Unmarshal(b, data); err != nil {\n\t\treturn fmt.Errorf(\"failed to load file %s error: %s\", p, err)\n\t}\n\n\tlog.Printf(\"Loaded %s\\n\", p)\n\treturn nil\n}", "func (rs *Restake) LoadProto(pbAct *iotextypes.StakeRestake) error {\n\tif pbAct == nil {\n\t\treturn ErrNilProto\n\t}\n\n\trs.bucketIndex = pbAct.GetBucketIndex()\n\trs.payload = pbAct.GetPayload()\n\trs.duration = pbAct.GetStakedDuration()\n\trs.autoStake = pbAct.GetAutoStake()\n\n\treturn nil\n}", "func (config *Config) Load() error {\n\tvar env string\n\tflag.StringVar(&env, \"env\", \"dev\", \"environment\")\n\n\tflag.Parse()\n\n\tviperRegistry := viper.New()\n\tviperRegistry.AddConfigPath(\"./config\")\n\tviperRegistry.SetConfigName(env)\n\tviperRegistry.SetConfigType(\"json\")\n\tviperRegistry.SetEnvPrefix(\"todo\")\n\tviperRegistry.AutomaticEnv()\n\n\tconfig.Env = env\n\n\tif err := viperRegistry.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureApplication(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureDB(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureAuth(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (wlt *Wallet) Load(dir string) error {\n\tr := &ReadableWallet{}\n\tif err := r.Load(filepath.Join(dir, wlt.GetFilename())); err != nil {\n\t\treturn err\n\t}\n\tr.Meta[\"filename\"] = wlt.GetFilename()\n\t*wlt = NewWalletFromReadable(r)\n\treturn nil\n}", "func Load(filepath string, startTag, endTag string, vars map[string]string) (result string, err error) {\n\tvar data []byte\n\tif data, err = ioutil.ReadFile(filepath); err == nil {\n\t\tvar tpl *Engine\n\t\tif tpl, err = New(string(data), startTag, endTag); err == nil {\n\t\t\tif result, err = tpl.Process(vars); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if err == errs.TmplVarsNotFoundError {\n\t\t\terr = nil\n\t\t\tresult = string(data)\n\t\t}\n\t}\n\treturn\n}", "func (l *Loader) Load(cfg *config.Config) {\n\tcfg.Address = os.Getenv(\"BRCEP_ADDRESS\")\n\tcfg.LogLevel = os.Getenv(\"BRCEP_LOG_LEVEL\")\n\tcfg.PreferredAPI = os.Getenv(\"BRCEP_PREFERRED_API\")\n\tcfg.ViaCepURL = os.Getenv(\"BRCEP_VIACEP_URL\")\n\tcfg.CepAbertoURL = os.Getenv(\"BRCEP_CEPABERTO_URL\")\n\tcfg.CepAbertoToken = os.Getenv(\"BRCEP_CEPABERTO_TOKEN\")\n\tcfg.CorreiosURL = os.Getenv(\"BRCEP_CORREIOS_URL\")\n}", "func Load(cfg interface{}, configPath string) error {\n\tif err := readConfigFile(configPath, cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ClusterState == nil {\n\t\tcfg.ClusterState = &ClusterState{}\n\t}\n\tif cfg.ALBIngressController == nil {\n\t\tcfg.ALBIngressController = &ALBIngressController{}\n\t}\n\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.ClusterState.UpTook != \"\" {\n\t\tcfg.ClusterState.upTook, err = time.ParseDuration(cfg.ClusterState.UpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif cfg.ALBIngressController.IngressUpTook != \"\" {\n\t\tcfg.ALBIngressController.ingressUpTook, err = time.ParseDuration(cfg.ALBIngressController.IngressUpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}" ]
[ "0.70846575", "0.6941715", "0.6930484", "0.67688364", "0.6714155", "0.6647504", "0.6631434", "0.65701777", "0.64257467", "0.63652515", "0.6344658", "0.620972", "0.6207725", "0.6139964", "0.61265564", "0.5930335", "0.59086376", "0.5823113", "0.5802144", "0.5792252", "0.5693667", "0.56829804", "0.56762475", "0.56285274", "0.5623558", "0.5518641", "0.5494872", "0.5493183", "0.54836494", "0.546983", "0.5464271", "0.5460658", "0.54480916", "0.54351294", "0.5430686", "0.5419393", "0.53909636", "0.5383543", "0.5377021", "0.5364359", "0.5361277", "0.5339527", "0.53096", "0.530837", "0.5251392", "0.5243386", "0.5243386", "0.52079505", "0.52001035", "0.5188874", "0.5187018", "0.5179063", "0.5175779", "0.51733714", "0.5173245", "0.51584876", "0.51530826", "0.5148211", "0.51422673", "0.51365185", "0.5134974", "0.5134226", "0.5117043", "0.5102523", "0.5100309", "0.50975543", "0.5094871", "0.508002", "0.50702477", "0.502236", "0.5017978", "0.50157046", "0.5014181", "0.50015056", "0.498564", "0.4970497", "0.49663433", "0.4960938", "0.4960261", "0.4956033", "0.494496", "0.4944538", "0.4931888", "0.4929976", "0.49245185", "0.4920092", "0.49166283", "0.49039724", "0.49017096", "0.48981398", "0.48963287", "0.4882128", "0.4874369", "0.48728004", "0.48691875", "0.48675567", "0.48662624", "0.48577738", "0.4844429", "0.48354807" ]
0.6917168
3
Forward forwards pass through the model.
func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) { hiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train) if err != nil { return ts.None, nil, nil, err } labels = sc.classifier.ForwardT(hiddenState, train) hiddenState.MustDrop() return labels, hiddenStates, attentions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Model) Forward(x *Node, states States) (rv *Node, err error) {\n\trv = x\n\tfor _, l := range m.Layers {\n\t\tif rv, err = l.Forward(rv, states); err != nil {\n\t\t\treturn nil, errors.Wrap(err, l.Name())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func (mod *backendModule) Forward(f *gatepb.Forward) error {\n\treturn mod.send(proto.Type(f.Typ), f)\n}", "func (m *Model) Forward(qkv attention.QKV) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: m.Key.Forward(qkv.Keys...),\n\t\tValues: m.Value.Forward(qkv.Values...),\n\t}\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (obj *Doc) Forward(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"Forward\", nil)\n\treturn err\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\th := nn.Affine(g, m.B, m.W, x)\n\tif yPrev != nil {\n\t\th = g.Add(h, g.Prod(m.WRec, yPrev))\n\t}\n\ts.Y = g.Invoke(m.Activation, h)\n\treturn\n}", "func (f *Forwarder) Forward(data *call.CallData) {\n\tf.transferAgents.Range(func(key interface{}, value interface{}) bool {\n\t\tstreamId := key.(userid.ID)\n\t\tstream := value.(TransferAgent)\n\t\tif streamId == userid.ID(data.UserId) { // Don't need to forward data back to sender\n\t\t\treturn true\n\t\t}\n\n\t\tif err := stream.Send(data); err != nil {\n\t\t\tf.logger.Error(err)\n\t\t}\n\n\t\treturn true\n\t})\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tg := m.Graph()\n\thalfSize := xs[0].Value().Size() / 2\n\n\tres := make([]ag.Node, len(xs))\n\tgate := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tres[i] = g.View(x, 0, 0, halfSize, 1)\n\t\tgate[i] = g.View(x, halfSize, 0, halfSize, 1)\n\t}\n\n\tgate = m.Norm.Forward(gate...)\n\tgate = m.Proj.Forward(gate...)\n\n\tif m.Act != nil {\n\t\tgate = m.Act.Forward(gate...)\n\t}\n\n\ty := make([]ag.Node, len(gate))\n\tfor i := range y {\n\t\ty[i] = g.Prod(gate[i], res[i])\n\t}\n\treturn y\n}", "func (ph *Handler) Forward() {\n\terr := recover()\n\tph.forward(err)\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tif p.RequiresFullSeq() {\n\t\treturn p.fullSeqForward(xs)\n\t}\n\treturn p.incrementalForward(xs)\n}", "func (m *Model) Forward(cache Cache, q, x []mat.Tensor) ([]mat.Tensor, []mat.Tensor, Cache) {\n\tvar pk, pv mat.Tensor\n\n\tpq := m.Query.Forward(q...)\n\n\tif hasCache := cache.HasValues(); hasCache && m.IsCrossAttention {\n\t\tpk = cache[0]\n\t\tpv = cache[1]\n\t} else {\n\t\tk := m.Key.Forward(x...)\n\t\tv := m.Value.Forward(x...)\n\n\t\tif hasCache {\n\t\t\tpk = ag.AppendRows(cache[0], k...)\n\t\t\tpv = ag.AppendRows(cache[1], v...)\n\t\t} else {\n\t\t\tpk = ag.Stack(k...)\n\t\t\tpv = ag.Stack(v...)\n\t\t}\n\t}\n\n\tresult, weights := attention.ScaledDotProductAttention(pq, pk, pv, m.ScaleFactor, m.UseCausalMask)\n\n\treturn result, weights, Cache{pk, pv}\n}", "func (inst *instance) Forward(port int) (string, error) {\n\tvar reply proxyrpc.ForwardResult\n\terr := inst.ProxyApp.Call(\n\t\t\"ProxyVM.Forward\",\n\t\tproxyrpc.ForwardParams{\n\t\t\tID: inst.ID,\n\t\t\tPort: port,\n\t\t},\n\t\t&reply)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reply.ManagerAddress, nil\n}", "func (l *AffineLayer) Forward(x mat.Matrix) mat.Matrix {\n\t_, c := x.Dims()\n\tif c != l.dimIn {\n\t\tpanic(fmt.Sprintf(\"expect %d but got %d\", l.dimIn, c))\n\t}\n\tl.x = x\n\tvar ret mat.Dense\n\tret.Mul(x, l.Weight)\n\tret.Apply(func(i, j int, val float64) float64 {\n\t\treturn l.Bias.At(j, 0) + val\n\t}, &ret)\n\treturn &ret\n}", "func (m *Model) StepForward(ns Nodes) (rv Nodes, err error) {\n\tstates := States{}\n\tvar tmp *Node\n\tfor _, x := range ns {\n\t\tif tmp, err = m.Forward(x, states); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trv = append(rv, tmp)\n\t}\n\treturn rv, nil\n}", "func (n *Network) Forward() {\n\tif !n.constructed() {\n\t\tlog.Panic(\"Cannot run an emtpy Network\")\n\t}\n\n\tfor l := range n.layers {\n\t\tcandy.Must(parallel.For(0, len(n.layers[l]), 1, func(g int) {\n\t\t\tgate := n.layers[l][g]\n\t\t\tgate.forward(gate)\n\t\t}))\n\t}\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func (b *RequiredArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) ArgumentNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func (q *CQPU) forward(predicate []*pbUtils.AttributePredicate, streamRec *pbQPU.ResponseStreamRecord, streamOut pbQPU.QPU_QueryServer, seqID *int64, respond bool) error {\n\tif respond {\n\t\terr := streamOut.Send(\n\t\t\tprotoutils.ResponseStreamRecord(\n\t\t\t\t*seqID,\n\t\t\t\tstreamRec.GetType(),\n\t\t\t\tstreamRec.GetLogOp(),\n\t\t\t))\n\t\t(*seqID)++\n\t\treturn err\n\t}\n\treturn nil\n}", "func (b *TestDriver) Forward(val int) error {\n\tlog.Printf(\"Forward: %d\", val)\n\n\treturn nil\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\ts.InG = g.Sigmoid(nn.Affine(g, m.BIn, m.WIn, x, m.WInRec, yPrev))\n\ts.ForG = g.Sigmoid(nn.Affine(g, m.BFor, m.WFor, x, m.WForRec, yPrev))\n\ts.Cand = g.Tanh(g.Mul(m.WCand, x))\n\ts.Y = g.Prod(s.InG, s.Cand)\n\tif yPrev != nil {\n\t\ts.Y = g.Add(s.Y, g.Prod(g.Tanh(yPrev), s.ForG))\n\t}\n\treturn\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (o *OutboundDispatcher) Forward(msg interface{}, des *service.Destination) error {\n\tfor _, v := range o.outboundTransports {\n\t\tif !v.AcceptRecipient(des.RecipientKeys) {\n\t\t\tif !v.Accept(des.ServiceEndpoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treq, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed marshal to bytes: %w\", err)\n\t\t}\n\n\t\t_, err = v.Send(req, des)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send msg using outbound transport: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no outbound transport found for serviceEndpoint: %s\", des.ServiceEndpoint)\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tys := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = m.forward(x)\n\t}\n\treturn ys\n}", "func (a *insertApp) forward(app *App, args ...interface{}) error {\n\tapp.State = \"pending\"\n\treturn db.Session.Apps().Insert(app)\n}", "func (lay *Layer) Forward(x *mat.Dense) (a *mat.Dense) {\n\t// x is (n x in )\n\trow, _ := x.Dims()\n\n\txx := new(mat.Dense)\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\tz.Apply(func(i, j int, v float64) float64 { return lay.act.f(v) }, z)\n\treturn z\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func (rt *Router) forward() {\n\tfor i, v := range rt.InInterfaceL {\n\t\t//pktS := \"\"\n\n\t\t// TRYE\n\t\t// get packet from interface i\n\t\tif pktS, err := v.Get(); err == nil {\n\t\t\t//fmt.Println(\"in routher forward, packet from Get(): \", pktS)\n\t\t\t// if packet exists make a forwarding decision\n\t\t\tp, err := FromByteS(pktS)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not get packet\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// HERE you will need to implement a lookup into the\n\t\t\t// forwarding table to find the appropriate outgoing interface\n\t\t\t// for now we assume the outgoing interface is also i\n\t\t\tfmt.Printf(\"%s: forwarding packet %s from interface %d to %d with mtu %d\\n\", rt.Str(), p.Str(), i, i, rt.OutInterfaceL[i].Mtu)\n\n\t\t\tif err = rt.OutInterfaceL[i].Put(p.ToByteS(), false); err != nil {\n\t\t\t\t//log.Printf(\"Could not put packet %s in router %s, into outInterface %d. Error: %s\", p.str, rt.forward, i, err)\n\t\t\t\tlog.Printf(\"%s: packet '%s' lost on interface %d\\n\", rt.Str(), i)\n\t\t\t}\n\t\t}\n\t\t//log.Println(\"no packet to forard in router\")\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (a *provisionApp) forward(app *App, args ...interface{}) error {\n\tvar units uint\n\tif len(args) > 0 {\n\t\tswitch args[0].(type) {\n\t\tcase int:\n\t\t\tunits = uint(args[0].(int))\n\t\tcase int64:\n\t\t\tunits = uint(args[0].(int64))\n\t\tcase uint:\n\t\t\tunits = args[0].(uint)\n\t\tcase uint64:\n\t\t\tunits = uint(args[0].(uint64))\n\t\tdefault:\n\t\t\tunits = 1\n\t\t}\n\t}\n\terr := Provisioner.Provision(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif units > 1 {\n\t\t_, err = Provisioner.AddUnits(app, units-1)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (req *RequestData) Forward(client *http.Client, config BasketConfig, basket string) (*http.Response, error) {\n\tforwardURL, err := url.ParseRequestURI(config.ForwardURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid forward URL: %s - %s\", config.ForwardURL, err)\n\t}\n\n\t// expand path\n\tif config.ExpandPath && len(req.Path) > len(basket)+1 {\n\t\tforwardURL.Path = expandURL(forwardURL.Path, req.Path, basket)\n\t}\n\n\t// append query\n\tif len(req.Query) > 0 {\n\t\tif len(forwardURL.RawQuery) > 0 {\n\t\t\tforwardURL.RawQuery += \"&\" + req.Query\n\t\t} else {\n\t\t\tforwardURL.RawQuery = req.Query\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(req.Method, forwardURL.String(), strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create forward request: %s\", err)\n\t}\n\n\t// copy headers\n\tfor header, vals := range req.Header {\n\t\tfor _, val := range vals {\n\t\t\tforwardReq.Header.Add(header, val)\n\t\t}\n\t}\n\t// headers cleanup\n\tforwardHeadersCleanup(forwardReq)\n\t// set do not forward header\n\tforwardReq.Header.Set(DoNotForwardHeader, \"1\")\n\n\t// forward request\n\tresponse, err := client.Do(forwardReq)\n\tif err != nil {\n\t\t// HTTP issue during forwarding - HTTP 502 Bad Gateway\n\t\tlog.Printf(\"[warn] failed to forward request for basket: %s - %s\", basket, err)\n\t\tbadGatewayResp := &http.Response{\n\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(\"Failed to forward request: %s\", err)))}\n\t\tbadGatewayResp.Header.Set(\"Content-Type\", \"text/plain\")\n\n\t\treturn badGatewayResp, nil\n\t}\n\n\treturn response, nil\n}", "func (m *Linear) Forward(x mat.Tensor) mat.Tensor {\n\treturn ag.Add(ag.Mul(m.W, x), m.B)\n}", "func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Ensure our request client does not follow redirects\n\thttpClient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tif config.TLS != nil {\n\t\ttlsConfig, err := config.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\ttracing.SetErrorAndDebugLog(r, \"Unable to configure TLS to call %s. Cause %s\", config.Address, err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(http.MethodGet, config.Address, http.NoBody)\n\ttracing.LogRequest(tracing.GetSpan(r), forwardReq)\n\tif err != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause %s\", config.Address, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteHeader(r, forwardReq, config.TrustForwardHeader)\n\n\ttracing.InjectRequestHeaders(forwardReq)\n\n\tforwardResponse, forwardErr := httpClient.Do(forwardReq)\n\tif forwardErr != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause: %s\", config.Address, forwardErr)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbody, readError := ioutil.ReadAll(forwardResponse.Body)\n\tif readError != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error reading body %s. Cause: %s\", config.Address, readError)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer forwardResponse.Body.Close()\n\n\t// Pass the forward response's body and selected headers if it\n\t// didn't return a response within the range of [200, 300).\n\tif forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {\n\t\tlog.Debugf(\"Remote error %s. StatusCode: %d\", config.Address, forwardResponse.StatusCode)\n\n\t\tutils.CopyHeaders(w.Header(), forwardResponse.Header)\n\t\tutils.RemoveHeaders(w.Header(), forward.HopHeaders...)\n\n\t\t// Grab the location header, if any.\n\t\tredirectURL, err := forwardResponse.Location()\n\n\t\tif err != nil {\n\t\t\tif err != http.ErrNoLocation {\n\t\t\t\ttracing.SetErrorAndDebugLog(r, \"Error reading response location header %s. Cause: %s\", config.Address, err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if redirectURL.String() != \"\" {\n\t\t\t// Set the location in our response if one was sent back.\n\t\t\tw.Header().Set(\"Location\", redirectURL.String())\n\t\t}\n\n\t\ttracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)\n\t\tw.WriteHeader(forwardResponse.StatusCode)\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tfor _, headerName := range config.AuthResponseHeaders {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tr.Header.Del(headerKey)\n\t\tif len(forwardResponse.Header[headerKey]) > 0 {\n\t\t\tr.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)\n\t\t}\n\t}\n\n\tr.RequestURI = r.URL.RequestURI()\n\tnext(w, r)\n}", "func (g *game) forward() {\n\tg.player.Parse(g.input)\n\n\tif g.player.IsQuitting() {\n\t\tg.next = g.newMenu()\n\t}\n}", "func (ms *MVCCStats) Forward(nowNanos int64) {\n\tif ms.LastUpdateNanos >= nowNanos {\n\t\treturn\n\t}\n\tms.AgeTo(nowNanos)\n}", "func (t *Type) ForwardType() *ForwardType", "func (m *EventItemRequestBuilder) Forward()(*i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.ForwardRequestBuilder) {\n return i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.NewForwardRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (tr *Peer) FastForward(ctx context.Context, target string,\n\treq *FastForwardRequest, resp *FastForwardResponse) error {\n\n\tif tr.isShutdown() {\n\t\treturn ErrTransportStopped\n\t}\n\n\ttr.wg.Add(1)\n\tdefer tr.wg.Done()\n\n\treturn tr.fastForward(ctx, target, req, resp)\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tif len(xs) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tmean := ag.ReduceMean(x)\n\t\tdev := ag.SubScalar(x, mean)\n\t\tstdDev := ag.Sqrt(ag.Add(ag.ReduceMean(ag.Square(dev)), m.Eps))\n\t\tout[i] = ag.Add(ag.Prod(ag.DivScalar(dev, stdDev), m.W), m.B)\n\t}\n\treturn out\n}", "func Forward() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\terr := recover() // Have to do recover directly in deferred function\n\tinternalPanicHandler.forward(err)\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func (f *Forward) Forward(state request.Request) (*dns.Msg, error) {\n\tif f == nil {\n\t\treturn nil, ErrNoForward\n\t}\n\n\tfails := 0\n\tvar upstreamErr error\n\tfor _, proxy := range f.List() {\n\t\tif proxy.Down(f.maxfails) {\n\t\t\tfails++\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// All upstream proxies are dead, assume healtcheck is complete broken and randomly\n\t\t\t// select an upstream to connect to.\n\t\t\tproxy = f.List()[0]\n\t\t}\n\n\t\tret, err := proxy.Connect(context.Background(), state, f.opts)\n\n\t\tret, err = truncated(state, ret, err)\n\t\tupstreamErr = err\n\n\t\tif err != nil {\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if the reply is correct; if not return FormErr.\n\t\tif !state.Match(ret) {\n\t\t\treturn state.ErrorMessage(dns.RcodeFormatError), nil\n\t\t}\n\n\t\treturn ret, err\n\t}\n\n\tif upstreamErr != nil {\n\t\treturn nil, upstreamErr\n\t}\n\n\treturn nil, ErrNoHealthy\n}", "func (s *Server) Forward(id int64, event api.Event) {\n\tif event.Type == \"logging\" {\n\t\t// Parse the message\n\t\tlogEntry := api.EventLogging{}\n\t\terr := json.Unmarshal(event.Metadata, &logEntry)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && logEntry.Level == \"dbug\" {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && !s.verbose && logEntry.Level == \"info\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := s.broadcast(event, true)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to forward event from member %d: %v\", id, err)\n\t}\n}", "func (v *SourceSearchContext) Forward(iter *gtk.TextIter) (*gtk.TextIter, *gtk.TextIter, bool, bool) {\n\n\tstart, end := new(gtk.TextIter), new(gtk.TextIter)\n\tvar hasWrappedAround C.gboolean\n\n\tc := C.gtk_source_search_context_forward(\n\t\tv.native(),\n\t\tnativeTextIter(iter),\n\t\tnativeTextIter(start),\n\t\tnativeTextIter(end),\n\t\t&hasWrappedAround)\n\n\treturn start, end, gobool(hasWrappedAround), gobool(c)\n}", "func (c *ManetConnection) forward(bytes []byte) {\n\tincomingHeader := data.PacketHeaderFromBytes(bytes)\n\n\tcached := c.inCache(incomingHeader.SequenceNumber, incomingHeader.SendKey)\n\tfmt.Println(\"CACHE: \", incomingHeader.SequenceNumber, incomingHeader.SendKey, cached)\n\n\tif cached || incomingHeader.TTL <= 1 {\n\t\tfmt.Println(\"DROP!\")\n\t\treturn\n\t}\n\n\tc.cache[incomingHeader.SequenceNumber] = incomingHeader.SendKey\n\tdelete(c.cache, incomingHeader.SequenceNumber-cacheDepth)\n\n\toutgoingHeader := &data.PacketHeader{\n\t\tSourceAddress: incomingHeader.SourceAddress,\n\t\tDestinationAddress: incomingHeader.DestinationAddress,\n\t\tPreviousHop: GetMyAddress(),\n\t\tTTL: incomingHeader.TTL - 1,\n\t\tPacketType: incomingHeader.PacketType,\n\t\tSequenceNumber: incomingHeader.SequenceNumber,\n\t\tNumBytes: incomingHeader.NumBytes,\n\t\tSendKey: incomingHeader.SendKey,\n\t}\n\n\tfor i, b := range outgoingHeader.ToBytes() {\n\t\tbytes[i] = b\n\t}\n\n\tfor neighbor := range myNeighbors {\n\t\tif neighbor == incomingHeader.PreviousHop {\n\t\t\tcontinue\n\t\t}\n\t\traddr := ToUDPAddr(neighbor)\n\t\tfmt.Println(\"FORWARD to\", neighbor, \"DEST: \", incomingHeader.DestinationAddress, \"aka\", raddr)\n\t\tif _, err := c.conn.WriteToUDP(bytes, raddr); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (p *Player) Forward() mgl32.Vec3 {\n\treturn p.Speed\n}", "func (m *ItemCalendarsItemCalendarViewEventItemRequestBuilder) Forward()(*ItemCalendarsItemCalendarViewItemForwardRequestBuilder) {\n return NewItemCalendarsItemCalendarViewItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func Forward(in, out Link) rules.Rule {\n\treturn rules.Rule(fmt.Sprintf(\n\t\t\"-t filter -A fw-interfaces -j ACCEPT -i %v -o %v\",\n\t\tin.Name(), out.Name()))\n}", "func (b *BaseController) Forward(title, templateName string) {\n\tb.Layout = filepath.Join(prefixNg, \"layout.htm\")\n\tb.TplName = filepath.Join(prefixNg, templateName)\n\tb.Data[\"Title\"] = b.Tr(title)\n\tb.LayoutSections = make(map[string]string)\n\tb.LayoutSections[\"HeaderInclude\"] = filepath.Join(prefixNg, viewPath, \"header-include.htm\")\n\n\tif b.UseCompressedJS {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-min-include.htm\")\n\t} else {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-include.htm\")\n\t}\n\n\tlog.Debugf(\"Loaded HeaderScriptInclude file: %s\", b.LayoutSections[\"HeaderScriptInclude\"])\n\n\tb.LayoutSections[\"FooterInclude\"] = filepath.Join(prefixNg, viewPath, \"footer-include.htm\")\n\tb.LayoutSections[\"HeaderContent\"] = filepath.Join(prefixNg, viewPath, \"header-content.htm\")\n\tb.LayoutSections[\"FooterContent\"] = filepath.Join(prefixNg, viewPath, \"footer-content.htm\")\n\n}", "func (matrix Matrix4) Forward() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[2][0],\n\t\tmatrix[2][1],\n\t\tmatrix[2][2],\n\t}.Unit()\n}", "func (r *Lachesis) FastForward(\n\treq *net.FastForwardRequest, resp *net.FastForwardResponse) error {\n\tresult, err := r.process(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, ok := result.(*net.FastForwardResponse)\n\tif !ok {\n\t\treturn ErrBadResult\n\t}\n\t*resp = *item\n\treturn nil\n}", "func (r *LeakyReLU[O]) Forward() (mat.Tensor, error) {\n\treturn r.x.Value().(mat.Matrix).ApplyWithAlpha(leakyReLU, r.alpha.Value().Item().F64()), nil\n}", "func (t *Transaction) forwardTransaction() {\n\tif t.tx == nil {\n\t\tpanic(\"tx is nil while forward was being called\")\n\t}\n\tselect {\n\tcase t.sendTxFound <- t.tx:\n\tcase <-t.shutdown:\n\t\treturn\n\t}\n}", "func Forward(bus EventBus) EventHandler {\n\treturn Handler(func(evt Event) error {\n\t\tbus.Publish(evt)\n\t\treturn nil\n\t})\n}", "func (r *RotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := Rotate(fx, r.angle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (fl *follow) forward(r io.Reader) (cont bool) {\n\tfl.Decoder.Reset(r)\n\treturn fl.Forwarder.Do(fl.Watcher, fl.Decoder)\n}", "func (f Forwarder) Forward() error {\n\terrs := []string{}\n\tfor container := range f.Config.Forwards {\n\t\terr := f.ForwardContainer(container)\n\t\tif err != nil {\n\t\t\terrs = append(errs, container)\n\t\t}\n\t}\n\n\tvar err error\n\tif len(errs) > 0 {\n\t\terr = fmt.Errorf(\"Unable to forward ports for containers %s\", strings.Join(errs, \", \"))\n\t}\n\treturn err\n}", "func Forward(b Branch, distance float64) Branch {\n\tvar b_new Branch\n\tb_new.phase = b.phase\n\tb_new.xy = b.xy + cmplx.Rect(distance, b.phase)\n\treturn b_new\n}", "func (la *Lattice) Forward(m TokenizeMode) {\n\tfor i, size := 1, len(la.list); i < size; i++ {\n\t\tcurrentList := la.list[i]\n\t\tfor index, target := range currentList {\n\t\t\tprevList := la.list[target.Start]\n\t\t\tif len(prevList) == 0 {\n\t\t\t\tla.list[i][index].Cost = maximumCost\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j, n := range prevList {\n\t\t\t\tvar c int16\n\t\t\t\tif n.Class != USER && target.Class != USER {\n\t\t\t\t\tc = la.dic.Connection.At(int(n.Right), int(target.Left))\n\t\t\t\t}\n\t\t\t\ttotalCost := int64(c) + int64(target.Weight) + int64(n.Cost)\n\t\t\t\tif m != Normal {\n\t\t\t\t\ttotalCost += int64(additionalCost(n))\n\t\t\t\t}\n\t\t\t\tif totalCost > maximumCost {\n\t\t\t\t\ttotalCost = maximumCost\n\t\t\t\t}\n\t\t\t\tif j == 0 || int32(totalCost) < la.list[i][index].Cost {\n\t\t\t\t\tla.list[i][index].Cost = int32(totalCost)\n\t\t\t\t\tla.list[i][index].prev = la.list[target.Start][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *Service) Forward(topicID, msgID, targetAddr, text string) error {\n\tpayload := map[string]interface{}{\n\t\t\"id\": msgID,\n\t\t\"address\": targetAddr,\n\t\t\"text\": text,\n\t}\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpf, err := s.client.Publish(topicID, b, 2, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pf.Wait(5 * time.Second)\n}", "func (b *LiteralArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) LiteralNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tlength := len(xs)\n\tqs := p.query.Forward(xs...)\n\tks := make([]ag.Node, length)\n\tvs := p.value.Forward(xs...)\n\tmapk := make(map[int]*IndexedNodes)\n\tmapv := make(map[int]*IndexedNodes)\n\n\t// TODO: can it be implemented in a concurrent fashion?\n\tfor i, q := range qs {\n\t\tnorm := p.Graph.Sqrt(p.Graph.ReduceSum(p.Graph.Pow(q, 2.0)))\n\t\tks[i] = p.Graph.DivScalar(q, norm) // Euclidean norm\n\t\th := p.getHash(ks[i].Value().(*mat.Dense))\n\t\tinsertNode(mapk, ks[i], i, h)\n\t\tinsertNode(mapv, vs[i], i, h)\n\t}\n\n\tcontext := make([]ag.Node, length)\n\tprob := make([]mat.Matrix, length)\n\tfor i, q := range qs {\n\t\tj := p.getHash(q.Value().(*mat.Dense))\n\t\tc, p := p.lshScaledDotProductAttention(p.Graph, q, mapk[j], mapv[j], length, p.scaleFactor)\n\t\tcontext[i], prob[i] = c, p\n\t}\n\n\tp.Attention = &ContextProb{\n\t\tcontext: context,\n\t\tprob: prob,\n\t}\n\treturn context\n}", "func (n *Node) Forward() FloatXX {\n\tif n.myoutCached {\n\t\treturn n.myout\n\t}\n\n\tif n.myType == InputNode {\n\t\tn.myout = n.inputValue\n\t} else {\n\t\tn.myout = FloatXX(0.0)\n\t\tfor index, otherNode := range n.inputNodes {\n\t\t\toutput := otherNode.Forward()\n\t\t\tn.inputs = append(n.inputs, output)\n\t\t\tn.myout += n.weights[index] * output\n\t\t}\n\t\tn.myout += n.biasValue * n.biasWeight\n\t\tmyoutActivated := n.activation(n.myout)\n\t\tn.myout = myoutActivated\n\t}\n\n\tn.myoutCached = true\n\treturn n.myout\n}", "func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train)\n\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tpredictionScores := mlm.lmHead.Forward(hiddenState)\n\n\treturn predictionScores, allHiddenStates, allAttentions, nil\n}", "func (r *Redirect) Forward(conn net.Conn) {\n\tif conn == nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\trequest = []byte{}\n\t\trequestTmp = make([]byte, 1024)\n\t)\n\n\tfor {\n\t\tn, err := conn.Read(requestTmp)\n\t\tif err != nil {\n\t\t\tr.reply(conn, nil, \"\", err)\n\t\t\treturn\n\t\t}\n\t\trequest = append(request, requestTmp[:n]...)\n\t\tif n < 1024 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(request)))\n\n\tif err != nil {\n\t\tr.reply(conn, nil, \"\", err)\n\t\treturn\n\t}\n\n\tu, err := url.Parse(string(req.RequestURI[1:]))\n\tif err != nil {\n\t\tr.reply(conn, req, \"\", err)\n\t\treturn\n\t}\n\treq.URL = u\n\treq.Host = u.Host\n\n\treq.RequestURI = \"\"\n\trequestObj := r.requestPool.Get().(*RequestWrapper)\n\trequestObj.CreatedTime = time.Now()\n\trequestObj.request = req\n\trequestObj.TryCount = 0\n\trequestObj.ID = r.makeID()\n\n\tif !r.putTask(requestObj, false) {\n\t\tr.reply(conn, req, \"\", errors.New(\"request put into buffer timeout\"))\n\t\treturn\n\t}\n\n\tr.reply(conn, req, requestObj.ID, nil)\n}", "func (c *compiler) jumpForward(jumpOp Opcode, args ...Opcode) int {\n\tc.add(jumpOp)\n\tc.add(args...)\n\tc.add(0)\n\treturn len(c.code)\n}", "func (r *Sub[O]) Forward() (mat.Tensor, error) {\n\treturn r.x1.Value().(mat.Matrix).Sub(r.x2.Value().(mat.Matrix)), nil\n}", "func (m *ItemMailFoldersItemMessagesMessageItemRequestBuilder) Forward()(*ItemMailFoldersItemMessagesItemForwardRequestBuilder) {\n return NewItemMailFoldersItemMessagesItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (r *Threshold[O]) Forward() (mat.Tensor, error) {\n\ty := r.x.Value().(mat.Matrix).ApplyWithAlpha(\n\t\tthreshold,\n\t\tr.threshold.Value().Item().F64(),\n\t\tr.k.Value().Item().F64(),\n\t)\n\treturn y, nil\n}", "func Forward(ctx context.Context, destination chan<- packet.Buf, source <-chan packet.Buf) {\n\tdefer contextack.Ack(ctx, ForwardDoneAck)\n\n\tvar p packet.Buf\n\n\tfor {\n\t\tvar (\n\t\t\tinput <-chan packet.Buf\n\t\t\toutput chan<- packet.Buf\n\t\t\tok bool\n\t\t)\n\n\t\tif p == nil {\n\t\t\tinput = source\n\t\t} else {\n\t\t\toutput = destination\n\t\t}\n\n\t\tselect {\n\t\tcase p, ok = <-input:\n\t\t\tif !ok {\n\t\t\t\t// EOF\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase output <- p:\n\t\t\t// ok\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *State) MoveForward() {\n\tif s.robotLost {\n\t\treturn\n\t}\n\tswitch s.direction {\n\tcase North:\n\t\ts.y++\n\t\tbreak\n\tcase South:\n\t\ts.y--\n\t\tbreak\n\tcase West:\n\t\ts.x--\n\t\tbreak\n\tcase East:\n\t\ts.x++\n\t\tbreak\n\t}\n\ts.robotLost = s.grid.hasRobotFallenOff(s.x, s.y)\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = p.forward(x)\n\t}\n\treturn ys\n}", "func (rh *RobertaLMHead) Forward(hiddenStates *ts.Tensor) *ts.Tensor {\n\tgelu := util.NewGelu()\n\tappliedDense := hiddenStates.Apply(rh.dense)\n\tgeluFwd := gelu.Fwd(appliedDense)\n\tappliedLN := geluFwd.Apply(rh.layerNorm)\n\tappliedDecoder := appliedLN.Apply(rh.decoder)\n\tappliedBias := appliedDecoder.MustAdd(rh.bias, true)\n\n\tgeluFwd.MustDrop()\n\tappliedDense.MustDrop()\n\tappliedLN.MustDrop()\n\n\treturn appliedBias\n}", "func (c *chrono) Forward(skew time.Duration) {\n\tc.skew = skew\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (n Neuron) FeedForward(previous_layer Layer) {\n sum := 0.0\n\n // Sum outputs from the previous layer.\n for _, neuron := range previous_layer {\n // TODO: there may be duplication issues here\n sum += neuron.output * neuron.output_weights[n.index].weight\n }\n\n n.output = n.Activation(sum)\n}", "func processForward(forward *chproto.ChangeForward) {\n\n\t// If we are already trying to forward a change forward message with\n\t// the same requesting node and request ID, discard this message.\n\tif _, exists := getForwardTimeout(uint16(*forward.Request.RequestNode),\n\t\t*forward.Request.RequestId); exists {\n\t\treturn\n\t}\n\n\t// Everything else in this function runs in a transaction.\n\t// We are read-only.\n\tstore.StartTransaction()\n\tdefer store.EndTransaction()\n\n\t// If this is a core node and this node stopped being leader less than\n\t// a Change Timeout Period ago, always add us to the ignore list.\n\tif config.IsCore() && !isIgnored(forward, config.Id()) {\n\t\tdiff := time.Now().Sub(store.StoppedLeading())\n\t\tif diff < config.CHANGE_TIMEOUT_PERIOD {\n\t\t\tforward.Ignores = append(forward.Ignores,\n\t\t\t\tuint32(config.Id()))\n\t\t}\n\t}\n\n\t// If all core node IDs are in the forward's ignore list, discard it.\n\tif len(forward.Ignores) == len(config.CoreNodes()) {\n\t\tlog.Print(\"shared/chrequest: dropped msg due to full ignores\")\n\t\treturn\n\t}\n\n\t// Otherwise, choose a potential leader node.\n\t// This is O(n^2) in the number of core nodes,\n\t// but we don't expect to have many.\n\tchosenNode := uint16(0)\n\t_, leader := store.Proposal()\n\tif leader != 0 && !isIgnored(forward, leader) {\n\t\tchosenNode = leader\n\t} else {\n\t\tfor _, node := range config.CoreNodes() {\n\t\t\tif !isIgnored(forward, node) {\n\t\t\t\tchosenNode = node\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif chosenNode == 0 {\n\t\t// Shouldn't happen.\n\t\tlog.Print(\"shared/chrequest: bug, \" +\n\t\t\t\"couldn't find candidate leader node\")\n\t\treturn\n\t}\n\n\t// If we are the selected leader, construct an external change request,\n\t// and send it on our change request channel.\n\tif chosenNode == config.Id() {\n\t\tintRequest := forward.Request\n\t\tchrequest := new(store.ChangeRequest)\n\t\tchrequest.RequestEntity = *intRequest.RequestEntity\n\t\tchrequest.RequestNode = uint16(*intRequest.RequestNode)\n\t\tchrequest.RequestId = *intRequest.RequestId\n\t\tchrequest.Changeset = make([]store.Change,\n\t\t\tlen(intRequest.Changeset))\n\n\t\tfor i, ch := range intRequest.Changeset {\n\t\t\tchrequest.Changeset[i].TargetEntity = *ch.TargetEntity\n\t\t\tchrequest.Changeset[i].Key = *ch.Key\n\t\t\tchrequest.Changeset[i].Value = *ch.Value\n\t\t}\n\n\t\tfor _, cb := range changeCallbacks {\n\t\t\tcb(chrequest)\n\t\t}\n\n\t\treturn\n\t}\n\n\t// Otherwise, we send it on to the selected leader,\n\t// add the selected leader to the ignore list,\n\t// and set a timeout to retry.\n\tsendForward(chosenNode, forward)\n\tforward.Ignores = append(forward.Ignores, uint32(chosenNode))\n\taddForwardTimeout(forward)\n}", "func (device *SilentStepperBrick) DriveForward() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionDriveForward), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {\n\tlState := makeFBOLockState()\n\tfbo.headLock.RLock(lState)\n\tdefer fbo.headLock.RUnlock(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t// We're already up to date.\n\t\treturn\n\t}\n\tif !fbo.hasBeenCleared {\n\t\t// No reason to fast-forward here if it hasn't ever been\n\t\t// cleared.\n\t\treturn\n\t}\n\n\tfbo.forcedFastForwards.Add(1)\n\tfbo.goTracked(func() {\n\t\tdefer fbo.forcedFastForwards.Done()\n\t\tctx, cancelFunc := fbo.newCtxWithFBOID()\n\t\tdefer cancelFunc()\n\n\t\tfbo.log.CDebugf(ctx, \"Forcing a fast-forward\")\n\t\tvar currHead ImmutableRootMetadata\n\t\tvar err error\n\tgetMD:\n\t\tfor i := 0; ; i++ {\n\t\t\tcurrHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)\n\t\t\tswitch errors.Cause(err).(type) {\n\t\t\tcase nil:\n\t\t\t\tbreak getMD\n\t\t\tcase kbfsmd.ServerErrorUnauthorized:\n\t\t\t\t// The MD server connection might not be authorized\n\t\t\t\t// yet, so give it a few chances to go through.\n\t\t\t\tif i > 5 {\n\t\t\t\t\tfbo.log.CDebugf(ctx,\n\t\t\t\t\t\t\"Still unauthorized for TLF %s; giving up fast-forward\",\n\t\t\t\t\t\tfbo.id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i == 0 {\n\t\t\t\t\tfbo.log.CDebugf(\n\t\t\t\t\t\tctx, \"Got unauthorized error when fast-forwarding %s; \"+\n\t\t\t\t\t\t\t\"trying again after a delay\", fbo.id())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tdefault:\n\t\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif currHead == (ImmutableRootMetadata{}) {\n\t\t\tfbo.log.CDebugf(ctx, \"No MD yet\")\n\t\t\treturn\n\t\t}\n\t\tfbo.log.CDebugf(ctx, \"Current head is revision %d\", currHead.Revision())\n\n\t\tlState := makeFBOLockState()\n\t\t// Kick off partial prefetching once the latest merged\n\t\t// revision is set.\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tfbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)\n\t\t\t}\n\t\t}()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\tfbo.headLock.Lock(lState)\n\t\tdefer fbo.headLock.Unlock(lState)\n\n\t\tif !fbo.hasBeenCleared {\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t\tfbo.hasBeenCleared = false\n\t\t\t}\n\t\t}()\n\n\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t// We're already up to date.\n\t\t\tfbo.log.CDebugf(ctx, \"Already up-to-date: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = fbo.doFastForwardLocked(ctx, lState, currHead)\n\t\tif err != nil {\n\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %v\", err)\n\t\t}\n\t})\n}", "func (d *Dispatcher) HandleForward(address string, h ForwardDial) {\n\td.forwards[address] = h\n}", "func (f *Forwarder) ForwardRequest(request []byte, destination, service, endpoint string,\n\tkeys []string, format tchannel.Format, opts *Options) ([]byte, error) {\n\n\tf.EmitEvent(RequestForwardedEvent{})\n\n\tf.incrementInflight()\n\topts = f.mergeDefaultOptions(opts)\n\trs := newRequestSender(f.sender, f, f.channel, request, keys, destination, service, endpoint, format, opts)\n\tb, err := rs.Send()\n\tf.decrementInflight()\n\n\tif err != nil {\n\t\tf.EmitEvent(FailedEvent{})\n\t} else {\n\t\tf.EmitEvent(SuccessEvent{})\n\t}\n\n\treturn b, err\n}", "func (c *compiler) patchForward(mark int) {\n\toffset := len(c.code) - mark\n\tc.code[mark-1] = opcodeInt(offset)\n}", "func (c *Cursor) Forward(n int) {\n\t(*c).Index += n\n}", "func (q Quat) Forward() Vec3f {\n\treturn q.RotateVec(Vec3f{0, 0, -1})\n}", "func (b *MessagesSendBuilder) ForwardMessages(v []int) *MessagesSendBuilder {\n\tb.Params[\"forward_messages\"] = v\n\treturn b\n}", "func (m *NN) Forward(x *gorgonia.Node) (err error) {\n\tl := make([]*gorgonia.Node, len(m.W)+1)\n\tldot := make([]*gorgonia.Node, len(m.W))\n\tp := make([]*gorgonia.Node, len(m.W))\n\n\t// initial the first layer\n\tl[0] = x\n\n\t// W X + B\n\tfor i := 0; i < len(m.W); i++ {\n\t\tif len(m.B) != 0 && i < len(m.W) {\n\t\t\tL1, err := gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(l[i].Shape(), m.W[i].Shape())\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tldot[i], err = gorgonia.BroadcastAdd(L1, m.B[i], nil, []byte{0})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tldot[i], err = gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"mul wrong \", err)\n\t\t\t}\n\t\t}\n\n\t\t// Dropout\n\t\tp[i], err = gorgonia.Dropout(ldot[i], m.D[i])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Can't drop!\")\n\t\t}\n\n\t\t//activation function\n\t\tl[i+1] = gorgonia.Must(m.A[i](p[i]))\n\t}\n\n\tm.Pred = gorgonia.Must(m.A[len(m.A)-1](l[len(l)-1]))\n\tgorgonia.Read(m.Pred, &m.PredVal)\n\treturn\n}", "func (ti *TimeIndex) iterForward(t time.Time) index.Iter {\n i := ti.IndexNear(t)\n return &forwardIter{\n at: i,\n ti: ti,\n }\n}", "func (rbm *RBM) Forward(v []float64) []float64 {\n\thidden := make([]float64, rbm.NumHiddenUnits)\n\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\thidden[i] = rbm.P_H_Given_V(i, v)\n\t}\n\treturn hidden\n}", "func (a *createBucketIam) forward(app *App, args ...interface{}) error {\n\tenv, err := createBucket(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _ := config.GetString(\"host\")\n\tenvVars := []bind.EnvVar{\n\t\t{Name: \"APPNAME\", Value: app.Name},\n\t\t{Name: \"TSURU_HOST\", Value: host},\n\t}\n\tvariables := map[string]string{\n\t\t\"ENDPOINT\": env.endpoint,\n\t\t\"LOCATIONCONSTRAINT\": strconv.FormatBool(env.locationConstraint),\n\t\t\"ACCESS_KEY_ID\": env.AccessKey,\n\t\t\"SECRET_KEY\": env.SecretKey,\n\t\t\"BUCKET\": env.bucket,\n\t}\n\tfor name, value := range variables {\n\t\tenvVars = append(envVars, bind.EnvVar{\n\t\t\tName: fmt.Sprintf(\"TSURU_S3_%s\", name),\n\t\t\tValue: value,\n\t\t\tInstanceName: s3InstanceName,\n\t\t})\n\t}\n\tapp.SetEnvsToApp(envVars, false, true)\n\treturn nil\n}", "func (n *MLP) forward(x mat.Matrix) (as, zs []mat.Matrix) {\n\tas = append(as, x) // first activation is input\n\n\t_x := x\n\n\tfor i := 0; i < len(n.weights); i++ {\n\t\tw := n.weights[i]\n\t\tb := n.biases[i]\n\n\t\tdot := new(mat.Dense)\n\t\tdot.Mul(_x, w)\n\n\t\tz := new(mat.Dense)\n\t\taddB := func(_, col int, v float64) float64 { return v + b.At(col, 0) }\n\t\tz.Apply(addB, dot)\n\n\t\ta := new(mat.Dense)\n\t\ta.Apply(applySigmoid, z)\n\n\t\tzs = append(zs, z)\n\t\tas = append(as, a)\n\n\t\t_x = a\n\t}\n\n\treturn\n}", "func (r *Pow) Forward() mat.Matrix {\n\treturn r.x.Value().Pow(r.power)\n}", "func (n *Network) Forward(inputs []float64) []float64 {\n\toutput := mat.NewVecDense(len(inputs), inputs)\n\n\tfor layerIdx, layer := range n.layers {\n\t\tfor outIdx, o := range output.RawVector().Data {\n\t\t\tif math.IsNaN(o) {\n\t\t\t\tpanic(fmt.Sprintf(\"NaN layer output at %d (layer %d)\", outIdx, layerIdx))\n\t\t\t}\n\t\t}\n\n\t\toutput = layer.forward(output)\n\t}\n\n\tres := []float64{}\n\tfor idx := 0; idx < output.Len(); idx++ {\n\t\tif math.IsNaN(output.AtVec(idx)) {\n\t\t\tpanic(\"NaN output value\")\n\t\t}\n\t\tres = append(res, output.AtVec(idx))\n\t}\n\n\treturn res\n}", "func forward(statusch <-chan engine.SearchStatus, responsech chan<- uci.Response) {\n\tfor info := range statusch {\n\t\tresponsech <- uci.ResponseSearchInformation{Depth: info.Depth}\n\t}\n}", "func (b *Brain) Forward(inputArray []float64) int {\r\n\tb.ForwardPasses++\r\n\tb.LastInputArray = inputArray // back this up\r\n\r\n\t// create network input\r\n\tvar (\r\n\t\tnetInput []float64\r\n\t\taction int\r\n\t)\r\n\tif b.ForwardPasses > b.TemporalWindow {\r\n\t\t// we have enough to actually do something reasonable\r\n\t\tnetInput = b.NetInput(inputArray)\r\n\r\n\t\tif b.Learning {\r\n\t\t\t// compute epsilon for the epsilon-greedy policy\r\n\t\t\tb.Epsilon = math.Min(1.0, math.Max(b.EpsilonMin, 1.0-float64(b.Age-b.LearningStepsBurnin)/float64(b.LearningStepsTotal-b.LearningStepsBurnin)))\r\n\t\t} else {\r\n\t\t\tb.Epsilon = b.EpsilonTestTime // use test-time value\r\n\t\t}\r\n\r\n\t\trf := b.Rand.Float64()\r\n\t\tif rf < b.Epsilon {\r\n\t\t\t// choose a random action with epsilon probability\r\n\t\t\taction = b.RandomAction()\r\n\t\t} else {\r\n\t\t\t// otherwise use our policy to make decision\r\n\t\t\taction, _ = b.Policy(netInput)\r\n\t\t}\r\n\t} else {\r\n\t\t// pathological case that happens first few iterations\r\n\t\t// before we accumulate window_size inputs\r\n\t\tnetInput = nil\r\n\t\taction = b.RandomAction()\r\n\t}\r\n\r\n\t// remember the state and action we took for backward pass\r\n\tcopy(b.NetWindow, b.NetWindow[1:])\r\n\tb.NetWindow[len(b.NetWindow)-1] = netInput\r\n\tcopy(b.StateWindow, b.StateWindow[1:])\r\n\tb.StateWindow[len(b.StateWindow)-1] = inputArray\r\n\tcopy(b.ActionWindow, b.ActionWindow[1:])\r\n\tb.ActionWindow[len(b.ActionWindow)-1] = action\r\n\r\n\treturn action\r\n}", "func (f *RemoteRuntime) PortForward(ctx context.Context, req *kubeapi.PortForwardRequest) (*kubeapi.PortForwardResponse, error) {\n\treturn f.RuntimeService.PortForward(ctx, req)\n}", "func (p *ProcType) FastForward(rev int64) *ProcType {\n\treturn p.Dir.Snapshot.fastForward(p, rev).(*ProcType)\n}", "func (re *RandomEqualize) Forward(x *ts.Tensor) *ts.Tensor {\n\tr := randPvalue()\n\tvar out *ts.Tensor\n\tswitch {\n\tcase r < re.pvalue:\n\t\tout = equalize(x)\n\tdefault:\n\t\tout = x.MustShallowClone()\n\t}\n\n\treturn out\n}", "func (t *TimeLine) Forward(nbars, num, denom uint32) {\n\tif nbars > 0 {\n\t\toldCursor := t.cursor\n\t\tt.forwardNBars(nbars)\n\t\tt.lastDelta = t.runCallbacks(oldCursor, t.cursor)\n\t}\n\n\tif num > 0 && denom > 0 {\n\t\tt.forward(num, denom, true)\n\t}\n\n}", "func forwardRequest(originatorAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte, toNode Node) {\n\tif self.Addr.String() == toNode.Addr.String() {\n\t\tfmt.Println(\"Stop. Can't forward to self - \", toNode.Addr.String())\n\t\treturn\n\t}\n\n\tsendRequestToNode(msgID, reqPay, &toNode)\n}" ]
[ "0.7115619", "0.70571136", "0.69965667", "0.69702876", "0.6634736", "0.6614", "0.65342593", "0.6481366", "0.6453834", "0.64295715", "0.6368864", "0.6234271", "0.6223834", "0.62171066", "0.6211164", "0.61765057", "0.61700433", "0.6166981", "0.61651725", "0.6146318", "0.6138534", "0.6138534", "0.6079714", "0.606273", "0.6047323", "0.60363173", "0.6031492", "0.6027961", "0.60170674", "0.60170674", "0.59922856", "0.59805536", "0.59745336", "0.5967437", "0.5958079", "0.5942645", "0.59374386", "0.5931645", "0.5888658", "0.5886676", "0.588589", "0.58730525", "0.5847739", "0.5829106", "0.5816305", "0.5796017", "0.5795595", "0.57895803", "0.5781477", "0.57796335", "0.5769082", "0.5762115", "0.57537293", "0.5734758", "0.57012063", "0.5697529", "0.56943", "0.5685213", "0.5676034", "0.56623995", "0.564404", "0.56392187", "0.56322736", "0.561377", "0.5608303", "0.560802", "0.55690306", "0.55685425", "0.5563199", "0.55562675", "0.5553099", "0.5545822", "0.55454445", "0.55437595", "0.5529709", "0.5513344", "0.55122876", "0.5504968", "0.5498305", "0.5497328", "0.5495212", "0.5492143", "0.5489961", "0.5489167", "0.5485278", "0.54730326", "0.54412466", "0.5424455", "0.5411337", "0.5405235", "0.5393996", "0.5377253", "0.537243", "0.53448695", "0.53408664", "0.53216213", "0.5314056", "0.5308751", "0.5295184", "0.52898306", "0.5283474" ]
0.0
-1
NewRobertaForMultipleChoice creates a new RobertaForMultipleChoice model.
func NewRobertaForMultipleChoice(p *nn.Path, config *bert.BertConfig) *RobertaForMultipleChoice { roberta := bert.NewBertModel(p.Sub("roberta"), config) dropout := util.NewDropout(config.HiddenDropoutProb) classifier := nn.NewLinear(p.Sub("classifier"), config.HiddenSize, 1, nn.DefaultLinearConfig()) return &RobertaForMultipleChoice{ roberta: roberta, dropout: dropout, classifier: classifier, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewChoice(allowedValues ...string) Choice {\n\treturn Choice{AllowedValues: allowedValues}\n}", "func NewMultipleResponsesClient() MultipleResponsesClient {\n return NewMultipleResponsesClientWithBaseURI(DefaultBaseURI, )\n}", "func (r Response) MultipleChoices(code string, payload Payload, header ...ResponseHeader) {\n\tr.Response(code, http.MultipleChoices, payload, header...)\n}", "func RadioButtonNew(group *glib.SList) (*RadioButton, error) {\n\tc := C.gtk_radio_button_new(cGSList(group))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapRadioButton(obj), nil\n}", "func (r *Responder) MultipleChoices() { r.write(http.StatusMultipleChoices) }", "func NewBetaGroupsBetaTestersCreateToManyRelationshipRequest(server string, id string, body BetaGroupsBetaTestersCreateToManyRelationshipJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBetaGroupsBetaTestersCreateToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func (t *Device) NewVehicle(Id string) (*OnfTest1Choice_Vehicle, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Vehicle == nil {\n\t\tt.Vehicle = make(map[string]*OnfTest1Choice_Vehicle)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Vehicle[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Vehicle\", key)\n\t}\n\n\tt.Vehicle[key] = &OnfTest1Choice_Vehicle{\n\t\tId: &Id,\n\t}\n\n\treturn t.Vehicle[key], nil\n}", "func NewBetaTestersBetaGroupsCreateToManyRelationshipRequest(server string, id string, body BetaTestersBetaGroupsCreateToManyRelationshipJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBetaTestersBetaGroupsCreateToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewEnumMultiResponse(ctx context.Context, selected []interface{}, options ...interface{}) EnumMultiResponse {\n\tvar er EnumMultiResponse\n\n\tfor _, s := range selected {\n\t\tselStr := fmt.Sprintf(\"%s\", s)\n\t\ter.Values = append(er.Values, selStr)\n\t}\n\n\tfor _, opt := range options {\n\t\toptStr := fmt.Sprintf(\"%s\", opt)\n\t\topt := EnumOption{\n\t\t\tValue: optStr,\n\t\t\tTitle: EnumValueTitle(optStr),\n\t\t}\n\n\t\tfor _, s := range selected {\n\t\t\tselStr := fmt.Sprintf(\"%s\", s)\n\t\t\tif optStr == selStr {\n\t\t\t\topt.Selected = true\n\t\t\t}\n\t\t}\n\n\t\ter.Options = append(er.Options, opt)\n\t}\n\n\treturn er\n}", "func (c *RBController) NewRecipe(w http.ResponseWriter, r *http.Request) (err error) {\n\t// build data with anonymous struct\n\tdata := struct {\n\t\t*Recipe\n\t\tNewRecipe bool\n\t}{\n\t\tnew(Recipe),\n\t\ttrue,\n\t}\n\n\t// pass data to render\n\tc.HTML(w, http.StatusOK, \"recipes/edit\", data)\n\treturn nil\n}", "func NewChoice() Choice {\n\treturn new(ChoiceImpl)\n}", "func NewMultiNested() *MultiNested {\n\tself := MultiNested{}\n\tself.SetDefaults()\n\treturn &self\n}", "func newChoiceBuilder(choiceDef *ChoiceDef) ChoiceBuilder {\n\treturn &chosenBuilder{\n\t\tchoiceDef: choiceDef,\n\t}\n}", "func (t *OpenconfigOfficeAp_Radios) NewRadio(Id uint8) (*OpenconfigOfficeAp_Radios_Radio, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Radio == nil {\n\t\tt.Radio = make(map[uint8]*OpenconfigOfficeAp_Radios_Radio)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Radio[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Radio\", key)\n\t}\n\n\tt.Radio[key] = &OpenconfigOfficeAp_Radios_Radio{\n\t\tId: &Id,\n\t}\n\n\treturn t.Radio[key], nil\n}", "func (c *ClientWithResponses) BetaTestersBetaGroupsCreateToManyRelationshipWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BetaTestersBetaGroupsCreateToManyRelationshipResponse, error) {\n\trsp, err := c.BetaTestersBetaGroupsCreateToManyRelationshipWithBody(ctx, id, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBetaTestersBetaGroupsCreateToManyRelationshipResponse(rsp)\n}", "func (c *ClientWithResponses) BetaGroupsBetaTestersCreateToManyRelationshipWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BetaGroupsBetaTestersCreateToManyRelationshipResponse, error) {\n\trsp, err := c.BetaGroupsBetaTestersCreateToManyRelationshipWithBody(ctx, id, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBetaGroupsBetaTestersCreateToManyRelationshipResponse(rsp)\n}", "func NewRobo(pitches []mlpapi.Pitch, rules []mlpapi.Rule) (robo *RoboRooney) {\n\trobo = &RoboRooney{}\n\trobo.cred = readCredentials()\n\n\trobo.mlpClient = mlpapi.New()\n\trobo.tracker = NewTracker()\n\trobo.ticker = time.NewTicker(time.Minute * time.Duration(robo.cred.TickerInterval))\n\n\tif len(pitches) == 0 {\n\t\tlog.Fatal(\"Need atleast one pitch to check\")\n\t}\n\n\trobo.pitches = pitches\n\trobo.rules = rules\n\n\treturn robo\n}", "func (v ConversationsResource) New(c buffalo.Context) error {\n\tconversation := &models.Conversation{}\n\n\tconversation.OccurredOn = time.Now()\n\tconversation.Publish = true\n\terr := v.loadForm(conversation, c)\n\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\treturn c.Render(200, r.HTML(\"conversations/new.html\"))\n}", "func NewRBAC(address common.Address, backend bind.ContractBackend) (*RBAC, error) {\n\tcontract, err := bindRBAC(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBAC{RBACCaller: RBACCaller{contract: contract}, RBACTransactor: RBACTransactor{contract: contract}, RBACFilterer: RBACFilterer{contract: contract}}, nil\n}", "func (c *ClientWithResponses) BetaGroupsBuildsCreateToManyRelationshipWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BetaGroupsBuildsCreateToManyRelationshipResponse, error) {\n\trsp, err := c.BetaGroupsBuildsCreateToManyRelationshipWithBody(ctx, id, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBetaGroupsBuildsCreateToManyRelationshipResponse(rsp)\n}", "func NewRadio(guildID string) *Radio {\n\treturn &Radio{\n\t\tGuildID: guildID,\n\t\tQueue: NewSongQueue(),\n\t\tcontrol: make(chan int),\n\t\tAutoPlay: true,\n\t\tSilent: false,\n\t}\n}", "func (*recipeLipidR) NewStruct() *recipeLipidR {\n\treturn &recipeLipidR{}\n}", "func NewRobertaForSequenceClassification(p *nn.Path, config *bert.BertConfig) *RobertaForSequenceClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tclassifier := NewRobertaClassificationHead(p.Sub(\"classifier\"), config)\n\n\treturn &RobertaForSequenceClassification{\n\t\troberta: roberta,\n\t\tclassifier: classifier,\n\t}\n}", "func (mc *RobertaForMultipleChoice) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmc.dropout = util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, 1, nn.DefaultLinearConfig())\n\tmc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tlmHead := NewRobertaLMHead(p.Sub(\"lm_head\"), config)\n\n\treturn &RobertaForMaskedLM{\n\t\troberta: roberta,\n\t\tlmHead: lmHead,\n\t}\n}", "func NewBuildsBetaGroupsCreateToManyRelationshipRequest(server string, id string, body BuildsBetaGroupsCreateToManyRelationshipJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBuildsBetaGroupsCreateToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func New(options ...Option) slice.Bundle {\n\tb := &slice.Bundle{}\n\tfor _, opt := range options {\n\t\topt.apply(b)\n\t}\n\treturn *b\n}", "func New(ingredient1,ingredient2,ingredient3 string) ingredients{\nreturn ingredients{\n\tbread: ingredient1,\n\tgravy: ingredient2,\n\tcheese: ingredient3,\n}\n}", "func (c *ClientWithResponses) BuildsBetaGroupsCreateToManyRelationshipWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BuildsBetaGroupsCreateToManyRelationshipResponse, error) {\n\trsp, err := c.BuildsBetaGroupsCreateToManyRelationshipWithBody(ctx, id, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBuildsBetaGroupsCreateToManyRelationshipResponse(rsp)\n}", "func NewRobertaForTokenClassification(p *nn.Path, config *bert.BertConfig) *RobertaForTokenClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tnumLabels := int64(len(config.Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForTokenClassification{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func (c *ClientWithResponses) BetaTestersBuildsCreateToManyRelationshipWithBodyWithResponse(ctx context.Context, id string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*BetaTestersBuildsCreateToManyRelationshipResponse, error) {\n\trsp, err := c.BetaTestersBuildsCreateToManyRelationshipWithBody(ctx, id, contentType, body, reqEditors...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ParseBetaTestersBuildsCreateToManyRelationshipResponse(rsp)\n}", "func (b *GroupsSetCallbackSettingsBuilder) LeadFormsNew(v bool) *GroupsSetCallbackSettingsBuilder {\n\tb.Params[\"lead_forms_new\"] = v\n\treturn b\n}", "func NewMultipleResponsesClientWithBaseURI(baseURI string, ) MultipleResponsesClient {\n return MultipleResponsesClient{NewWithBaseURI(baseURI, )}\n}", "func (c RadioButtonCreator) Create(ctx context.Context, parent page.ControlI) page.ControlI {\n\tctrl := NewRadioButton(parent, c.ID)\n\tif c.Text != \"\" {\n\t\tctrl.SetText(c.Text)\n\t}\n\tif c.LabelMode != html5tag.LabelDefault {\n\t\tctrl.LabelMode = c.LabelMode\n\t}\n\tif c.LabelAttributes != nil {\n\t\tctrl.LabelAttributes().Merge(c.LabelAttributes)\n\t}\n\tif c.Group != \"\" {\n\t\tctrl.SetGroup(c.Group)\n\t}\n\n\tctrl.ApplyOptions(ctx, c.ControlOptions)\n\tif c.SaveState {\n\t\tctrl.SaveState(ctx, c.SaveState)\n\t}\n\tif c.Inline {\n\t\tctrl.SetInline(c.Inline)\n\t}\n\treturn ctrl\n}", "func NewCreate(f func(string, string, []string) (proto.Message, error)) *cobra.Command {\n\tvar (\n\t\tdisplayName string\n\t\tpermissionIDs []string\n\t)\n\n\tcmd := template.NewArg1Proto(\"create ROLE_ID\", \"Create a new role\", func(cmd *cobra.Command, arg string) (proto.Message, error) {\n\t\tvar names []string\n\t\tfor _, p := range permissionIDs {\n\t\t\tnames = append(names, fmt.Sprintf(\"permissions/%s\", p))\n\t\t}\n\t\treturn f(arg, displayName, names)\n\t})\n\n\tcmd.Flags().StringVar(&displayName, \"display-name\", \"\", \"display name\")\n\tcmd.Flags().StringSliceVar(&permissionIDs, \"permission-ids\", nil, \"permission ids\")\n\n\treturn cmd\n}", "func NewObject(t ...[2]*Term) Object {\n\tobj := newobject(len(t))\n\tfor i := range t {\n\t\tobj.Insert(t[i][0], t[i][1])\n\t}\n\treturn obj\n}", "func New() *RelatedAltPtysSubGrp {\n\tvar m RelatedAltPtysSubGrp\n\treturn &m\n}", "func (c *Client) NewCreateArrayPrismRequest(ctx context.Context, path string, payload *CreateArrayPrismPayload, contentType string) (*http.Request, error) {\n\tvar body bytes.Buffer\n\tif contentType == \"\" {\n\t\tcontentType = \"*/*\" // Use default encoder\n\t}\n\terr := c.Encoder.Encode(payload, &body, contentType)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to encode body: %s\", err)\n\t}\n\tscheme := c.Scheme\n\tif scheme == \"\" {\n\t\tscheme = \"http\"\n\t}\n\tu := url.URL{Host: c.Host, Scheme: scheme, Path: path}\n\treq, err := http.NewRequest(\"POST\", u.String(), &body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\tif contentType == \"*/*\" {\n\t\theader.Set(\"Content-Type\", \"application/json\")\n\t} else {\n\t\theader.Set(\"Content-Type\", contentType)\n\t}\n\treturn req, nil\n}", "func NewBetaGroupsBuildsCreateToManyRelationshipRequest(server string, id string, body BetaGroupsBuildsCreateToManyRelationshipJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBetaGroupsBuildsCreateToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\n\tlayerNormConfig := nn.DefaultLayerNormConfig()\n\tlayerNormConfig.Eps = 1e-12\n\tlayerNorm := nn.NewLayerNorm(p.Sub(\"layer_norm\"), []int64{config.HiddenSize}, layerNormConfig)\n\n\tdecoder := util.NewLinearNoBias(p.Sub(\"decoder\"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig())\n\n\tbias := p.NewVar(\"bias\", []int64{config.VocabSize}, nn.NewKaimingUniformInit())\n\n\treturn &RobertaLMHead{\n\t\tdense: dense,\n\t\tdecoder: decoder,\n\t\tlayerNorm: layerNorm,\n\t\tbias: bias,\n\t}\n}", "func newModelItems() modelItems {\n\treturn []item{}\n}", "func NewMultiValidator(validators ProcessesValidators) Validator {\n\treturn &MultiValidator{validators: validators}\n}", "func NewRBACTransactor(address common.Address, transactor bind.ContractTransactor) (*RBACTransactor, error) {\n\tcontract, err := bindRBAC(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBACTransactor{contract: contract}, nil\n}", "func (a *api) MultiCreateTeamV1(\n\tctx context.Context,\n\treq *desc.MultiCreateTeamV1Request) (*desc.MultiCreateTeamV1Response, error) {\n\tmetrics.IncTotalRequestsCounter()\n\tif err := req.Validate(); err != nil {\n\t\tmetrics.IncInvalidRequestsCounter()\n\t\tlog.Error().Err(err).Msg(\"invalid argument\")\n\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t}\n\tlog.Debug().Msgf(\"MultiCreateTeamV1() was called with len=%d\", len(req.Teams))\n\n\ttracer := opentracing.GlobalTracer()\n\tparentSpan := tracer.StartSpan(\"MultiCreateTeamV1\")\n\tdefer parentSpan.Finish()\n\n\tteams := make([]models.Team, 0, len(req.Teams))\n\tfor _, team := range req.Teams {\n\t\tteams = append(teams, models.Team{\n\t\t\tName: team.Name,\n\t\t\tDescription: team.Description,\n\t\t})\n\t}\n\n\tbatches := utils.SplitToBulks(teams, config.GetInstance().Common.BatchSize)\n\n\tvar teamsIds []uint64\n\n\tfor i, batch := range batches {\n\t\tids, err := a.repo.CreateTeams(ctx, batch)\n\n\t\tif err != nil {\n\t\t\treturn &desc.MultiCreateTeamV1Response{Ids: teamsIds}, status.Error(codes.Internal, err.Error())\n\t\t}\n\n\t\tchildSpan := tracer.StartSpan(\n\t\t\tfmt.Sprintf(\"batch_index=%d, batch_size=%d\", i, len(batch)),\n\t\t\topentracing.ChildOf(parentSpan.Context()),\n\t\t)\n\t\tchildSpan.Finish()\n\n\t\tteamsIds = append(teamsIds, ids...)\n\t}\n\n\treturn &desc.MultiCreateTeamV1Response{\n\t\tIds: teamsIds,\n\t}, nil\n}", "func NewREDEMPTIONREQUESTS() REDEMPTIONREQUESTS {\r\n return &REDEMPTIONREQUESTS_IMPL{}\r\n}", "func NewRTGProtocol(n int, q, p []uint64, sigma float64) *RTGProtocol {\n\trtg := new(RTGProtocol)\n\trtg.ringQModCount = len(q)\n\trtg.ringPModulusBigint = big.NewInt(1)\n\tfor _, pi := range p {\n\t\trtg.ringPModulusBigint.Mul(rtg.ringPModulusBigint, new(big.Int).SetUint64(pi))\n\t}\n\trtg.alpha = len(p)\n\tif rtg.alpha != 0 {\n\t\trtg.beta = int(math.Ceil(float64(len(q)) / float64(len(p))))\n\t} else {\n\t\trtg.beta = 1\n\t}\n\tvar err error\n\trtg.ringQP, err = ring.NewRing(n, append(q, p...))\n\tif err != nil {\n\t\tpanic(err) // TODO error\n\t}\n\n\tprng, err := utils.NewPRNG()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trtg.gaussianSampler = ring.NewGaussianSampler(prng)\n\trtg.sigma = sigma\n\n\trtg.tmpPoly = [2]*ring.Poly{rtg.ringQP.NewPoly(), rtg.ringQP.NewPoly()}\n\n\treturn rtg\n}", "func NewRobertaForQuestionAnswering(p *nn.Path, config *bert.BertConfig) *RobertaForQuestionAnswering {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForQuestionAnswering{\n\t\troberta: roberta,\n\t\tqaOutputs: qaOutputs,\n\t}\n}", "func New() *Motto {\n return &Motto{otto.New(), make(map[string]ModuleLoader), nil, make(map[string]otto.Value)}\n}", "func NewMultiStrategy(filters []PeerFilter, peerIDs []peer.ID) *MultiStrategy {\n\treturn &MultiStrategy{\n\t\tfilters: filters,\n\t\tpeerIDs: peerIDs,\n\t}\n}", "func (m *EducationAssignmentItemRequestBuilder) Rubric()(*i4a60e659b3e1427ff2f92b71f44e26c8ac1ac819ee646533021117deeeb6b88a.RubricRequestBuilder) {\n return i4a60e659b3e1427ff2f92b71f44e26c8ac1ac819ee646533021117deeeb6b88a.NewRubricRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func NewRaid(inputPlanes ...Plane) (Raid, error) {\n\tif len(inputPlanes) == 0 {\n\t\treturn Raid{}, errors.New(\"no planes to launch\")\n\t}\n\tvar planes []Plane\n\tfor _, plane := range inputPlanes {\n\t\tplanes = append(planes, plane)\n\t}\n\treturn Raid{Planes: planes}, nil\n}", "func GenerateMultiSelect(items []string, text string, phtext string) (options Blocks) {\n\n\tvar o []Options\n\n\tfor i, item := range items {\n\t\to = append(o, Options{\n\t\t\tValue: fmt.Sprintf(\"value-%v\", i),\n\t\t\tOptionsText: OptionsText{\n\t\t\t\tType: \"plain_text\",\n\t\t\t\tText: item,\n\t\t\t\tEmoji: true,\n\t\t\t},\n\t\t},\n\t\t)\n\t}\n\n\tSection := Blocks{Type: \"section\",\n\t\tText: &Text{\n\t\t\tText: text,\n\t\t\tType: \"mrkdwn\",\n\t\t},\n\t\tAccessory: &Accessory{\n\t\t\tType: \"multi_static_select\",\n\t\t\tPlaceHolder: &PlaceHolder{\n\t\t\t\tType: \"plain_text\",\n\t\t\t\tText: phtext,\n\t\t\t\tEmoji: true,\n\t\t\t},\n\t\t\tOptions: &o,\n\t\t},\n\t}\n\n\treturn Section\n\n}", "func newReconciledMTAdapterRoleBinding() *rbacv1.RoleBinding {\n\treturn NewMTAdapterRoleBinding(newReconciledServiceAccount())()\n}", "func NewRetrier(options ...RetrierOption) *Retrier {\n\tt := defaultRetrier()\n\n\tfor _, opt := range options {\n\t\topt(t)\n\t}\n\n\treturn t\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func NewLanguageModel(ctx *pulumi.Context,\n\tname string, args *LanguageModelArgs, opts ...pulumi.ResourceOption) (*LanguageModel, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.BaseModelName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'BaseModelName'\")\n\t}\n\tif args.InputDataConfig == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InputDataConfig'\")\n\t}\n\tif args.LanguageCode == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'LanguageCode'\")\n\t}\n\tif args.ModelName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'ModelName'\")\n\t}\n\tvar resource LanguageModel\n\terr := ctx.RegisterResource(\"aws:transcribe/languageModel:LanguageModel\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func newBook(r CreateRequest) *book.Book {\n\tb := new(book.Book)\n\tb.ID = db.NextID()\n\tb.Author = r.Author\n\tb.Title = r.Title\n\treturn b\n}", "func NewBetaTestersBuildsCreateToManyRelationshipRequest(server string, id string, body BetaTestersBuildsCreateToManyRelationshipJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBetaTestersBuildsCreateToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewAndroidLobApp()(*AndroidLobApp) {\n m := &AndroidLobApp{\n MobileLobApp: *NewMobileLobApp(),\n }\n odataTypeValue := \"#microsoft.graph.androidLobApp\"\n m.SetOdataType(&odataTypeValue)\n return m\n}", "func NewMatcher(criteria ...Criterion) *Matcher {\n\tm := Matcher{\n\t\tconstraints: make([]choiceConstraint, 0, 5),\n\t}\n\tfor _, criterion := range criteria {\n\t\tcriterion(&m)\n\t}\n\treturn &m\n}", "func (a *api) MultiCreateClassroomV1(ctx context.Context,\n\treq *grpcApi.MultiCreateClassroomV1Request) (res *grpcApi.MultiCreateClassroomV1Response, err error) {\n\n\tdefer utils.LogGrpcCall(\"MultiCreateClassroomV1\", &req, &res, &err)\n\n\ttracer := opentracing.GlobalTracer()\n\tspan := tracer.StartSpan(\"MultiCreateClassroomV1\")\n\tdefer span.Finish()\n\n\tif err = req.Validate(); err != nil {\n\n\t\terr = status.Error(codes.InvalidArgument, err.Error())\n\t\treturn nil, err\n\t}\n\n\tvar classrooms []models.Classroom\n\tfor _, protoClassroom := range req.Classrooms {\n\n\t\tclassrooms = append(classrooms, models.Classroom{\n\t\t\tTenantId: protoClassroom.TenantId,\n\t\t\tCalendarId: protoClassroom.CalendarId,\n\t\t})\n\t}\n\n\tfl := flusher.New(a.classroomRepo, chunkSize)\n\tremainingClassrooms := fl.Flush(ctx, span, classrooms)\n\n\tvar createdCount = uint64(len(classrooms) - len(remainingClassrooms))\n\tif createdCount == 0 {\n\n\t\terr = status.Error(codes.Unavailable, errors.New(\"flush call returned non nil result\").Error())\n\t\treturn nil, err\n\t}\n\n\tres = &grpcApi.MultiCreateClassroomV1Response{CreatedCount: createdCount}\n\treturn res, nil\n}", "func (to *Session) CreateMultipleParameters(pls []tc.Parameter, opts RequestOptions) (tc.Alerts, toclientlib.ReqInf, error) {\n\tvar alerts tc.Alerts\n\treqInf, err := to.post(apiParameters, opts, pls, &alerts)\n\treturn alerts, reqInf, err\n}", "func NewMeetingParticipants()(*MeetingParticipants) {\n m := &MeetingParticipants{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}", "func NewAsyncBR(t mockConstructorTestingTNewAsyncBR) *AsyncBR {\n\tmock := &AsyncBR{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (*authItemGroupR) NewStruct() *authItemGroupR {\n\treturn &authItemGroupR{}\n}", "func newChoiceFalseBuilder(choiceDef *ChoiceDef) ChoiceFalseBuilder {\n\treturn &choiceFalseBuilder{\n\t\tchoiceDef: choiceDef,\n\t}\n}", "func NewUpdateAllowedCombinationsResult()(*UpdateAllowedCombinationsResult) {\n m := &UpdateAllowedCombinationsResult{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}", "func NewBetaTestersBetaGroupsCreateToManyRelationshipRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParamWithLocation(\"simple\", false, \"id\", runtime.ParamLocationPath, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserverURL, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toperationPath := fmt.Sprintf(\"/v1/betaTesters/%s/relationships/betaGroups\", pathParam0)\n\tif operationPath[0] == '/' {\n\t\toperationPath = \".\" + operationPath\n\t}\n\n\tqueryURL, err := serverURL.Parse(operationPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryURL.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\n\treturn req, nil\n}", "func (a PromptsApi) CreatePromptBot(listId string, emailId string, endDate string, promptSubject string, promptBody string, botTypeId string, templateId string) (*PromptBotBot, *APIResponse, error) {\n\n\tvar httpMethod = \"Post\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/prompts/bots\"\n\n\n\theaderParams := make(map[string]string)\n\tqueryParams := url.Values{}\n\tformParams := make(map[string]string)\n\tvar postBody interface{}\n\tvar fileName string\n\tvar fileBytes []byte\n\t// authentication '(BBOAuth2)' required\n\t// oauth required\n\tif a.Configuration.AccessToken != \"\"{\n\t\theaderParams[\"Authorization\"] = \"Bearer \" + a.Configuration.AccessToken\n\t}\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\theaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{ \"application/x-www-form-urlencoded\", }\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\theaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\theaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\n\tformParams[\"listId\"] = listId\n\tformParams[\"emailId\"] = emailId\n\tformParams[\"endDate\"] = endDate\n\tformParams[\"promptSubject\"] = promptSubject\n\tformParams[\"promptBody\"] = promptBody\n\tformParams[\"botTypeId\"] = botTypeId\n\tformParams[\"templateId\"] = templateId\n\tvar successPayload = new(PromptBotBot)\n\thttpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)\n\tif err != nil {\n\t\treturn successPayload, NewAPIResponse(httpResponse.RawResponse), err\n\t}\n\terr = json.Unmarshal(httpResponse.Body(), &successPayload)\n\treturn successPayload, NewAPIResponse(httpResponse.RawResponse), err\n}", "func New(raw interface{}) Enum {\n\tval := reflect.ValueOf(raw)\n\tswitch val.Kind() {\n\tcase reflect.Slice:\n\t\tif val.Len() == 0 {\n\t\t\treturn empty\n\t\t}\n\t\treturn slice{val}\n\tdefault: // Or maybe Invalid?\n\t\treturn empty\n\t}\n}", "func (*recipeAdditiveR) NewStruct() *recipeAdditiveR {\n\treturn &recipeAdditiveR{}\n}", "func NewBetaGroupsBetaTestersCreateToManyRelationshipRequestWithBody(server string, id string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParamWithLocation(\"simple\", false, \"id\", runtime.ParamLocationPath, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserverURL, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toperationPath := fmt.Sprintf(\"/v1/betaGroups/%s/relationships/betaTesters\", pathParam0)\n\tif operationPath[0] == '/' {\n\t\toperationPath = \".\" + operationPath\n\t}\n\n\tqueryURL, err := serverURL.Parse(operationPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", queryURL.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\n\treturn req, nil\n}", "func NewMultiFileReader(file Directory, form bool) *MultiFileReader {\n\tit := file.Entries()\n\n\tmfr := &MultiFileReader{\n\t\tfiles: []DirIterator{it},\n\t\tpath: []string{\"\"},\n\t\tform: form,\n\t\tmutex: &sync.Mutex{},\n\t}\n\tmfr.mpWriter = multipart.NewWriter(&mfr.buf)\n\n\treturn mfr\n}", "func (r *RoleBinding) Create() error {\n\troleBinding := getRoleBinding(r.Name, r.Namespace, r.labels)\n\troleBinding.Subjects = r.subjects\n\troleBinding.RoleRef = *r.roleRef\n\treturn Create(r.client, roleBinding)\n}", "func NewRbac(c *restclient.Config) (*RbacClient, error) {\n\tconfig := *c\n\tif err := setGroupDefaults(rbac.GroupName, &config); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := restclient.RESTClientFor(&config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RbacClient{client}, nil\n}", "func New(token string) (*GAB, error) {\n\tbot, err := tapi.NewBotAPI(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create new bot with provided token: %v\", err)\n\t}\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\treturn &GAB{\n\t\tTelBot: bot,\n\t}, nil\n}", "func NewMultiRoleBindingCRD(k8ssvc k8s.Service) *MultiRoleBindingCRD {\n\treturn &MultiRoleBindingCRD{\n\t\tk8ssvc: k8ssvc,\n\t}\n}", "func NewModel(selection *Selection) *Model {\n\treturn &Model{Selection: selection}\n}", "func newLabo(s *goquery.Selection, l *Labo) *Labo {\n\tfor _, fn := range laboFn {\n\t\tfn(s, l)\n\t}\n\treturn l\n}", "func NewBot() TipBot {\n\t// create sqlite databases\n\tdb, txLogger := migration()\n\treturn TipBot{\n\t\tDatabase: db,\n\t\tClient: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),\n\t\tlogger: txLogger,\n\t\tBunt: createBunt(),\n\t\tTelegram: newTelegramBot(),\n\t}\n}", "func NewTournament(name string) *Tournament {\n\tresult := &Tournament{\n\t\tName: name,\n\t\tGameScore: 50,\n\t\tInitialRanking: 1500,\n\t}\n\treturn result\n}", "func NewMultiRaft(nodeID uint64, config *Config) (*MultiRaft, error) {\n\tif nodeID == 0 {\n\t\treturn nil, util.Error(\"Invalid NodeID\")\n\t}\n\terr := config.Validate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.Ticker == nil {\n\t\tconfig.Ticker = newTicker(config.TickInterval)\n\t}\n\n\tm := &MultiRaft{\n\t\tConfig: *config,\n\t\tmultiNode: raft.StartMultiNode(nodeID, config.ElectionTimeoutTicks,\n\t\t\tconfig.HeartbeatIntervalTicks),\n\t\tnodeID: nodeID,\n\t\tEvents: make(chan interface{}, 1000),\n\t\tops: make(chan interface{}, 100),\n\t\trequests: make(chan *rpc.Call, 100),\n\t\tstopped: make(chan struct{}),\n\t}\n\n\terr = m.Transport.Listen(nodeID, m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}", "func (roles *RoleProvider) New(r *idam.Role) (*idam.Role, error) {\n\troles.lock.Lock()\n\tdefer roles.lock.Unlock()\n\n\tif r, ok := roles.getRole(r.Name); ok {\n\t\treturn copyRole(r), nil\n\t}\n\n\tnewRole := idam.NewRole(r.Name, r.Permissions, r.Creator)\n\n\troles.roles = append(roles.roles, newRole)\n\n\treturn copyRole(newRole), roles.saveToFile()\n}", "func NewOf3Or5(max int) Multiples {\n\tvar m Multiples\n\n\tfor i := 1; i < max; i++ {\n\t\tif i%3 == 0 || i%5 == 0 {\n\t\t\tm = append(m, i)\n\t\t}\n\t}\n\n\treturn m\n}", "func New[T float.DType](c Config) *RAdam[T] {\n\tadam := &RAdam[T]{\n\t\tConfig: c,\n\t\tRoMax: 2.0/(1.0-c.Beta2) - 1.0,\n\t\tTimeStep: 1.0,\n\t}\n\treturn adam\n}", "func NewLearner(id int, nrOfNodes int, valueOut chan<- Value) *Learner {\n\t//TODO(student): Task 2 and 3 - algorithm and distributed implementation\n\treturn &Learner{}\n}", "func NewMultipleNode(total int64, nodes []Node, ) *MultipleNode {\n\tthis := MultipleNode{}\n\tthis.Total = total\n\tthis.Nodes = nodes\n\treturn &this\n}", "func NewRetrier(strategies ...Strategy) Retrier {\n\treturn &retrier{\n\t\tstrategies: strategies,\n\t}\n}", "func New(lms chan mysignals.LifeSignal) *Person {\n\t// create new Person\n\tp := Person{\n\t\tid: newPersonID(),\n\t\tage: Age{\n\t\t\tvalue: 15,\n\t\t\tlock: sync.Mutex{},\n\t\t\tmaxage: 40,\n\t\t},\n\t\tsmartphone: smartphone.New(),\n\t\tlifemsgs: lms,\n\t\tengaged: engaged{\n\t\t\tvalue: false,\n\t\t\tlock: sync.Mutex{},\n\t\t},\n\t\t// use &brain.Brain{}\n\t\t// instead of brain.Brain{}\n\t\t// because Brain implements the interface DecisionMaker{} using a pointer receiver\n\t\t// \t\t\t(b* Brain)Method(...)\n\t\t// instead of a value receiver\n\t\t// \t\t\t(b Brain)Method(...)\n\t\tbrain: &brain.Brain{},\n\t\t// sex is M or F\n\t\tsex: func() byte {\n\t\t\tif utils.NewRandomIntInRange(0, 1) == 0 {\n\t\t\t\treturn 'M'\n\t\t\t}\n\t\t\treturn 'F'\n\t\t}(),\n\t}\n\t// start listening for signals\n\tgo (&p).listenForSignals()\n\t// return Person information\n\treturn &p\n}", "func NewBuildsIndividualTestersCreateToManyRelationshipRequest(server string, id string, body BuildsIndividualTestersCreateToManyRelationshipJSONRequestBody) (*http.Request, error) {\n\tvar bodyReader io.Reader\n\tbuf, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyReader = bytes.NewReader(buf)\n\treturn NewBuildsIndividualTestersCreateToManyRelationshipRequestWithBody(server, id, \"application/json\", bodyReader)\n}", "func NewComposite(t ...Type) *Composite {\n\tcomp := &Composite{}\n\tcomp.elems = append(comp.elems, t...)\n\treturn comp\n}", "func NewCombination(numbers []string, length int) (*Combination, error) {\n\tif length < 1 {\n\t\treturn nil, errors.New(\"Invalid combination length\")\n\t}\n\treturn &Combination{Numbers: shuffleAndExtract(numbers, length)}, nil\n}", "func New(questionsPath string, textPath string) *Truman {\n\tt := &Truman{}\n\n\tquestionsFilePath, _ := filepath.Abs(questionsPath)\n\ttextFilePath, _ := filepath.Abs(textPath)\n\n\tt.loadQuestions(questionsFilePath)\n\tt.loadText(textFilePath)\n\n\treturn t\n}", "func New() Model {\n\treturn Model{\n\t\tType: Arabic,\n\t\tPage: 0,\n\t\tPerPage: 1,\n\t\tTotalPages: 1,\n\t\tKeyMap: DefaultKeyMap,\n\t\tActiveDot: \"•\",\n\t\tInactiveDot: \"○\",\n\t\tArabicFormat: \"%d/%d\",\n\t}\n}", "func NewLearner(id int, nrOfNodes int, valueOut chan<- Value) *Learner {\n\treturn &Learner{\n\t\tid: id,\n\t\ttotal_nodes: nrOfNodes,\n\t\tquorum: (nrOfNodes / 2) + 1,\n\t\tchosenVal: ZeroValue,\n\t\tlearned: make(map[int]Learn, nrOfNodes),\n\t\tlearnIn: make(chan Learn),\n\t\tvalOut: valueOut,\n\t\tstop: make(chan bool),\n\t}\n}", "func New(enum enumerator) enumerator {\n\tenum.set(enum)\n\n\treturn enum\n}", "func NewRBAC(config *RBACConfig) (rbac *RBAC, err error) {\n\tr := cache.NewRedis(config.Redis)\n\td, err := db.Init(config.Mgo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trbac = &RBAC{\n\t\tCache: cache.NewPermissionDao(r, d),\n\t\tPermission: db.NewPermissionDao(d),\n\t\tRole: db.NewRoleDao(d),\n\t\tUser: db.NewUserDao(d),\n\t}\n\treturn\n}", "func (s *FeedbackService) CreateMultiFeedbackV1(\n\tctx context.Context,\n\treq *fb.CreateMultiFeedbackV1Request,\n) (*fb.CreateMultiFeedbackV1Response, error) {\n\n\tlog.Info().Msgf(\"Handle request for CreateMultiFeedbackV1: %v\", req)\n\n\tif err := req.Validate(); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument,\n\t\t\t\"request is invalid: %v\",\n\t\t\terr.Error())\n\t}\n\n\trootspan, spanctx := opentracing.StartSpanFromContext(ctx, \"CreateMultiFeedbackV1\")\n\tdefer rootspan.Finish()\n\n\tvar entities []models.Entity\n\tfor i := 0; i < len(req.Feedbacks); i++ {\n\t\tentities = append(entities, &models.Feedback{\n\t\t\tUserId: req.Feedbacks[i].UserId,\n\t\t\tClassroomId: req.Feedbacks[i].ClassroomId,\n\t\t\tComment: req.Feedbacks[i].Comment,\n\t\t})\n\t}\n\n\tchunks, err := utils.SplitSlice(entities, s.chunks)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tres := &fb.CreateMultiFeedbackV1Response{}\n\n\t// try to insert into database one chunk per transaction\n\t// if transaction fails, only those IDs which have been already added successfully\n\t// will be returned to the client\n\tfor i := 0; i < len(chunks); i++ {\n\t\tspan, _ := opentracing.StartSpanFromContext(spanctx, \"batch\")\n\n\t\taddedIds, err := s.repo.AddEntities(ctx, chunks[i]...)\n\t\tif err != nil {\n\t\t\tspan.LogFields(oplog.Uint64(\"batch size\", 0))\n\t\t\tspan.Finish()\n\t\t\treturn res, status.Errorf(codes.Internal, \"bulk insertion failed: %v\", err)\n\t\t}\n\t\tres.FeedbackId = append(res.FeedbackId, addedIds...)\n\n\t\tspan.LogFields(oplog.Uint64(\"batch size\", calculateSize(chunks[i]...)))\n\t\tspan.Finish()\n\n\t\tfor _, id := range addedIds {\n\t\t\ts.prod.SendEvent(producer.CreateEvent(producer.Create, id))\n\t\t\ts.prom.IncCreate()\n\t\t}\n\t}\n\treturn res, nil\n}", "func createBot(ctx *gin.Context) {\n\tbody := struct {\n\t\tName string `json:\"name\"`\n\t\tChildDirected bool `json:\"child_directed\"`\n\t\tLocale string `json:\"locale\"`\n\t\tAbortMessages []string `json:\"abort_messages\"`\n\t\tClarificationPrompts []string `json:\"clarification_prompts\"`\n\t}{}\n\tif err := ctx.Bind(&body); err != nil { //validation error\n\t\tctx.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error(), \"message\": \"Validation Error.\", \"data\": nil})\n\t} else {\n\t\tcred := credentials.NewStaticCredentials(os.Getenv(\"ACCESS_KEY_ID\"), os.Getenv(\"SECRET_ACCESS_KEY\"), \"\")\n\t\tconfig := aws.NewConfig().WithCredentials(cred).WithRegion(os.Getenv(\"AWS_REGION\"))\n\t\tsess := session.Must(session.NewSession(config))\n\t\tsvc := lexmodelbuildingservice.New(sess)\n\t\tvar clarificationPrompts []*lexmodelbuildingservice.Message\n\t\tfor _, val := range body.ClarificationPrompts {\n\t\t\tclarificationPrompts = append(clarificationPrompts, &lexmodelbuildingservice.Message{\n\t\t\t\tContent: aws.String(val),\n\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t})\n\t\t}\n\t\tvar abortMessages []*lexmodelbuildingservice.Message\n\t\tfor _, val := range body.AbortMessages {\n\t\t\tabortMessages = append(abortMessages, &lexmodelbuildingservice.Message{\n\t\t\t\tContent: aws.String(val),\n\t\t\t\tContentType: aws.String(\"PlainText\"),\n\t\t\t})\n\t\t}\n\t\t_, err = svc.PutBot(&lexmodelbuildingservice.PutBotInput{\n\t\t\tName: aws.String(body.Name),\n\t\t\tChildDirected: aws.Bool(body.ChildDirected),\n\t\t\tLocale: aws.String(body.Locale),\n\t\t\tClarificationPrompt: &lexmodelbuildingservice.Prompt{Messages: clarificationPrompts, MaxAttempts: aws.Int64(5)},\n\t\t\tAbortStatement: &lexmodelbuildingservice.Statement{Messages: abortMessages},\n\t\t})\n\t\tif err != nil {\n\t\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Server Error.\", \"data\": nil})\n\t\t} else {\n\t\t\t_, err := svc.PutBotAlias(&lexmodelbuildingservice.PutBotAliasInput{\n\t\t\t\tBotName: aws.String(body.Name),\n\t\t\t\tBotVersion: aws.String(\"$LATEST\"),\n\t\t\t\tName: aws.String(body.Name),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Server Error.\", \"data\": nil})\n\t\t\t} else {\n\t\t\t\tctx.JSON(http.StatusOK, gin.H{\"error\": nil, \"message\": \"New Bot Created.\", \"data\": nil})\n\t\t\t}\n\t\t}\n\t}\n}", "func NewMultipleDevice(total int64, devices []Device, ) *MultipleDevice {\n\tthis := MultipleDevice{}\n\tthis.Total = total\n\tthis.Devices = devices\n\treturn &this\n}" ]
[ "0.48868722", "0.4619283", "0.4487543", "0.4456285", "0.42859465", "0.41999", "0.41992977", "0.4195675", "0.4194431", "0.415553", "0.41500634", "0.41447544", "0.41297522", "0.41187063", "0.40561128", "0.40476024", "0.40391248", "0.40369943", "0.40235433", "0.4007433", "0.39862293", "0.3976484", "0.39475423", "0.39365304", "0.3930016", "0.39183837", "0.390873", "0.38943404", "0.38820913", "0.38756922", "0.38746992", "0.38675067", "0.3861412", "0.38548476", "0.3846219", "0.3834548", "0.38296998", "0.38268086", "0.38228515", "0.3822454", "0.38176975", "0.38118562", "0.3811659", "0.38057232", "0.38013506", "0.38006055", "0.37941664", "0.37848774", "0.37794432", "0.37766156", "0.37762028", "0.37683403", "0.3767425", "0.37648737", "0.37585545", "0.375621", "0.37561032", "0.3754847", "0.37374476", "0.37348893", "0.3732003", "0.37263557", "0.3693234", "0.36904943", "0.36854264", "0.3680273", "0.36685875", "0.36685243", "0.36665836", "0.36659062", "0.36618266", "0.36591652", "0.3651987", "0.36499545", "0.3647777", "0.36472568", "0.36471412", "0.3640555", "0.36349463", "0.363419", "0.36300337", "0.36274326", "0.3624371", "0.36230373", "0.36230344", "0.3621782", "0.36142316", "0.36071634", "0.35945857", "0.35774323", "0.3577408", "0.35717884", "0.35704657", "0.35690156", "0.35592678", "0.35582578", "0.35551563", "0.35537347", "0.35524684", "0.35516027" ]
0.755682
0
Load loads model from file or model name. It also updates default configuration parameters if provided. This method implements `PretrainedModel` interface.
func (mc *RobertaForMultipleChoice) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error { var urlOrFilename string // If modelName, infer to default configuration filename: if modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok { urlOrFilename = modelFile } else { // Otherwise, just take the input urlOrFilename = modelNameOrPath } cachedFile, err := util.CachedPath(urlOrFilename) if err != nil { return err } vs := nn.NewVarStore(device) p := vs.Root() mc.roberta = bert.NewBertModel(p.Sub("roberta"), config.(*bert.BertConfig)) mc.dropout = util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb) classifier := nn.NewLinear(p.Sub("classifier"), config.(*bert.BertConfig).HiddenSize, 1, nn.DefaultLinearConfig()) mc.classifier = classifier err = vs.Load(cachedFile) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load(fileName string, src interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tdecoder := gob.NewDecoder(file)\n\t\tif err = decoder.Decode(src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Restore parameters\n\tswitch src.(type) {\n\tcase Model:\n\t\tmodel := src.(Model)\n\t\tmodel.SetParams(model.GetParams())\n\tdefault:\n\t\treturn errors.New(\"the file is not a model dump\")\n\t}\n\treturn nil\n}", "func (mlm *RobertaForMaskedLM) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmlm.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmlm.lmHead = NewRobertaLMHead(p.Sub(\"lm_head\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sc *RobertaForSequenceClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tsc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tsc.classifier = NewRobertaClassificationHead(p.Sub(\"classifier\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Model) Load(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\tif err := json.Unmarshal(data, m); err != nil {\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\treturn nil\n}", "func Load(modelArchive string, framework Framework, flags ModelFlags) (*Model, error) {\n\tf, _ := os.Open(modelArchive)\n\tdefer f.Close()\n\tvar outDir string\n\tif fi, err := f.Stat(); err == nil && fi.IsDir() {\n\t\toutDir = modelArchive\n\t} else if err == nil && !fi.IsDir() {\n\t\ttmpDir := os.TempDir()\n\t\toutDir = filepath.Join(tmpDir, utils.PseudoUuid())\n\t\tif err := utils.Unzip(modelArchive, outDir); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to extract model archive: %v\", err)\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s does not exist\", modelArchive)\n\t}\n\n\tmodelFilename := filepath.Join(outDir, \"saved_model.pb\")\n\tif _, err := os.Stat(modelFilename); err != nil {\n\t\t// This if is here for when we can read pbtxt files\n\t\tif _, err2 := os.Stat(modelFilename + \"txt\"); err2 == nil {\n\t\t\tmodelFilename = modelFilename + \"txt\"\n\t\t\treturn nil, errors.New(\"Currently loading saved_model.pbtxt is not supported\")\n\t\t\t//comment the return when we can read pbtxt\n\t\t} else {\n\t\t\treturn nil, errors.New(\"saved_model.pb does not exist\")\n\t\t}\n\t}\n\n\tflags.ModelPath = outDir\n\tflags.ModelFile = modelFilename\n\tvar model Model\n\terr := framework.Load(&model, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &model, nil\n}", "func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tdropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tnumLabels := int64(len(config.(*bert.BertConfig).Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\ttc.roberta = roberta\n\ttc.dropout = dropout\n\ttc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (am *AssetManager) LoadModel(name, iname string) {\n\tif strings.Contains(name, \".obj\") {\n\t\tam.Models[iname] = NewWavefrontModelFromFile(am.modelsDir + name)\n\t} else {\n\t\tlog.Fatal(\"cannot find \" + name)\n\t}\n}", "func (qa *RobertaForQuestionAnswering) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\tqa.roberta = roberta\n\tqa.qaOutputs = qaOutputs\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(model interface{}, provider Provider, strict bool) error {\n\treturn load(model, provider, strict)\n}", "func LoadModel(r io.Reader) (Model, error) {\n\tdec := json.NewDecoder(r)\n\tvar m Model\n\tif err := dec.Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\tm.setWeightVec()\n\treturn m, nil\n}", "func Load(modelName string) (r *pb.TextResponse, err error) {\n\tif modelName == \"\" {\n\t\tmodelName = defaultModel\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tr, err = grpcClient.LoadModel(ctx, &pb.TextRequest{Text: modelName})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}", "func (s *DataStore) Load() error {\n\tfile, err := os.Open(s.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = json.NewDecoder(file).Decode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadModelFile(path string) (Model, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fp.Close()\n\treturn LoadModel(fp)\n}", "func Load(filename string) (*SvmModel, error) {\n\n\tcfn := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cfn))\n\n\tmdl := C.svm_load_model(cfn)\n\tif mdl == nil {\n\t\treturn nil, SvmError{Message: fmt.Sprintf(\"unable to load model file: %s\", filename)}\n\t}\n\n\treturn &SvmModel{object: mdl}, nil\n}", "func (wrapper *TvmWrapper) LoadModel(modelParam *ModelParam) (*moduleInfo, error) {\n\tdefer runtime.GC()\n\n\t// debug model parameters\n\tfmt.Print(modelParam.DebugStr())\n\n\t// load module library\n\tfmt.Print(\"start to load module library...\\n\")\n\tmodLibP, err := gotvm.LoadModuleFromFile(modelParam.ModelLibPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// read module json file\n\tfmt.Print(\"start to read module json file...\\n\")\n\tbytes, err := ioutil.ReadFile(modelParam.ModelJSONPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tmodJsonStr := string(bytes)\n\n\t// create graph module of tvm\n\tfmt.Print(\"start to create graph module of tvm...\\n\")\n\tfuncp, err := gotvm.GetGlobalFunction(\"tvm.graph_runtime.create\")\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t\treturn nil, err\n\t}\n\t// graph_runtime.create\n\t// arg[0] : model json text\n\t// arg[1] : model library\n\t// arg[2] : device type (ex. KDLCPU, KDLGPU...)\n\t// arg[3] : device id\n\tgraphrt, err := funcp.Invoke(modJsonStr, modLibP, wrapper.config.DeviceType, (int64)(0))\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tgraphmod := graphrt.AsModule()\n\n\t// import params to graph module\n\tfmt.Print(\"start to import params to graph module...\\n\")\n\tbytes, err = ioutil.ReadFile(modelParam.ModelParamsPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tfuncp, err = graphmod.GetFunction(\"load_params\")\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\t_, err = funcp.Invoke(bytes)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// create module information\n\tfmt.Print(\"start to create module information...\\n\")\n\tinfo := newModuleInfo(graphmod, modelParam.InputShape, modelParam.OutputShape)\n\treturn info, nil\n}", "func loadModel(modelName string) (multilayer.MultiLayerPerceptron, error) {\n\tf, err := os.Open(\"models/\" + modelName + \".model.gob\")\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, fmt.Errorf(\"failed opening model: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\n\tnn := multilayer.MultiLayerPerceptron{}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\terr = nn.UnmarshalBinary(data)\n\treturn nn, err\n}", "func (t *TOMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif t.Reader != nil {\n\t\tr = t.Reader\n\t} else if t.Path != \"\" {\n\t\tfile, err := getConfig(t.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tif _, err := toml.DecodeReader(r, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (env *Environment) LoadExistingModel(m string) *text.NaiveBayes {\n\t// get the classifier definition to make sure it is well defined\n\tclf := env.GetClassifierDefinition(m)\n\tclf.panicErrors()\n\n\tstreamChan := make(chan base.TextDatapoint, clf.TextChannelSize)\n\tmodel := clf.getModel(streamChan)\n\terr := model.RestoreFromFile(env.baseModelPath(clf.ModelOut))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn model\n}", "func Load(fileName string) (*openapi3.Swagger, error) {\n\tmodel, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = model.Validate(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"Loaded OpenAPI 3 Specification file:\", fileName)\n\treturn model, nil\n}", "func Load(r io.Reader) error {\n\treturn DefaultInstance.Load(r)\n}", "func (l *OptionalTOMLLoader) Load(s interface{}) error {\n\tif _, err := os.Stat(l.Path); err == nil {\n\t\treturn l.TOMLLoader.Load(s)\n\t}\n\treturn nil\n}", "func (e *CachedEnforcer) LoadModel() error {\n\tif e.autoClear {\n\t\tdefer e.InvalidateCache()\n\t}\n\treturn e.base.LoadModel()\n}", "func (c *IntentClassifier) Load(filePath string) error {\n\tlog.Printf(\"Loading Classifier from %s...\", filePath)\n\tmeta := persist.Load(filePath)\n\t//get the classifier current meta data\n\tname, version := c.getMeta()\n\tif meta.Name != name {\n\t\treturn fmt.Errorf(\"This file doesn't contain a KNearestNeighbors classifier\")\n\t}\n\tif meta.Version != version {\n\t\treturn fmt.Errorf(\"Can't understand this file format\")\n\t}\n\n\tdecoder := gob.NewDecoder(bytes.NewBuffer(meta.Data))\n\terr := decoder.Decode(&c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding RNN checkpoint file: %s\", err)\n\t}\n\n\tcheckpointFile = filePath\n\treturn nil\n}", "func (k *KMP) Load(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(b, k)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid load format, %s\", format)\n\t}\n\treturn err\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(filename string) (*Params, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar params Params\n\tif err := json.Unmarshal(file, &params); err != nil {\n\t\tlog.Printf(\"failed to parse %s: %s\", file, string(file))\n\t\treturn nil, err\n\t}\n\treturn &params, nil\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func (lm *LocalMeta) Load() error {\n\t// initialize gset\n\tvar err error\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, \"\")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfile, err := os.Open(lm.filename)\n\tif err != nil && !os.IsNotExist(errors.Cause(err)) {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif os.IsNotExist(errors.Cause(err)) {\n\t\treturn nil\n\t}\n\tdefer file.Close()\n\n\t_, err = toml.DecodeReader(file, lm)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, lm.BinlogGTID)\n\treturn errors.Trace(err)\n}", "func InitModel(modelDir string, modelFile string) *TfModel {\n\tmodelpath := filepath.Join(modelDir, modelFile)\n\tmodel, err := ioutil.ReadFile(modelpath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Construct an in-memory graph from the serialized form.\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toperations := graph.Operations()\n\tfor _, op := range operations {\n\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t}\n\t// Create a session for inference over graph.\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &TfModel{Model: &tf.SavedModel{Graph: graph, Session: session}}\n}", "func (e *Definition) Load(path, entity string) error {\n\n\tfullPath := filepath.Join(path, entity)\n\n\tb, err := ioutil.ReadFile(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontent := string(b)\n\te.json = jsonutil.NewFromString(content)\n\te.byteRead = 0\n\n\ts, err := schema.Read(e)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read schema: %s\", err)\n\t\treturn err\n\t}\n\n\te.schema = s\n\tv := validator.New(s)\n\te.validator = v\n\treturn nil\n}", "func Load(reader io.Reader, configuration interface{}) error {\n\tif err := FromYAML(reader, configuration); err != nil {\n\t\treturn err\n\t}\n\treturn FromEnv(configuration)\n}", "func Init(path string, tags []string) *TfModel {\n\tmodel, err := tf.LoadSavedModel(path, tags, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading Saved Model:%v\\n\", err.Error())\n\t\treturn nil\n\t}\n\toperations := model.Graph.Operations()\n\tfor _, op := range operations {\n\t\tname := op.Name()\n\t\tif strings.HasPrefix(name, \"sentence\") || strings.HasPrefix(name, \"dropout\") || strings.HasPrefix(name, \"inference\") {\n\t\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t\t}\n\t}\n\tlog.Println(\"op loading finished\")\n\treturn &TfModel{Model: model}\n}", "func Load(filename string, v interface{}) {\n\tParse(read(filename), v)\n}", "func (trm *TrmConfig) Load(pathTrm, pathVoice string) {\n\tfmt.Println(\"trm config load\")\n\ttrm.OpenJSON(pathTrm)\n\ttrm.OpenJSON(pathVoice)\n}", "func Load() error {\n\treturn def.Load()\n}", "func LoadModel(args ...interface{}) (*WordModel, error) {\n\tvar arg interface{}\n\tif len(args) == 0 {\n\t\targ = \"https://raw.githubusercontent.com/go-ego/gse/master/data/dict/dictionary.txt\"\n\t} else {\n\t\targ = args[0]\n\t}\n\n\tr, err := readerFromAnything(arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodel := NewWordModel()\n\n\tscanner := bufio.NewScanner(r)\n\tvar words []WordFreq\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, errors.New(\"Error: not enough fields\")\n\t\t}\n\t\tword := fields[0]\n\t\tfreq, _ := strconv.ParseFloat(fields[1], 32)\n\t\tif len([]rune(word)) < 2 {\n\t\t\t//freq = 2\n\t\t}\n\t\twords = append(words, WordFreq{\n\t\t\tWord: word,\n\t\t\tLogProbability: float32((freq)),\n\t\t})\n\t}\n\n\tsort.Slice(words, func(a, b int) bool {\n\t\treturn words[a].Word < words[b].Word\n\t})\n\n\tprev := \"\"\n\tfor _, word := range words {\n\t\tif word.Word == prev {\n\t\t\tcontinue\n\t\t}\n\t\tprev = word.Word\n\t\tmodel.AddWord(word.Word, word.LogProbability)\n\t}\n\n\tmodel.Finish()\n\n\treturn model, nil\n}", "func (self *LSHforest) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn msgpack.Unmarshal(b, self)\n}", "func Load() models.Language {\n\tif models.ConfigFile != \"\" {\n\t\tlangFile = models.ConfigFile\n\t} else {\n\t\tmodels.ConfigFile = langFile\n\t}\n\n\tlang := language.LoadLanguages(langFile)\n\treturn lang\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func Load(config interface{}, configPath string) error {\n\tswitch fileExtension(configPath) {\n\tcase \"yaml\":\n\t\treturn loadYaml(config, configPath)\n\tcase \"json\":\n\t\treturn loadJson(config, configPath)\n\tdefault:\n\t\treturn ero.Newf(\"Can not support load file %s\", configPath)\n\t}\n}", "func (lf LoaderFunc) Load(serverType string) (Input, error) {\n\treturn lf(serverType)\n}", "func Load(v interface{}, loadFrom string) error {\n\tcfg, err := ini.Load(loadFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.NameMapper = ini.TitleUnderscore\n\n\treturn cfg.MapTo(v)\n}", "func Load(filePath string, t Tomler) error {\n\ttomlValue := t.TOMLValue()\n\tvar err error\n\tif _, err = toml.DecodeFile(filePath, tomlValue); err != nil {\n\t\treturn err\n\t}\n\treturn t.FromTOML(tomlValue)\n}", "func (p *BaseProvider) Load() error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (b *baseLoader) Load(ctx context.Context, src *url.URL) (*Schema, error) {\n\t// open IO\n\tvar r io.ReadCloser\n\tswitch src.Scheme {\n\tcase \"file\":\n\t\tvar err error\n\t\tif r, err = os.Open(src.Path); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q from %q: %w\", src.Path, src, err)\n\t\t}\n\tcase \"http\", \"https\":\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, src.String(), nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create request for %q: %w\", src, err)\n\t\t}\n\t\tresp, err := b.client.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed requesting %q: %w\", src, err)\n\t\t}\n\t\tr = resp.Body\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme: %v\", src.Scheme)\n\t}\n\tdefer func() {\n\t\t_ = r.Close()\n\t}()\n\n\t// read and init schema\n\tvar s Schema\n\tif err := json.NewDecoder(r).Decode(&s); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding %q failed: %w\", src, err)\n\t}\n\tif s.ID == nil {\n\t\treturn nil, fmt.Errorf(\"no ID set on %q\", src)\n\t}\n\ts.calculateID()\n\ts.setSrc(src)\n\n\treturn &s, nil\n}", "func Load(path string) (*OBJFile, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\treturn Decode(in)\n}", "func (dto *GetAdapterModelResponse) Load(data base.ModelInterface) error {\n\tm, ok := data.(*model.AdapterModel)\n\tif !ok {\n\t\tlog.Error(\"GetAdapterModelResponse.Load() failed, convert interface failed.\")\n\t\treturn base.ErrorDataConvert\n\t}\n\tdto.GetResponse.Load(&m.Model)\n\tdto.Name = m.Name\n\tdto.Type = m.Type\n\tdto.Capability.Load(m.Capability)\n\treturn nil\n}", "func (l *Loader) LoadObjModel(file string) models.RawModel {\n\tdat, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvertices := make([]mgl32.Vec3, 0)\n\ttextures := make([]mgl32.Vec2, 0)\n\tnormals := make([]mgl32.Vec3, 0)\n\tvar verticesArray []float32\n\tvar texturesArray []float32\n\tvar normalsArray []float32\n\tindicesArray := make([]uint32, 0)\n\tlines := strings.Split(string(dat), \"\\n\")\n\tvar fStart int\n\tfor i, line := range lines {\n\t\tsplited := strings.Split(line, \" \")\n\t\tif len(splited) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := splited[0]\n\t\tif t == \"v\" {\n\t\t\tvertices = append(vertices, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vn\" {\n\t\t\tnormals = append(normals, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vt\" {\n\t\t\ttextures = append(textures, mgl32.Vec2{toFloat(splited[1]), toFloat(splited[2])})\n\t\t}\n\t\tif t == \"f\" {\n\t\t\tfStart = i\n\t\t\ttexturesArray = make([]float32, len(vertices)*2)\n\t\t\tnormalsArray = make([]float32, len(vertices)*3)\n\t\t\tverticesArray = make([]float32, len(vertices)*3)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor i := fStart; i < len(lines); i++ {\n\t\tsplited := strings.Split(lines[i], \" \")\n\t\tif len(splited) == 0 || splited[0] != \"f\" {\n\t\t\tbreak\n\t\t}\n\t\tvertex1 := strings.Split(splited[1], \"/\")\n\t\tvertex2 := strings.Split(splited[2], \"/\")\n\t\tvertex3 := strings.Split(splited[3], \"/\")\n\t\tindicesArray = processVertex(vertex1, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex2, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex3, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t}\n\tcolors := make([]float32, len(normalsArray))\n\tfor i := range colors {\n\t\tcolors[i] = 1\n\t}\n\treturn l.LoadToVAO(verticesArray, texturesArray, indicesArray, normalsArray, colors)\n}", "func (f *Flow) Load(cacheDir string) (err error) {\n\tif f.FlowFile == \"\" {\n\t\treturn nil\n\t}\n\tvar content []byte\n\tswitch getURLType(f.FlowFile) {\n\tcase \"local\":\n\t\tcontent, err = ioutil.ReadFile(f.FlowFile)\n\tcase \"web\":\n\t\tcontent, err = get(cacheDir, f.FlowFile)\n\t// TODO git - including the branch\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognised floe file type: <%s>\", f.FlowFile)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal into a flow\n\tnewFlow := &Flow{}\n\terr = yaml.Unmarshal(content, &newFlow)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up the flow, and copy bits into this flow\n\terr = newFlow.zero()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(newFlow.Name) != 0 {\n\t\tf.Name = newFlow.Name\n\t}\n\tf.ReuseSpace = newFlow.ReuseSpace\n\tif len(newFlow.HostTags) != 0 {\n\t\tf.HostTags = newFlow.HostTags\n\t}\n\tif len(newFlow.ResourceTags) != 0 {\n\t\tf.ResourceTags = newFlow.ResourceTags\n\t}\n\tif len(newFlow.Env) != 0 {\n\t\tf.Env = newFlow.Env\n\t}\n\tif len(newFlow.Tasks) != 0 {\n\t\tf.Tasks = newFlow.Tasks\n\t}\n\t// Pointless overriding triggers - as they are what caused this load\n\treturn nil\n}", "func (s *CommandLineSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.callback != nil {\n\t\treturn s.koanf.Load(posflag.ProviderWithFlag(s.flags, \".\", s.koanf, s.callback), nil)\n\t}\n\n\treturn s.koanf.Load(posflag.Provider(s.flags, \".\", s.koanf), nil)\n}", "func (s *YAMLFileSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.path == \"\" {\n\t\treturn errors.New(\"invalid yaml path source configuration\")\n\t}\n\n\treturn s.koanf.Load(file.Provider(s.path), yaml.Parser())\n}", "func Load(p string) (Spec, error) {\n\tvar spec Spec\n\n\tbuf, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to read file: %s - %w\", p, err)\n\t}\n\n\terr = yaml.Unmarshal(buf, &spec)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to parse spec: %s - %w\", p, err)\n\t}\n\n\tspec.Path = p\n\n\treturn spec, nil\n}", "func Load(config *Config) error {\n\treturn NewLoader(config).Load()\n}", "func Load(path string, target interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn load(formatter, data, target)\n}", "func Load(filepath string, config interface{}) error {\n\tmagazine := make(map[string]interface{})\n\tfileBytes, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := yaml.Unmarshal(fileBytes, &magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagazine = flatten(magazine)\n\tif err := applyEnv(magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagBytes, err := yaml.Marshal(bellows.Expand(magazine))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(magBytes, config)\n}", "func (m *SynapsesPersist) Load() {\n\tdataPath, err := filepath.Abs(m.relativePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teFile, err := os.Open(dataPath + m.file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer eFile.Close()\n\n\tbytes, err := ioutil.ReadAll(eFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(bytes, &m.Synapses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (defaultStorage) Load() error {\n\tpanic(noConfigStorage)\n}", "func (function *Function) Load() (err error) {\n\tdefinition, err := ioutil.ReadFile(function.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfunction.Definition = string(definition)\n\n\treturn\n}", "func Load(state *state.State, driverName string, name string, config map[string]string, logger logger.Logger, volIDFunc func(volType VolumeType, volName string) (int64, error), commonRulesFunc func() map[string]func(string) error) (Driver, error) {\n\t// Locate the driver loader.\n\tdriverFunc, ok := drivers[driverName]\n\tif !ok {\n\t\treturn nil, ErrUnknownDriver\n\t}\n\n\td := driverFunc()\n\terr := d.init(state, name, config, logger, volIDFunc, commonRulesFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (vm *BFVM) LoadFromString(source string) error {\n\treturn vm.LoadFromStream(strings.NewReader(source))\n}", "func (appConf *AppConf) Load(filename string, forceReload bool) (*AppConf, error){\n\t// appConf is load and force reload is false return direction\n\tif isLoad && !forceReload{\n\t\treturn appConf, nil\n\t}\n\tfilename, err := appConf.getEnvConfigPath(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = toml.DecodeFile(filename, appConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"使用配置文件: %s\", filename)\n\t// mark appConf as loaded\n\tisLoad = true\n\treturn appConf, nil\n}", "func (d *Datastore) Load() (Object, error) {\n\td.localLock.Lock()\n\tdefer d.localLock.Unlock()\n\n\t// clear Object first, as mapstructure's decoder doesn't have ZeroFields set to true for merging purposes\n\td.meta.Object = d.meta.Object[:0]\n\n\terr := d.kv.LoadConfig(d.meta)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = d.meta.unmarshall()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.meta.object, nil\n}", "func (ctx *AppContext) Load(env string) {\n\tlog.Println(\"Load app context\")\n\n\t// Load env specific config\n\tenvConfig := viper.Sub(env)\n\tctx.Env = env\n\tctx.ProjectID = envConfig.GetString(\"project_id\")\n\tctx.SuffixOfKind = envConfig.GetString(\"datastore.kind_suffix\")\n\tctx.EtcdServers = envConfig.GetStringSlice(\"etcd\")\n\n\t// Load common config\n\tctx.CommonConfig = viper.Sub(\"common\")\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tif err == nil {\n\t\tdecoder := json.NewDecoder(file)\n\t\terr = decoder.Decode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func Load() {\n\tvar err error\n\n\tconfLen := len(FilePath)\n\tif confLen != 0 {\n\t\terr = readFromJSON(FilePath)\n\t}\n\tif err == nil {\n\t\terr = readFromENV()\n\t}\n\tif err != nil {\n\t\tpanic(`Configuration not found. Please specify configuration`)\n\t}\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func TestDnn_LoadModel(t *testing.T) {\n\t//MODEL_PARAM=tmodel.pb,input_1,reshape_3/Reshape\n\tparam := os.Getenv(\"MODEL_PARAM\")\n\tif param == \"\" {\n\t\tt.Skip(\"Skipping model loading test; no MODEL_PARAM set\")\n\t\t//t.Error(\"no MODEL_PARAM set\")\n\t}\n\tstr2dnnfilter := func(inp string) VideoProfile {\n\t\tdnnfilter := VideoProfile{}\n\t\tstrs := strings.Split(inp, \",\")\n\t\tif len(strs) != 3 {\n\t\t\treturn dnnfilter\n\t\t}\n\t\tdnnfilter.Detector.ModelPath = strs[0]\n\t\tdnnfilter.Detector.Input = strs[1]\n\t\tdnnfilter.Detector.Output = strs[2]\n\t\treturn dnnfilter\n\t}\n\n\t_, dir := setupTest(t)\n\tdefer os.RemoveAll(dir)\n\n\tdnncfg := str2dnnfilter(param)\n\n\tif len(dnncfg.Detector.ModelPath) <= 0 || len(dnncfg.Detector.Input) <= 0 || len(dnncfg.Detector.Output) <= 0 {\n\t\tt.Errorf(\"invalid MODEL_PARAM set %v\", param)\n\t}\n\n\tdnnfilter := NewDnnFilter()\n\tdnnfilter.dnncfg = dnncfg\n\tif dnnfilter.InitDnnFilter(dnncfg) != true {\n\t\tt.Errorf(\"Can not load model file %v\", dnncfg.Detector.ModelPath)\n\t}\n\tdnnfilter.StopDnnFilter()\n}", "func (p *Puck) Load(name ...string) error {\n\tcmd := []byte(\"load();\\n\")\n\terr := p.command(name, cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *tomlLoader) Load(out interface{}) error {\n\tif _, err := toml.DecodeReader(l.r, out); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load(key string, data []byte) Entity {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tentity Entity\n\t)\n\n\tbuffer.Write(data)\n\tdecoder := gob.NewDecoder(&buffer)\n\tentityType := strings.Split(key, \".\")[0]\n\n\tswitch entityType {\n\tcase \"player\":\n\t\tentity = new(Player)\n\tcase \"planet\":\n\t\tentity = new(Planet)\n\tcase \"mission\":\n\t\tentity = new(Mission)\n\tcase \"sun\":\n\t\tentity = new(Sun)\n\tcase \"ss\":\n\t\tentity = new(SolarSlot)\n\tcase \"spy_report\":\n\t\tentity = new(SpyReport)\n\tdefault:\n\t\treturn nil\n\t}\n\tdecoder.Decode(entity)\n\treturn entity\n}", "func Load(r io.Reader, v interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSONLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\tif j.Reader != nil {\n\t\tr = j.Reader\n\t} else if j.Path != \"\" {\n\t\tfile, err := getConfig(j.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\treturn json.NewDecoder(r).Decode(s)\n}", "func (y *YAMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif y.Reader != nil {\n\t\tr = y.Reader\n\t} else if y.Path != \"\" {\n\t\tfile, err := getConfig(y.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(data, s)\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func (m *Method) TrainModel(c *gin.Context) {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(c.Request.Body)\n\tJSONStr := buf.String()\n\tm.GoPython(`ml.py`, JSONStr)\n\n\tvar response Response = Response{Status: `model training started`}\n\tc.JSON(http.StatusOK, response)\n}", "func (tfl tiltfileLoader) Load(ctx context.Context, tf *corev1alpha1.Tiltfile, prevResult *TiltfileLoadResult) TiltfileLoadResult {\n\tstart := time.Now()\n\tfilename := tf.Spec.Path\n\tabsFilename, err := ospath.RealAbs(tf.Spec.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn TiltfileLoadResult{\n\t\t\t\tConfigFiles: []string{filename},\n\t\t\t\tError: fmt.Errorf(\"No Tiltfile found at paths '%s'. Check out https://docs.tilt.dev/tutorial.html\", filename),\n\t\t\t}\n\t\t}\n\t\tabsFilename, _ = filepath.Abs(filename)\n\t\treturn TiltfileLoadResult{\n\t\t\tConfigFiles: []string{absFilename},\n\t\t\tError: err,\n\t\t}\n\t}\n\n\ttiltignorePath := watch.TiltignorePath(absFilename)\n\ttlr := TiltfileLoadResult{\n\t\tConfigFiles: []string{absFilename, tiltignorePath},\n\t}\n\n\ttiltignore, err := watch.ReadTiltignore(tiltignorePath)\n\n\t// missing tiltignore is fine, but a filesystem error is not\n\tif err != nil {\n\t\ttlr.Error = err\n\t\treturn tlr\n\t}\n\n\ttlr.Tiltignore = tiltignore\n\n\ts := newTiltfileState(ctx, tfl.dcCli, tfl.webHost, tfl.execer, tfl.k8sContextPlugin, tfl.versionPlugin,\n\t\ttfl.configPlugin, tfl.extensionPlugin, tfl.ciSettingsPlugin, feature.FromDefaults(tfl.fDefaults))\n\n\tmanifests, result, err := s.loadManifests(tf)\n\n\ttlr.BuiltinCalls = result.BuiltinCalls\n\ttlr.DefaultRegistry = s.defaultReg\n\n\t// All data models are loaded with GetState. We ignore the error if the state\n\t// isn't properly loaded. This is necessary for handling partial Tiltfile\n\t// execution correctly, where some state is correctly assembled but other\n\t// state is not (and should be assumed empty).\n\tws, _ := watch.GetState(result)\n\ttlr.WatchSettings = ws\n\n\t// NOTE(maia): if/when add secret settings that affect the engine, add them to tlr here\n\tss, _ := secretsettings.GetState(result)\n\ts.secretSettings = ss\n\n\tioState, _ := io.GetState(result)\n\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, ioState.Paths...)\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, s.postExecReadFiles...)\n\ttlr.ConfigFiles = sliceutils.DedupedAndSorted(tlr.ConfigFiles)\n\n\tdps, _ := dockerprune.GetState(result)\n\ttlr.DockerPruneSettings = dps\n\n\taSettings, _ := tiltfileanalytics.GetState(result)\n\ttlr.AnalyticsOpt = aSettings.Opt\n\n\ttlr.Secrets = s.extractSecrets()\n\ttlr.FeatureFlags = s.features.ToEnabled()\n\ttlr.Error = err\n\ttlr.Manifests = manifests\n\ttlr.TeamID = s.teamID\n\n\tobjectSet, _ := v1alpha1.GetState(result)\n\ttlr.ObjectSet = objectSet\n\n\tvs, _ := version.GetState(result)\n\ttlr.VersionSettings = vs\n\n\ttelemetrySettings, _ := telemetry.GetState(result)\n\ttlr.TelemetrySettings = telemetrySettings\n\n\tus, _ := updatesettings.GetState(result)\n\ttlr.UpdateSettings = us\n\n\tci, _ := cisettings.GetState(result)\n\ttlr.CISettings = ci\n\n\tconfigSettings, _ := config.GetState(result)\n\tif tlr.Error == nil {\n\t\ttlr.EnabledManifests, tlr.Error = configSettings.EnabledResources(tf, manifests)\n\t}\n\n\tduration := time.Since(start)\n\tif tlr.Error == nil {\n\t\ts.logger.Infof(\"Successfully loaded Tiltfile (%s)\", duration)\n\t}\n\textState, _ := tiltextension.GetState(result)\n\thashState, _ := hasher.GetState(result)\n\n\tvar prevHashes hasher.Hashes\n\tif prevResult != nil {\n\t\tprevHashes = prevResult.Hashes\n\t}\n\ttlr.Hashes = hashState.GetHashes()\n\n\ttfl.reportTiltfileLoaded(s.builtinCallCounts, s.builtinArgCounts, duration,\n\t\textState.ExtsLoaded, prevHashes, tlr.Hashes)\n\n\tif len(aSettings.CustomTagsToReport) > 0 {\n\t\treportCustomTags(tfl.analytics, aSettings.CustomTagsToReport)\n\t}\n\n\treturn tlr\n}", "func (k *Kluster) Load() error {\n\tif err := k.LoadSummary(); err != nil {\n\t\treturn err\n\t}\n\n\t// DEBUG:\n\t// fmt.Printf(\"DEBUG: cluster %s config version: %s\\tMin: %s\\tMax: %s\\n\", k.Name, k.Version, MinSemVersion, SemVersion)\n\n\tver, err := version.NewSemVer(k.Version)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"the cluster version (%s) is not well formed or not SemVer compliance. %s\", k.Version, err)\n\t}\n\tif ver.LT(MinSemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is not supported by this KubeKit, the minimun version supported is %s\", k.Version, MinVersion)\n\t}\n\tif ver.GT(SemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is greater than the cluster version supported by this KubeKit (%s)\", k.Version, Version)\n\t}\n\n\tk.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tname := k.Platform()\n\tconfig := k.Platforms[name]\n\n\tcred, err := k.GetCredentials()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tplatform, err := provisioner.NewPlatform(name, k.Name, config, cred, k.ui, k.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.provisioner[name] = platform\n\n\treturn nil\n}", "func (c *Info) Load() error {\n\tb, err := ioutil.ReadFile(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Lock()\n\terr = json.Unmarshal(b, c)\n\tc.Unlock()\n\n\treturn err\n}", "func Load(filename string) (*Beam, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treader := bufio.NewReader(f)\n\tdecoder := json.NewDecoder(reader)\n\tdecoder.DisallowUnknownFields()\n\tcfg := new(Beam)\n\t// This **Beam double-pointer appears to be required to detect an invalid\n\t// input of \"null\". See Test_Load/file_contains_null test.\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding JSON value in %v: %v\", filename, err)\n\t}\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"loading %v resulted in nil config\", filename)\n\t}\n\tif decoder.More() {\n\t\treturn nil, fmt.Errorf(\"found unexpected data after config in %v\", filename)\n\t}\n\treturn cfg, nil\n}", "func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}", "func (s *Startup) Load() error {\n\n\t// TODO: parameterize startup config file name\n\tjsonFile, err := ioutil.ReadFile(\"startup.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(jsonFile, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil // no error\n}", "func (component *Component) Load(filename string) error {\n\treturn util.LoadYAML(filename, component)\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func (s *EnvironmentSource) Load(_ *schema.StructValidator) (err error) {\n\tkeyMap, ignoredKeys := getEnvConfigMap(schema.Keys, s.prefix, s.delimiter)\n\n\treturn s.koanf.Load(env.ProviderWithValue(s.prefix, constDelimiter, koanfEnvironmentCallback(keyMap, ignoredKeys, s.prefix, s.delimiter)), nil)\n}", "func Load(filename string, data any, validation bool) error {\n\tisJSON := strings.HasSuffix(filename, \".json\")\n\n\tbs, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif validation {\n\t\terr := validate(bs, data, isJSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn unmarshal(bs, data, isJSON)\n}", "func Load(env string) *Configuration {\n\t_, filePath, _, _ := runtime.Caller(0)\n\tconfigName := \"config.\" + env + \".yaml\"\n\tconfigPath := filePath[:len(filePath)-9] + \"files\" + string(filepath.Separator)\n\n\tviper.SetConfigName(configName)\n\tviper.AddConfigPath(configPath)\n\tviper.SetConfigType(\"yaml\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Configuration\n\tviper.Unmarshal(&config)\n\tsetGinMode(config.Server.Mode)\n\n\treturn &config\n}", "func Load(path string) (*LevelDB, error) {\n\treturn LoadWithOptions(path, DefaultOptions)\n}", "func Load(name string, data interface{}) error {\n\tp := jsonPath(name)\n\t// Don't load anything if the file doesn't exist\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"File %s didn't exist, loading with fresh data\\n\", p)\n\t\treturn nil\n\t}\n\n\t// Read and unmarshal the json\n\tif b, err := ioutil.ReadFile(p); err != nil {\n\t\treturn err\n\t} else if len(b) == 0 {\n\t\tlog.Printf(\"File %s was empty, loading with fresh data\\n\", p)\n\t\treturn nil\n\t} else if err := json.Unmarshal(b, data); err != nil {\n\t\treturn fmt.Errorf(\"failed to load file %s error: %s\", p, err)\n\t}\n\n\tlog.Printf(\"Loaded %s\\n\", p)\n\treturn nil\n}", "func (rs *Restake) LoadProto(pbAct *iotextypes.StakeRestake) error {\n\tif pbAct == nil {\n\t\treturn ErrNilProto\n\t}\n\n\trs.bucketIndex = pbAct.GetBucketIndex()\n\trs.payload = pbAct.GetPayload()\n\trs.duration = pbAct.GetStakedDuration()\n\trs.autoStake = pbAct.GetAutoStake()\n\n\treturn nil\n}", "func (config *Config) Load() error {\n\tvar env string\n\tflag.StringVar(&env, \"env\", \"dev\", \"environment\")\n\n\tflag.Parse()\n\n\tviperRegistry := viper.New()\n\tviperRegistry.AddConfigPath(\"./config\")\n\tviperRegistry.SetConfigName(env)\n\tviperRegistry.SetConfigType(\"json\")\n\tviperRegistry.SetEnvPrefix(\"todo\")\n\tviperRegistry.AutomaticEnv()\n\n\tconfig.Env = env\n\n\tif err := viperRegistry.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureApplication(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureDB(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureAuth(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (wlt *Wallet) Load(dir string) error {\n\tr := &ReadableWallet{}\n\tif err := r.Load(filepath.Join(dir, wlt.GetFilename())); err != nil {\n\t\treturn err\n\t}\n\tr.Meta[\"filename\"] = wlt.GetFilename()\n\t*wlt = NewWalletFromReadable(r)\n\treturn nil\n}", "func Load(filepath string, startTag, endTag string, vars map[string]string) (result string, err error) {\n\tvar data []byte\n\tif data, err = ioutil.ReadFile(filepath); err == nil {\n\t\tvar tpl *Engine\n\t\tif tpl, err = New(string(data), startTag, endTag); err == nil {\n\t\t\tif result, err = tpl.Process(vars); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if err == errs.TmplVarsNotFoundError {\n\t\t\terr = nil\n\t\t\tresult = string(data)\n\t\t}\n\t}\n\treturn\n}", "func (l *Loader) Load(cfg *config.Config) {\n\tcfg.Address = os.Getenv(\"BRCEP_ADDRESS\")\n\tcfg.LogLevel = os.Getenv(\"BRCEP_LOG_LEVEL\")\n\tcfg.PreferredAPI = os.Getenv(\"BRCEP_PREFERRED_API\")\n\tcfg.ViaCepURL = os.Getenv(\"BRCEP_VIACEP_URL\")\n\tcfg.CepAbertoURL = os.Getenv(\"BRCEP_CEPABERTO_URL\")\n\tcfg.CepAbertoToken = os.Getenv(\"BRCEP_CEPABERTO_TOKEN\")\n\tcfg.CorreiosURL = os.Getenv(\"BRCEP_CORREIOS_URL\")\n}", "func Load(cfg interface{}, configPath string) error {\n\tif err := readConfigFile(configPath, cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ClusterState == nil {\n\t\tcfg.ClusterState = &ClusterState{}\n\t}\n\tif cfg.ALBIngressController == nil {\n\t\tcfg.ALBIngressController = &ALBIngressController{}\n\t}\n\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.ClusterState.UpTook != \"\" {\n\t\tcfg.ClusterState.upTook, err = time.ParseDuration(cfg.ClusterState.UpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif cfg.ALBIngressController.IngressUpTook != \"\" {\n\t\tcfg.ALBIngressController.ingressUpTook, err = time.ParseDuration(cfg.ALBIngressController.IngressUpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}" ]
[ "0.70856375", "0.6942267", "0.691719", "0.67702013", "0.6714875", "0.6647788", "0.6632438", "0.6570047", "0.6427433", "0.6367626", "0.63450754", "0.6210927", "0.62089187", "0.6141275", "0.6126932", "0.5932069", "0.59089965", "0.5824516", "0.5803706", "0.57926947", "0.56931376", "0.5685074", "0.56759435", "0.5629026", "0.5624409", "0.55188453", "0.5496034", "0.549438", "0.5485185", "0.5469166", "0.54661906", "0.5462454", "0.544723", "0.5436073", "0.54302883", "0.54199696", "0.5392638", "0.5384862", "0.53777784", "0.53655183", "0.53620535", "0.5341112", "0.5309845", "0.5309004", "0.5252267", "0.5244161", "0.5244161", "0.52102965", "0.5200908", "0.5191221", "0.51873565", "0.5179895", "0.517651", "0.5174189", "0.5173903", "0.51596195", "0.5154276", "0.51491684", "0.5142233", "0.51373446", "0.51358354", "0.51347655", "0.5117462", "0.5103656", "0.510187", "0.5097216", "0.50966686", "0.50809854", "0.50709903", "0.5022858", "0.50180924", "0.5016142", "0.50149995", "0.5002425", "0.49866006", "0.4971974", "0.4967155", "0.49617535", "0.4960292", "0.4955598", "0.49451393", "0.49449015", "0.49324843", "0.4930584", "0.4926257", "0.4920262", "0.49176425", "0.4904417", "0.4903159", "0.4899459", "0.48970014", "0.48836428", "0.48743317", "0.48730356", "0.48698953", "0.48682275", "0.48675355", "0.48576903", "0.48446506", "0.4835371" ]
0.6931012
2
ForwardT forwards pass through the model.
func (mc *RobertaForMultipleChoice) ForwardT(inputIds, mask, tokenTypeIds, positionIds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) { numChoices := inputIds.MustSize()[1] inputIdsSize := inputIds.MustSize() flatInputIds := inputIds.MustView([]int64{-1, inputIdsSize[len(inputIdsSize)-1]}, false) flatPositionIds := ts.None if positionIds.MustDefined() { positionIdsSize := positionIds.MustSize() flatPositionIds = positionIds.MustView([]int64{-1, positionIdsSize[len(positionIdsSize)-1]}, false) } flatTokenTypeIds := ts.None if tokenTypeIds.MustDefined() { tokenTypeIdsSize := tokenTypeIds.MustSize() flatTokenTypeIds = tokenTypeIds.MustView([]int64{-1, tokenTypeIdsSize[len(tokenTypeIdsSize)-1]}, false) } flatMask := ts.None if mask.MustDefined() { flatMaskSize := flatMask.MustSize() flatMask = mask.MustView([]int64{-1, flatMaskSize[len(flatMaskSize)-1]}, false) } var pooledOutput *ts.Tensor _, pooledOutput, hiddenStates, attentions, err = mc.roberta.ForwardT(flatInputIds, flatMask, flatTokenTypeIds, flatPositionIds, ts.None, ts.None, ts.None, train) if err != nil { return ts.None, nil, nil, err } appliedDO := pooledOutput.ApplyT(mc.dropout, train) appliedCls := appliedDO.Apply(mc.classifier) output = appliedCls.MustView([]int64{-1, numChoices}, true) appliedDO.MustDrop() return output, hiddenStates, attentions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mod *backendModule) Forward(f *gatepb.Forward) error {\n\treturn mod.send(proto.Type(f.Typ), f)\n}", "func (m *Model) Forward(qkv attention.QKV) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: m.Key.Forward(qkv.Keys...),\n\t\tValues: m.Value.Forward(qkv.Values...),\n\t}\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (m *Model) Forward(x *Node, states States) (rv *Node, err error) {\n\trv = x\n\tfor _, l := range m.Layers {\n\t\tif rv, err = l.Forward(rv, states); err != nil {\n\t\t\treturn nil, errors.Wrap(err, l.Name())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\th := nn.Affine(g, m.B, m.W, x)\n\tif yPrev != nil {\n\t\th = g.Add(h, g.Prod(m.WRec, yPrev))\n\t}\n\ts.Y = g.Invoke(m.Activation, h)\n\treturn\n}", "func (obj *Doc) Forward(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"Forward\", nil)\n\treturn err\n}", "func (t *Type) ForwardType() *ForwardType", "func (ch *RobertaClassificationHead) ForwardT(hiddenStates *ts.Tensor, train bool) *ts.Tensor {\n\tappliedDO1 := hiddenStates.MustSelect(1, 0, false).ApplyT(ch.dropout, train)\n\tappliedDense := appliedDO1.Apply(ch.dense)\n\ttanhTs := appliedDense.MustTanh(false)\n\tappliedDO2 := tanhTs.ApplyT(ch.dropout, train)\n\tretVal := appliedDO2.Apply(ch.outProj)\n\n\tappliedDO1.MustDrop()\n\tappliedDense.MustDrop()\n\ttanhTs.MustDrop()\n\tappliedDO2.MustDrop()\n\n\treturn retVal\n}", "func (f *Forwarder) Forward(data *call.CallData) {\n\tf.transferAgents.Range(func(key interface{}, value interface{}) bool {\n\t\tstreamId := key.(userid.ID)\n\t\tstream := value.(TransferAgent)\n\t\tif streamId == userid.ID(data.UserId) { // Don't need to forward data back to sender\n\t\t\treturn true\n\t\t}\n\n\t\tif err := stream.Send(data); err != nil {\n\t\t\tf.logger.Error(err)\n\t\t}\n\n\t\treturn true\n\t})\n}", "func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Ensure our request client does not follow redirects\n\thttpClient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tif config.TLS != nil {\n\t\ttlsConfig, err := config.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\ttracing.SetErrorAndDebugLog(r, \"Unable to configure TLS to call %s. Cause %s\", config.Address, err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(http.MethodGet, config.Address, http.NoBody)\n\ttracing.LogRequest(tracing.GetSpan(r), forwardReq)\n\tif err != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause %s\", config.Address, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteHeader(r, forwardReq, config.TrustForwardHeader)\n\n\ttracing.InjectRequestHeaders(forwardReq)\n\n\tforwardResponse, forwardErr := httpClient.Do(forwardReq)\n\tif forwardErr != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause: %s\", config.Address, forwardErr)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbody, readError := ioutil.ReadAll(forwardResponse.Body)\n\tif readError != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error reading body %s. Cause: %s\", config.Address, readError)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer forwardResponse.Body.Close()\n\n\t// Pass the forward response's body and selected headers if it\n\t// didn't return a response within the range of [200, 300).\n\tif forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {\n\t\tlog.Debugf(\"Remote error %s. StatusCode: %d\", config.Address, forwardResponse.StatusCode)\n\n\t\tutils.CopyHeaders(w.Header(), forwardResponse.Header)\n\t\tutils.RemoveHeaders(w.Header(), forward.HopHeaders...)\n\n\t\t// Grab the location header, if any.\n\t\tredirectURL, err := forwardResponse.Location()\n\n\t\tif err != nil {\n\t\t\tif err != http.ErrNoLocation {\n\t\t\t\ttracing.SetErrorAndDebugLog(r, \"Error reading response location header %s. Cause: %s\", config.Address, err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if redirectURL.String() != \"\" {\n\t\t\t// Set the location in our response if one was sent back.\n\t\t\tw.Header().Set(\"Location\", redirectURL.String())\n\t\t}\n\n\t\ttracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)\n\t\tw.WriteHeader(forwardResponse.StatusCode)\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tfor _, headerName := range config.AuthResponseHeaders {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tr.Header.Del(headerKey)\n\t\tif len(forwardResponse.Header[headerKey]) > 0 {\n\t\t\tr.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)\n\t\t}\n\t}\n\n\tr.RequestURI = r.URL.RequestURI()\n\tnext(w, r)\n}", "func (q *CQPU) forward(predicate []*pbUtils.AttributePredicate, streamRec *pbQPU.ResponseStreamRecord, streamOut pbQPU.QPU_QueryServer, seqID *int64, respond bool) error {\n\tif respond {\n\t\terr := streamOut.Send(\n\t\t\tprotoutils.ResponseStreamRecord(\n\t\t\t\t*seqID,\n\t\t\t\tstreamRec.GetType(),\n\t\t\t\tstreamRec.GetLogOp(),\n\t\t\t))\n\t\t(*seqID)++\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Transaction) forwardTransaction() {\n\tif t.tx == nil {\n\t\tpanic(\"tx is nil while forward was being called\")\n\t}\n\tselect {\n\tcase t.sendTxFound <- t.tx:\n\tcase <-t.shutdown:\n\t\treturn\n\t}\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\ts.InG = g.Sigmoid(nn.Affine(g, m.BIn, m.WIn, x, m.WInRec, yPrev))\n\ts.ForG = g.Sigmoid(nn.Affine(g, m.BFor, m.WFor, x, m.WForRec, yPrev))\n\ts.Cand = g.Tanh(g.Mul(m.WCand, x))\n\ts.Y = g.Prod(s.InG, s.Cand)\n\tif yPrev != nil {\n\t\ts.Y = g.Add(s.Y, g.Prod(g.Tanh(yPrev), s.ForG))\n\t}\n\treturn\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func (rt *Router) forward() {\n\tfor i, v := range rt.InInterfaceL {\n\t\t//pktS := \"\"\n\n\t\t// TRYE\n\t\t// get packet from interface i\n\t\tif pktS, err := v.Get(); err == nil {\n\t\t\t//fmt.Println(\"in routher forward, packet from Get(): \", pktS)\n\t\t\t// if packet exists make a forwarding decision\n\t\t\tp, err := FromByteS(pktS)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not get packet\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// HERE you will need to implement a lookup into the\n\t\t\t// forwarding table to find the appropriate outgoing interface\n\t\t\t// for now we assume the outgoing interface is also i\n\t\t\tfmt.Printf(\"%s: forwarding packet %s from interface %d to %d with mtu %d\\n\", rt.Str(), p.Str(), i, i, rt.OutInterfaceL[i].Mtu)\n\n\t\t\tif err = rt.OutInterfaceL[i].Put(p.ToByteS(), false); err != nil {\n\t\t\t\t//log.Printf(\"Could not put packet %s in router %s, into outInterface %d. Error: %s\", p.str, rt.forward, i, err)\n\t\t\t\tlog.Printf(\"%s: packet '%s' lost on interface %d\\n\", rt.Str(), i)\n\t\t\t}\n\t\t}\n\t\t//log.Println(\"no packet to forard in router\")\n\t}\n}", "func (ph *Handler) Forward() {\n\terr := recover()\n\tph.forward(err)\n}", "func (tr *Peer) FastForward(ctx context.Context, target string,\n\treq *FastForwardRequest, resp *FastForwardResponse) error {\n\n\tif tr.isShutdown() {\n\t\treturn ErrTransportStopped\n\t}\n\n\ttr.wg.Add(1)\n\tdefer tr.wg.Done()\n\n\treturn tr.fastForward(ctx, target, req, resp)\n}", "func (inst *instance) Forward(port int) (string, error) {\n\tvar reply proxyrpc.ForwardResult\n\terr := inst.ProxyApp.Call(\n\t\t\"ProxyVM.Forward\",\n\t\tproxyrpc.ForwardParams{\n\t\t\tID: inst.ID,\n\t\t\tPort: port,\n\t\t},\n\t\t&reply)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reply.ManagerAddress, nil\n}", "func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tlabels = sc.classifier.ForwardT(hiddenState, train)\n\thiddenState.MustDrop()\n\n\treturn labels, hiddenStates, attentions, nil\n}", "func (tc *RobertaForTokenClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := tc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := hiddenState.ApplyT(tc.dropout, train)\n\toutput = appliedDO.Apply(tc.classifier)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tg := m.Graph()\n\thalfSize := xs[0].Value().Size() / 2\n\n\tres := make([]ag.Node, len(xs))\n\tgate := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tres[i] = g.View(x, 0, 0, halfSize, 1)\n\t\tgate[i] = g.View(x, halfSize, 0, halfSize, 1)\n\t}\n\n\tgate = m.Norm.Forward(gate...)\n\tgate = m.Proj.Forward(gate...)\n\n\tif m.Act != nil {\n\t\tgate = m.Act.Forward(gate...)\n\t}\n\n\ty := make([]ag.Node, len(gate))\n\tfor i := range y {\n\t\ty[i] = g.Prod(gate[i], res[i])\n\t}\n\treturn y\n}", "func (a *provisionApp) forward(app *App, args ...interface{}) error {\n\tvar units uint\n\tif len(args) > 0 {\n\t\tswitch args[0].(type) {\n\t\tcase int:\n\t\t\tunits = uint(args[0].(int))\n\t\tcase int64:\n\t\t\tunits = uint(args[0].(int64))\n\t\tcase uint:\n\t\t\tunits = args[0].(uint)\n\t\tcase uint64:\n\t\t\tunits = uint(args[0].(uint64))\n\t\tdefault:\n\t\t\tunits = 1\n\t\t}\n\t}\n\terr := Provisioner.Provision(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif units > 1 {\n\t\t_, err = Provisioner.AddUnits(app, units-1)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Model) Forward(cache Cache, q, x []mat.Tensor) ([]mat.Tensor, []mat.Tensor, Cache) {\n\tvar pk, pv mat.Tensor\n\n\tpq := m.Query.Forward(q...)\n\n\tif hasCache := cache.HasValues(); hasCache && m.IsCrossAttention {\n\t\tpk = cache[0]\n\t\tpv = cache[1]\n\t} else {\n\t\tk := m.Key.Forward(x...)\n\t\tv := m.Value.Forward(x...)\n\n\t\tif hasCache {\n\t\t\tpk = ag.AppendRows(cache[0], k...)\n\t\t\tpv = ag.AppendRows(cache[1], v...)\n\t\t} else {\n\t\t\tpk = ag.Stack(k...)\n\t\t\tpv = ag.Stack(v...)\n\t\t}\n\t}\n\n\tresult, weights := attention.ScaledDotProductAttention(pq, pk, pv, m.ScaleFactor, m.UseCausalMask)\n\n\treturn result, weights, Cache{pk, pv}\n}", "func (b *TestDriver) Forward(val int) error {\n\tlog.Printf(\"Forward: %d\", val)\n\n\treturn nil\n}", "func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train)\n\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tpredictionScores := mlm.lmHead.Forward(hiddenState)\n\n\treturn predictionScores, allHiddenStates, allAttentions, nil\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func (rh *RobertaLMHead) Forward(hiddenStates *ts.Tensor) *ts.Tensor {\n\tgelu := util.NewGelu()\n\tappliedDense := hiddenStates.Apply(rh.dense)\n\tgeluFwd := gelu.Fwd(appliedDense)\n\tappliedLN := geluFwd.Apply(rh.layerNorm)\n\tappliedDecoder := appliedLN.Apply(rh.decoder)\n\tappliedBias := appliedDecoder.MustAdd(rh.bias, true)\n\n\tgeluFwd.MustDrop()\n\tappliedDense.MustDrop()\n\tappliedLN.MustDrop()\n\n\treturn appliedBias\n}", "func (ti *TimeIndex) iterForward(t time.Time) index.Iter {\n i := ti.IndexNear(t)\n return &forwardIter{\n at: i,\n ti: ti,\n }\n}", "func (req *RequestData) Forward(client *http.Client, config BasketConfig, basket string) (*http.Response, error) {\n\tforwardURL, err := url.ParseRequestURI(config.ForwardURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid forward URL: %s - %s\", config.ForwardURL, err)\n\t}\n\n\t// expand path\n\tif config.ExpandPath && len(req.Path) > len(basket)+1 {\n\t\tforwardURL.Path = expandURL(forwardURL.Path, req.Path, basket)\n\t}\n\n\t// append query\n\tif len(req.Query) > 0 {\n\t\tif len(forwardURL.RawQuery) > 0 {\n\t\t\tforwardURL.RawQuery += \"&\" + req.Query\n\t\t} else {\n\t\t\tforwardURL.RawQuery = req.Query\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(req.Method, forwardURL.String(), strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create forward request: %s\", err)\n\t}\n\n\t// copy headers\n\tfor header, vals := range req.Header {\n\t\tfor _, val := range vals {\n\t\t\tforwardReq.Header.Add(header, val)\n\t\t}\n\t}\n\t// headers cleanup\n\tforwardHeadersCleanup(forwardReq)\n\t// set do not forward header\n\tforwardReq.Header.Set(DoNotForwardHeader, \"1\")\n\n\t// forward request\n\tresponse, err := client.Do(forwardReq)\n\tif err != nil {\n\t\t// HTTP issue during forwarding - HTTP 502 Bad Gateway\n\t\tlog.Printf(\"[warn] failed to forward request for basket: %s - %s\", basket, err)\n\t\tbadGatewayResp := &http.Response{\n\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(\"Failed to forward request: %s\", err)))}\n\t\tbadGatewayResp.Header.Set(\"Content-Type\", \"text/plain\")\n\n\t\treturn badGatewayResp, nil\n\t}\n\n\treturn response, nil\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (l *AffineLayer) Forward(x mat.Matrix) mat.Matrix {\n\t_, c := x.Dims()\n\tif c != l.dimIn {\n\t\tpanic(fmt.Sprintf(\"expect %d but got %d\", l.dimIn, c))\n\t}\n\tl.x = x\n\tvar ret mat.Dense\n\tret.Mul(x, l.Weight)\n\tret.Apply(func(i, j int, val float64) float64 {\n\t\treturn l.Bias.At(j, 0) + val\n\t}, &ret)\n\treturn &ret\n}", "func (r *Lachesis) FastForward(\n\treq *net.FastForwardRequest, resp *net.FastForwardResponse) error {\n\tresult, err := r.process(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, ok := result.(*net.FastForwardResponse)\n\tif !ok {\n\t\treturn ErrBadResult\n\t}\n\t*resp = *item\n\treturn nil\n}", "func (n *Network) Forward() {\n\tif !n.constructed() {\n\t\tlog.Panic(\"Cannot run an emtpy Network\")\n\t}\n\n\tfor l := range n.layers {\n\t\tcandy.Must(parallel.For(0, len(n.layers[l]), 1, func(g int) {\n\t\t\tgate := n.layers[l][g]\n\t\t\tgate.forward(gate)\n\t\t}))\n\t}\n}", "func (m *Linear) Forward(x mat.Tensor) mat.Tensor {\n\treturn ag.Add(ag.Mul(m.W, x), m.B)\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (a *insertApp) forward(app *App, args ...interface{}) error {\n\tapp.State = \"pending\"\n\treturn db.Session.Apps().Insert(app)\n}", "func (o *OutboundDispatcher) Forward(msg interface{}, des *service.Destination) error {\n\tfor _, v := range o.outboundTransports {\n\t\tif !v.AcceptRecipient(des.RecipientKeys) {\n\t\t\tif !v.Accept(des.ServiceEndpoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treq, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed marshal to bytes: %w\", err)\n\t\t}\n\n\t\t_, err = v.Send(req, des)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send msg using outbound transport: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no outbound transport found for serviceEndpoint: %s\", des.ServiceEndpoint)\n}", "func (m *Model) StepForward(ns Nodes) (rv Nodes, err error) {\n\tstates := States{}\n\tvar tmp *Node\n\tfor _, x := range ns {\n\t\tif tmp, err = m.Forward(x, states); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trv = append(rv, tmp)\n\t}\n\treturn rv, nil\n}", "func (c *ManetConnection) forward(bytes []byte) {\n\tincomingHeader := data.PacketHeaderFromBytes(bytes)\n\n\tcached := c.inCache(incomingHeader.SequenceNumber, incomingHeader.SendKey)\n\tfmt.Println(\"CACHE: \", incomingHeader.SequenceNumber, incomingHeader.SendKey, cached)\n\n\tif cached || incomingHeader.TTL <= 1 {\n\t\tfmt.Println(\"DROP!\")\n\t\treturn\n\t}\n\n\tc.cache[incomingHeader.SequenceNumber] = incomingHeader.SendKey\n\tdelete(c.cache, incomingHeader.SequenceNumber-cacheDepth)\n\n\toutgoingHeader := &data.PacketHeader{\n\t\tSourceAddress: incomingHeader.SourceAddress,\n\t\tDestinationAddress: incomingHeader.DestinationAddress,\n\t\tPreviousHop: GetMyAddress(),\n\t\tTTL: incomingHeader.TTL - 1,\n\t\tPacketType: incomingHeader.PacketType,\n\t\tSequenceNumber: incomingHeader.SequenceNumber,\n\t\tNumBytes: incomingHeader.NumBytes,\n\t\tSendKey: incomingHeader.SendKey,\n\t}\n\n\tfor i, b := range outgoingHeader.ToBytes() {\n\t\tbytes[i] = b\n\t}\n\n\tfor neighbor := range myNeighbors {\n\t\tif neighbor == incomingHeader.PreviousHop {\n\t\t\tcontinue\n\t\t}\n\t\traddr := ToUDPAddr(neighbor)\n\t\tfmt.Println(\"FORWARD to\", neighbor, \"DEST: \", incomingHeader.DestinationAddress, \"aka\", raddr)\n\t\tif _, err := c.conn.WriteToUDP(bytes, raddr); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (s *Service) Forward(topicID, msgID, targetAddr, text string) error {\n\tpayload := map[string]interface{}{\n\t\t\"id\": msgID,\n\t\t\"address\": targetAddr,\n\t\t\"text\": text,\n\t}\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpf, err := s.client.Publish(topicID, b, 2, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pf.Wait(5 * time.Second)\n}", "func (r *RotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := Rotate(fx, r.angle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (b *BaseController) Forward(title, templateName string) {\n\tb.Layout = filepath.Join(prefixNg, \"layout.htm\")\n\tb.TplName = filepath.Join(prefixNg, templateName)\n\tb.Data[\"Title\"] = b.Tr(title)\n\tb.LayoutSections = make(map[string]string)\n\tb.LayoutSections[\"HeaderInclude\"] = filepath.Join(prefixNg, viewPath, \"header-include.htm\")\n\n\tif b.UseCompressedJS {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-min-include.htm\")\n\t} else {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-include.htm\")\n\t}\n\n\tlog.Debugf(\"Loaded HeaderScriptInclude file: %s\", b.LayoutSections[\"HeaderScriptInclude\"])\n\n\tb.LayoutSections[\"FooterInclude\"] = filepath.Join(prefixNg, viewPath, \"footer-include.htm\")\n\tb.LayoutSections[\"HeaderContent\"] = filepath.Join(prefixNg, viewPath, \"header-content.htm\")\n\tb.LayoutSections[\"FooterContent\"] = filepath.Join(prefixNg, viewPath, \"footer-content.htm\")\n\n}", "func (lay *Layer) Forward(x *mat.Dense) (a *mat.Dense) {\n\t// x is (n x in )\n\trow, _ := x.Dims()\n\n\txx := new(mat.Dense)\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\tz.Apply(func(i, j int, v float64) float64 { return lay.act.f(v) }, z)\n\treturn z\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tys := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = m.forward(x)\n\t}\n\treturn ys\n}", "func processForward(forward *chproto.ChangeForward) {\n\n\t// If we are already trying to forward a change forward message with\n\t// the same requesting node and request ID, discard this message.\n\tif _, exists := getForwardTimeout(uint16(*forward.Request.RequestNode),\n\t\t*forward.Request.RequestId); exists {\n\t\treturn\n\t}\n\n\t// Everything else in this function runs in a transaction.\n\t// We are read-only.\n\tstore.StartTransaction()\n\tdefer store.EndTransaction()\n\n\t// If this is a core node and this node stopped being leader less than\n\t// a Change Timeout Period ago, always add us to the ignore list.\n\tif config.IsCore() && !isIgnored(forward, config.Id()) {\n\t\tdiff := time.Now().Sub(store.StoppedLeading())\n\t\tif diff < config.CHANGE_TIMEOUT_PERIOD {\n\t\t\tforward.Ignores = append(forward.Ignores,\n\t\t\t\tuint32(config.Id()))\n\t\t}\n\t}\n\n\t// If all core node IDs are in the forward's ignore list, discard it.\n\tif len(forward.Ignores) == len(config.CoreNodes()) {\n\t\tlog.Print(\"shared/chrequest: dropped msg due to full ignores\")\n\t\treturn\n\t}\n\n\t// Otherwise, choose a potential leader node.\n\t// This is O(n^2) in the number of core nodes,\n\t// but we don't expect to have many.\n\tchosenNode := uint16(0)\n\t_, leader := store.Proposal()\n\tif leader != 0 && !isIgnored(forward, leader) {\n\t\tchosenNode = leader\n\t} else {\n\t\tfor _, node := range config.CoreNodes() {\n\t\t\tif !isIgnored(forward, node) {\n\t\t\t\tchosenNode = node\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif chosenNode == 0 {\n\t\t// Shouldn't happen.\n\t\tlog.Print(\"shared/chrequest: bug, \" +\n\t\t\t\"couldn't find candidate leader node\")\n\t\treturn\n\t}\n\n\t// If we are the selected leader, construct an external change request,\n\t// and send it on our change request channel.\n\tif chosenNode == config.Id() {\n\t\tintRequest := forward.Request\n\t\tchrequest := new(store.ChangeRequest)\n\t\tchrequest.RequestEntity = *intRequest.RequestEntity\n\t\tchrequest.RequestNode = uint16(*intRequest.RequestNode)\n\t\tchrequest.RequestId = *intRequest.RequestId\n\t\tchrequest.Changeset = make([]store.Change,\n\t\t\tlen(intRequest.Changeset))\n\n\t\tfor i, ch := range intRequest.Changeset {\n\t\t\tchrequest.Changeset[i].TargetEntity = *ch.TargetEntity\n\t\t\tchrequest.Changeset[i].Key = *ch.Key\n\t\t\tchrequest.Changeset[i].Value = *ch.Value\n\t\t}\n\n\t\tfor _, cb := range changeCallbacks {\n\t\t\tcb(chrequest)\n\t\t}\n\n\t\treturn\n\t}\n\n\t// Otherwise, we send it on to the selected leader,\n\t// add the selected leader to the ignore list,\n\t// and set a timeout to retry.\n\tsendForward(chosenNode, forward)\n\tforward.Ignores = append(forward.Ignores, uint32(chosenNode))\n\taddForwardTimeout(forward)\n}", "func (f *Forward) Forward(state request.Request) (*dns.Msg, error) {\n\tif f == nil {\n\t\treturn nil, ErrNoForward\n\t}\n\n\tfails := 0\n\tvar upstreamErr error\n\tfor _, proxy := range f.List() {\n\t\tif proxy.Down(f.maxfails) {\n\t\t\tfails++\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// All upstream proxies are dead, assume healtcheck is complete broken and randomly\n\t\t\t// select an upstream to connect to.\n\t\t\tproxy = f.List()[0]\n\t\t}\n\n\t\tret, err := proxy.Connect(context.Background(), state, f.opts)\n\n\t\tret, err = truncated(state, ret, err)\n\t\tupstreamErr = err\n\n\t\tif err != nil {\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if the reply is correct; if not return FormErr.\n\t\tif !state.Match(ret) {\n\t\t\treturn state.ErrorMessage(dns.RcodeFormatError), nil\n\t\t}\n\n\t\treturn ret, err\n\t}\n\n\tif upstreamErr != nil {\n\t\treturn nil, upstreamErr\n\t}\n\n\treturn nil, ErrNoHealthy\n}", "func (r *LeakyReLU[O]) Forward() (mat.Tensor, error) {\n\treturn r.x.Value().(mat.Matrix).ApplyWithAlpha(leakyReLU, r.alpha.Value().Item().F64()), nil\n}", "func (s *Server) Forward(id int64, event api.Event) {\n\tif event.Type == \"logging\" {\n\t\t// Parse the message\n\t\tlogEntry := api.EventLogging{}\n\t\terr := json.Unmarshal(event.Metadata, &logEntry)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && logEntry.Level == \"dbug\" {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && !s.verbose && logEntry.Level == \"info\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := s.broadcast(event, true)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to forward event from member %d: %v\", id, err)\n\t}\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func (t *TimeLine) forward(num, denom uint32, runCallbacks bool) {\n\tend := t.cursor + t.Ticks(num, denom)\n\tif runCallbacks {\n\t\tt.lastDelta = t.runCallbacks(t.cursor, end)\n\t}\n\tt.cursor = end\n}", "func (la *Lattice) Forward(m TokenizeMode) {\n\tfor i, size := 1, len(la.list); i < size; i++ {\n\t\tcurrentList := la.list[i]\n\t\tfor index, target := range currentList {\n\t\t\tprevList := la.list[target.Start]\n\t\t\tif len(prevList) == 0 {\n\t\t\t\tla.list[i][index].Cost = maximumCost\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j, n := range prevList {\n\t\t\t\tvar c int16\n\t\t\t\tif n.Class != USER && target.Class != USER {\n\t\t\t\t\tc = la.dic.Connection.At(int(n.Right), int(target.Left))\n\t\t\t\t}\n\t\t\t\ttotalCost := int64(c) + int64(target.Weight) + int64(n.Cost)\n\t\t\t\tif m != Normal {\n\t\t\t\t\ttotalCost += int64(additionalCost(n))\n\t\t\t\t}\n\t\t\t\tif totalCost > maximumCost {\n\t\t\t\t\ttotalCost = maximumCost\n\t\t\t\t}\n\t\t\t\tif j == 0 || int32(totalCost) < la.list[i][index].Cost {\n\t\t\t\t\tla.list[i][index].Cost = int32(totalCost)\n\t\t\t\t\tla.list[i][index].prev = la.list[target.Start][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (g *game) forward() {\n\tg.player.Parse(g.input)\n\n\tif g.player.IsQuitting() {\n\t\tg.next = g.newMenu()\n\t}\n}", "func (m *EventItemRequestBuilder) Forward()(*i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.ForwardRequestBuilder) {\n return i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.NewForwardRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (fl *follow) forward(r io.Reader) (cont bool) {\n\tfl.Decoder.Reset(r)\n\treturn fl.Forwarder.Do(fl.Watcher, fl.Decoder)\n}", "func (b *RequiredArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) ArgumentNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tif p.RequiresFullSeq() {\n\t\treturn p.fullSeqForward(xs)\n\t}\n\treturn p.incrementalForward(xs)\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tif len(xs) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tmean := ag.ReduceMean(x)\n\t\tdev := ag.SubScalar(x, mean)\n\t\tstdDev := ag.Sqrt(ag.Add(ag.ReduceMean(ag.Square(dev)), m.Eps))\n\t\tout[i] = ag.Add(ag.Prod(ag.DivScalar(dev, stdDev), m.W), m.B)\n\t}\n\treturn out\n}", "func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {\n\tlState := makeFBOLockState()\n\tfbo.headLock.RLock(lState)\n\tdefer fbo.headLock.RUnlock(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t// We're already up to date.\n\t\treturn\n\t}\n\tif !fbo.hasBeenCleared {\n\t\t// No reason to fast-forward here if it hasn't ever been\n\t\t// cleared.\n\t\treturn\n\t}\n\n\tfbo.forcedFastForwards.Add(1)\n\tfbo.goTracked(func() {\n\t\tdefer fbo.forcedFastForwards.Done()\n\t\tctx, cancelFunc := fbo.newCtxWithFBOID()\n\t\tdefer cancelFunc()\n\n\t\tfbo.log.CDebugf(ctx, \"Forcing a fast-forward\")\n\t\tvar currHead ImmutableRootMetadata\n\t\tvar err error\n\tgetMD:\n\t\tfor i := 0; ; i++ {\n\t\t\tcurrHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)\n\t\t\tswitch errors.Cause(err).(type) {\n\t\t\tcase nil:\n\t\t\t\tbreak getMD\n\t\t\tcase kbfsmd.ServerErrorUnauthorized:\n\t\t\t\t// The MD server connection might not be authorized\n\t\t\t\t// yet, so give it a few chances to go through.\n\t\t\t\tif i > 5 {\n\t\t\t\t\tfbo.log.CDebugf(ctx,\n\t\t\t\t\t\t\"Still unauthorized for TLF %s; giving up fast-forward\",\n\t\t\t\t\t\tfbo.id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i == 0 {\n\t\t\t\t\tfbo.log.CDebugf(\n\t\t\t\t\t\tctx, \"Got unauthorized error when fast-forwarding %s; \"+\n\t\t\t\t\t\t\t\"trying again after a delay\", fbo.id())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tdefault:\n\t\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif currHead == (ImmutableRootMetadata{}) {\n\t\t\tfbo.log.CDebugf(ctx, \"No MD yet\")\n\t\t\treturn\n\t\t}\n\t\tfbo.log.CDebugf(ctx, \"Current head is revision %d\", currHead.Revision())\n\n\t\tlState := makeFBOLockState()\n\t\t// Kick off partial prefetching once the latest merged\n\t\t// revision is set.\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tfbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)\n\t\t\t}\n\t\t}()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\tfbo.headLock.Lock(lState)\n\t\tdefer fbo.headLock.Unlock(lState)\n\n\t\tif !fbo.hasBeenCleared {\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t\tfbo.hasBeenCleared = false\n\t\t\t}\n\t\t}()\n\n\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t// We're already up to date.\n\t\t\tfbo.log.CDebugf(ctx, \"Already up-to-date: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = fbo.doFastForwardLocked(ctx, lState, currHead)\n\t\tif err != nil {\n\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %v\", err)\n\t\t}\n\t})\n}", "func (p *Player) Forward() mgl32.Vec3 {\n\treturn p.Speed\n}", "func (n *Node) Forward() FloatXX {\n\tif n.myoutCached {\n\t\treturn n.myout\n\t}\n\n\tif n.myType == InputNode {\n\t\tn.myout = n.inputValue\n\t} else {\n\t\tn.myout = FloatXX(0.0)\n\t\tfor index, otherNode := range n.inputNodes {\n\t\t\toutput := otherNode.Forward()\n\t\t\tn.inputs = append(n.inputs, output)\n\t\t\tn.myout += n.weights[index] * output\n\t\t}\n\t\tn.myout += n.biasValue * n.biasWeight\n\t\tmyoutActivated := n.activation(n.myout)\n\t\tn.myout = myoutActivated\n\t}\n\n\tn.myoutCached = true\n\treturn n.myout\n}", "func (r *Sub[O]) Forward() (mat.Tensor, error) {\n\treturn r.x1.Value().(mat.Matrix).Sub(r.x2.Value().(mat.Matrix)), nil\n}", "func httpForward(store *ForwardStore) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tkey := mux.Vars(r)[\"uid\"]\n\t\tif key == \"\" {\n\t\t\tkey = \"0\"\n\t\t}\n\t\tforward, _ := store.get(key)\n\t\thttp.Redirect(w, r, forward.URL, 302)\n\t}\n}", "func Forward() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\terr := recover() // Have to do recover directly in deferred function\n\tinternalPanicHandler.forward(err)\n}", "func (ms *MVCCStats) Forward(nowNanos int64) {\n\tif ms.LastUpdateNanos >= nowNanos {\n\t\treturn\n\t}\n\tms.AgeTo(nowNanos)\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func (qa *RobertaForQuestionAnswering) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (startScores, endScores *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := qa.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, ts.None, nil, nil, err\n\t}\n\n\tsequenceOutput := hiddenState.Apply(qa.qaOutputs)\n\tlogits := sequenceOutput.MustSplit(1, -1, true)\n\tstartScores = logits[0].MustSqueeze1(-1, false)\n\tendScores = logits[1].MustSqueeze1(-1, false)\n\n\tfor _, x := range logits {\n\t\tx.MustDrop()\n\t}\n\n\treturn startScores, endScores, hiddenStates, attentions, nil\n}", "func (r *Redirect) Forward(conn net.Conn) {\n\tif conn == nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\trequest = []byte{}\n\t\trequestTmp = make([]byte, 1024)\n\t)\n\n\tfor {\n\t\tn, err := conn.Read(requestTmp)\n\t\tif err != nil {\n\t\t\tr.reply(conn, nil, \"\", err)\n\t\t\treturn\n\t\t}\n\t\trequest = append(request, requestTmp[:n]...)\n\t\tif n < 1024 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(request)))\n\n\tif err != nil {\n\t\tr.reply(conn, nil, \"\", err)\n\t\treturn\n\t}\n\n\tu, err := url.Parse(string(req.RequestURI[1:]))\n\tif err != nil {\n\t\tr.reply(conn, req, \"\", err)\n\t\treturn\n\t}\n\treq.URL = u\n\treq.Host = u.Host\n\n\treq.RequestURI = \"\"\n\trequestObj := r.requestPool.Get().(*RequestWrapper)\n\trequestObj.CreatedTime = time.Now()\n\trequestObj.request = req\n\trequestObj.TryCount = 0\n\trequestObj.ID = r.makeID()\n\n\tif !r.putTask(requestObj, false) {\n\t\tr.reply(conn, req, \"\", errors.New(\"request put into buffer timeout\"))\n\t\treturn\n\t}\n\n\tr.reply(conn, req, requestObj.ID, nil)\n}", "func (s *Service) forwardToLeader(w http.ResponseWriter, req *http.Request) {\n\turl, err := url.Parse(s.RaftConfig.RaftNodeConfig.NodeProtocol + req.RequestURI)\n\tif err != nil {\n\t\tpanic(\"parse leader host url failed: \" + err.Error())\n\t}\n\turl.Host = s.raftNode.GetLeaderHost()\n\n\t// without leader, then return special error\n\tif url.Host == \"\" {\n\t\trpc.ReplyErr(w, apierrors.CodeNoLeader, apierrors.ErrNoLeader.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"forward url: %v\", url)\n\n\tproxy := httpproxy.ReverseProxy{\n\t\tDirector: func(request *http.Request) {\n\t\t\trequest.URL = url\n\t\t},\n\t}\n\n\tproxy.ServeHTTP(w, req)\n}", "func forwardBox(ctx *Context, t *Tuple, w Writer) error {\n\tw.Write(ctx, t)\n\treturn nil\n}", "func (a *createBucketIam) forward(app *App, args ...interface{}) error {\n\tenv, err := createBucket(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _ := config.GetString(\"host\")\n\tenvVars := []bind.EnvVar{\n\t\t{Name: \"APPNAME\", Value: app.Name},\n\t\t{Name: \"TSURU_HOST\", Value: host},\n\t}\n\tvariables := map[string]string{\n\t\t\"ENDPOINT\": env.endpoint,\n\t\t\"LOCATIONCONSTRAINT\": strconv.FormatBool(env.locationConstraint),\n\t\t\"ACCESS_KEY_ID\": env.AccessKey,\n\t\t\"SECRET_KEY\": env.SecretKey,\n\t\t\"BUCKET\": env.bucket,\n\t}\n\tfor name, value := range variables {\n\t\tenvVars = append(envVars, bind.EnvVar{\n\t\t\tName: fmt.Sprintf(\"TSURU_S3_%s\", name),\n\t\t\tValue: value,\n\t\t\tInstanceName: s3InstanceName,\n\t\t})\n\t}\n\tapp.SetEnvsToApp(envVars, false, true)\n\treturn nil\n}", "func (v *SourceSearchContext) Forward(iter *gtk.TextIter) (*gtk.TextIter, *gtk.TextIter, bool, bool) {\n\n\tstart, end := new(gtk.TextIter), new(gtk.TextIter)\n\tvar hasWrappedAround C.gboolean\n\n\tc := C.gtk_source_search_context_forward(\n\t\tv.native(),\n\t\tnativeTextIter(iter),\n\t\tnativeTextIter(start),\n\t\tnativeTextIter(end),\n\t\t&hasWrappedAround)\n\n\treturn start, end, gobool(hasWrappedAround), gobool(c)\n}", "func (r *Threshold[O]) Forward() (mat.Tensor, error) {\n\ty := r.x.Value().(mat.Matrix).ApplyWithAlpha(\n\t\tthreshold,\n\t\tr.threshold.Value().Item().F64(),\n\t\tr.k.Value().Item().F64(),\n\t)\n\treturn y, nil\n}", "func (m *NN) Forward(x *gorgonia.Node) (err error) {\n\tl := make([]*gorgonia.Node, len(m.W)+1)\n\tldot := make([]*gorgonia.Node, len(m.W))\n\tp := make([]*gorgonia.Node, len(m.W))\n\n\t// initial the first layer\n\tl[0] = x\n\n\t// W X + B\n\tfor i := 0; i < len(m.W); i++ {\n\t\tif len(m.B) != 0 && i < len(m.W) {\n\t\t\tL1, err := gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(l[i].Shape(), m.W[i].Shape())\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tldot[i], err = gorgonia.BroadcastAdd(L1, m.B[i], nil, []byte{0})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tldot[i], err = gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"mul wrong \", err)\n\t\t\t}\n\t\t}\n\n\t\t// Dropout\n\t\tp[i], err = gorgonia.Dropout(ldot[i], m.D[i])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Can't drop!\")\n\t\t}\n\n\t\t//activation function\n\t\tl[i+1] = gorgonia.Must(m.A[i](p[i]))\n\t}\n\n\tm.Pred = gorgonia.Must(m.A[len(m.A)-1](l[len(l)-1]))\n\tgorgonia.Read(m.Pred, &m.PredVal)\n\treturn\n}", "func Forward(bus EventBus) EventHandler {\n\treturn Handler(func(evt Event) error {\n\t\tbus.Publish(evt)\n\t\treturn nil\n\t})\n}", "func forwardTlcAck(gossiperPtr *core.Gossiper, ack *core.TLCAck) {\n\n\tif ack.HopLimit == 0 {\n\t\t// if we have reached the HopLimit, drop the message\n\t\treturn\n\t}\n\n\tgossiperPtr.DestinationTable.DsdvLock.Lock()\n\tforwardingAddress := gossiperPtr.DestinationTable.Dsdv[ack.Destination]\n\tgossiperPtr.DestinationTable.DsdvLock.Unlock()\n\t// If current node has no information about next hop to the destination in question\n\tif strings.Compare(forwardingAddress, \"\") == 0 {\n\t\t// TODO: What to do if there is no 'next hop' known when peer has to forward a private packet\n\t}\n\n\t// Decrement the HopLimit right before forwarding the packet\n\tack.HopLimit--\n\t// Encode and send packet\n\tpacketToSend := core.GossipPacket{Ack: ack}\n\tpacketBytes, err := protobuf.Encode(&packetToSend)\n\thelpers.HandleErrorFatal(err)\n\tcore.ConnectAndSend(forwardingAddress, gossiperPtr.Conn, packetBytes)\n}", "func (m *ItemCalendarsItemCalendarViewEventItemRequestBuilder) Forward()(*ItemCalendarsItemCalendarViewItemForwardRequestBuilder) {\n return NewItemCalendarsItemCalendarViewItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func httpSetForward(store *ForwardStore) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tf := &Forward{}\n\n\t\tif r.Body == nil {\n\t\t\thttp.Error(w, \"No Post body\", 400)\n\t\t\treturn\n\t\t}\n\n\t\terr := json.NewDecoder(r.Body).Decode(f)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\n\t\tnewForward := store.set(f)\n\t\tjson.NewEncoder(w).Encode(newForward)\n\t}\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (re *RandomEqualize) Forward(x *ts.Tensor) *ts.Tensor {\n\tr := randPvalue()\n\tvar out *ts.Tensor\n\tswitch {\n\tcase r < re.pvalue:\n\t\tout = equalize(x)\n\tdefault:\n\t\tout = x.MustShallowClone()\n\t}\n\n\treturn out\n}", "func (p *ProcType) FastForward(rev int64) *ProcType {\n\treturn p.Dir.Snapshot.fastForward(p, rev).(*ProcType)\n}", "func (d *Dispatcher) HandleForward(address string, h ForwardDial) {\n\td.forwards[address] = h\n}", "func (b *LiteralArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) LiteralNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (rr *RandRotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := RandomRotate(fx, rr.minAngle, rr.maxAngle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func Forward(in, out Link) rules.Rule {\n\treturn rules.Rule(fmt.Sprintf(\n\t\t\"-t filter -A fw-interfaces -j ACCEPT -i %v -o %v\",\n\t\tin.Name(), out.Name()))\n}", "func forward(backend *Backend, local *net.TCPConn, remote *net.TCPConn) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tlogDebug(\"<%s> Start transfer %s to %s\", remote.RemoteAddr(), local.LocalAddr(), remote.LocalAddr())\n\tgo copy_half(backend, local, remote, &wg)\n\tgo copy_half(backend, remote, local, &wg)\n\twg.Wait()\n\tlogDebug(\"<%s> Finished transfer from %s to %s done\", remote.RemoteAddr(), local.LocalAddr(), remote.LocalAddr())\n}", "func (n Neuron) FeedForward(previous_layer Layer) {\n sum := 0.0\n\n // Sum outputs from the previous layer.\n for _, neuron := range previous_layer {\n // TODO: there may be duplication issues here\n sum += neuron.output * neuron.output_weights[n.index].weight\n }\n\n n.output = n.Activation(sum)\n}", "func (matrix Matrix4) Forward() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[2][0],\n\t\tmatrix[2][1],\n\t\tmatrix[2][2],\n\t}.Unit()\n}", "func forwardRequest(originatorAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte, toNode Node) {\n\tif self.Addr.String() == toNode.Addr.String() {\n\t\tfmt.Println(\"Stop. Can't forward to self - \", toNode.Addr.String())\n\t\treturn\n\t}\n\n\tsendRequestToNode(msgID, reqPay, &toNode)\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tlength := len(xs)\n\tqs := p.query.Forward(xs...)\n\tks := make([]ag.Node, length)\n\tvs := p.value.Forward(xs...)\n\tmapk := make(map[int]*IndexedNodes)\n\tmapv := make(map[int]*IndexedNodes)\n\n\t// TODO: can it be implemented in a concurrent fashion?\n\tfor i, q := range qs {\n\t\tnorm := p.Graph.Sqrt(p.Graph.ReduceSum(p.Graph.Pow(q, 2.0)))\n\t\tks[i] = p.Graph.DivScalar(q, norm) // Euclidean norm\n\t\th := p.getHash(ks[i].Value().(*mat.Dense))\n\t\tinsertNode(mapk, ks[i], i, h)\n\t\tinsertNode(mapv, vs[i], i, h)\n\t}\n\n\tcontext := make([]ag.Node, length)\n\tprob := make([]mat.Matrix, length)\n\tfor i, q := range qs {\n\t\tj := p.getHash(q.Value().(*mat.Dense))\n\t\tc, p := p.lshScaledDotProductAttention(p.Graph, q, mapk[j], mapv[j], length, p.scaleFactor)\n\t\tcontext[i], prob[i] = c, p\n\t}\n\n\tp.Attention = &ContextProb{\n\t\tcontext: context,\n\t\tprob: prob,\n\t}\n\treturn context\n}", "func (q Quat) Forward() Vec3f {\n\treturn q.RotateVec(Vec3f{0, 0, -1})\n}", "func Forward(b Branch, distance float64) Branch {\n\tvar b_new Branch\n\tb_new.phase = b.phase\n\tb_new.xy = b.xy + cmplx.Rect(distance, b.phase)\n\treturn b_new\n}", "func (n *MLP) forward(x mat.Matrix) (as, zs []mat.Matrix) {\n\tas = append(as, x) // first activation is input\n\n\t_x := x\n\n\tfor i := 0; i < len(n.weights); i++ {\n\t\tw := n.weights[i]\n\t\tb := n.biases[i]\n\n\t\tdot := new(mat.Dense)\n\t\tdot.Mul(_x, w)\n\n\t\tz := new(mat.Dense)\n\t\taddB := func(_, col int, v float64) float64 { return v + b.At(col, 0) }\n\t\tz.Apply(addB, dot)\n\n\t\ta := new(mat.Dense)\n\t\ta.Apply(applySigmoid, z)\n\n\t\tzs = append(zs, z)\n\t\tas = append(as, a)\n\n\t\t_x = a\n\t}\n\n\treturn\n}", "func (c *chrono) Forward(skew time.Duration) {\n\tc.skew = skew\n}", "func (b *Brain) Forward(inputArray []float64) int {\r\n\tb.ForwardPasses++\r\n\tb.LastInputArray = inputArray // back this up\r\n\r\n\t// create network input\r\n\tvar (\r\n\t\tnetInput []float64\r\n\t\taction int\r\n\t)\r\n\tif b.ForwardPasses > b.TemporalWindow {\r\n\t\t// we have enough to actually do something reasonable\r\n\t\tnetInput = b.NetInput(inputArray)\r\n\r\n\t\tif b.Learning {\r\n\t\t\t// compute epsilon for the epsilon-greedy policy\r\n\t\t\tb.Epsilon = math.Min(1.0, math.Max(b.EpsilonMin, 1.0-float64(b.Age-b.LearningStepsBurnin)/float64(b.LearningStepsTotal-b.LearningStepsBurnin)))\r\n\t\t} else {\r\n\t\t\tb.Epsilon = b.EpsilonTestTime // use test-time value\r\n\t\t}\r\n\r\n\t\trf := b.Rand.Float64()\r\n\t\tif rf < b.Epsilon {\r\n\t\t\t// choose a random action with epsilon probability\r\n\t\t\taction = b.RandomAction()\r\n\t\t} else {\r\n\t\t\t// otherwise use our policy to make decision\r\n\t\t\taction, _ = b.Policy(netInput)\r\n\t\t}\r\n\t} else {\r\n\t\t// pathological case that happens first few iterations\r\n\t\t// before we accumulate window_size inputs\r\n\t\tnetInput = nil\r\n\t\taction = b.RandomAction()\r\n\t}\r\n\r\n\t// remember the state and action we took for backward pass\r\n\tcopy(b.NetWindow, b.NetWindow[1:])\r\n\tb.NetWindow[len(b.NetWindow)-1] = netInput\r\n\tcopy(b.StateWindow, b.StateWindow[1:])\r\n\tb.StateWindow[len(b.StateWindow)-1] = inputArray\r\n\tcopy(b.ActionWindow, b.ActionWindow[1:])\r\n\tb.ActionWindow[len(b.ActionWindow)-1] = action\r\n\r\n\treturn action\r\n}", "func ResetForwardContext(ctx context.Context) context.Context {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\tlog.Error(\"failed to get forwarding metadata\")\n\t}\n\tmd.Set(ForwardMetadataKey, \"\")\n\treturn metadata.NewOutgoingContext(ctx, md)\n}", "func (xf *HttpEchoTransfer) Forward() (inbytes uint64, outbytes uint64, err error) {\n\txf.m.Lock()\n\tdefer xf.m.Unlock()\n\tif xf.forwarding {\n\t\terr = errors.New(\"already forwarding\")\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\t/*\n\t\t// CMsg\n\t\ttype CMsg struct {\n\t\t\tCode uint64\n\t\t\tId uint64\n\t\t\tMsg []byte\n\t\t\tErr error\n\t\t}\n\t*/\n\tvar msg *cmtp.CMsg\n\tvar rw *net.TCPConn\n\t/*\n\t\tnewrawio chan io.ReadWriteCloser\n\t\tlastIdx int\n\t\trawio []io.ReadWriteCloser\n\t\tidleslot *queues.LifoQ\n\t\tworkerMsg chan *cmtp.CMsg\n\t*/\n\tvar rwidx int\n\ttime.Sleep(1e9)\n\ttpf(\"HttpEchoTransfer forwarding ...\\n\")\n\tfor {\n\t\tselect {\n\t\tcase rw = <-xf.newrawio:\n\t\t\tidlecount := xf.idleslot.Pop()\n\t\t\tif idlecount == nil {\n\t\t\t\txf.lastIdx++\n\t\t\t\trwidx = xf.lastIdx\n\t\t\t\txf.rawio = append(xf.rawio, rw)\n\t\t\t} else {\n\t\t\t\trwidx = idlecount.(int)\n\t\t\t\txf.rawio[rwidx] = rw\n\t\t\t}\n\t\t\twg.Add(1)\n\t\t\tgo xf.echoserver(rwidx, &wg)\n\t\tcase msg = <-xf.workerMsg:\n\t\t\t//tpf(\"echoserver exit with msg %v\\n\", msg)\n\t\t\t//tpf(\"echoserver exit with msg %s\\n\", msg.String())\n\t\t\t//msg = <-xf.workerMsg\n\t\t\t//tpf(\"echoserver exit with msg2 %s\\n\", msg.String())\n\t\t\txf.rawio[msg.Id].Close()\n\t\t\txf.rawio[msg.Id] = nil\n\t\t\txf.idleslot.Push(int(msg.Id))\n\t\t\t// TODO: in/out bytes in msg.Msg\n\t\t}\n\t}\n\twg.Wait()\n\tclose(xf.closed)\n\treturn\n}", "func Forward(ctx context.Context, destination chan<- packet.Buf, source <-chan packet.Buf) {\n\tdefer contextack.Ack(ctx, ForwardDoneAck)\n\n\tvar p packet.Buf\n\n\tfor {\n\t\tvar (\n\t\t\tinput <-chan packet.Buf\n\t\t\toutput chan<- packet.Buf\n\t\t\tok bool\n\t\t)\n\n\t\tif p == nil {\n\t\t\tinput = source\n\t\t} else {\n\t\t\toutput = destination\n\t\t}\n\n\t\tselect {\n\t\tcase p, ok = <-input:\n\t\t\tif !ok {\n\t\t\t\t// EOF\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase output <- p:\n\t\t\t// ok\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (a *createRepository) forward(app *App, args ...interface{}) error {\n\tgUrl := repository.GitServerUri()\n\tvar users []string\n\tfor _, t := range app.GetTeams() {\n\t\tusers = append(users, t.Users...)\n\t}\n\tc := gandalf.Client{Endpoint: gUrl}\n\t_, err := c.NewRepository(app.Name, users, false)\n\treturn err\n}" ]
[ "0.69482577", "0.6621834", "0.6508942", "0.6488017", "0.6365582", "0.6333117", "0.61553794", "0.613421", "0.61081684", "0.6089787", "0.6033418", "0.6019624", "0.6017017", "0.59916246", "0.5969902", "0.59648085", "0.59556293", "0.5928323", "0.5927592", "0.5907717", "0.5900434", "0.5887188", "0.58783567", "0.58527166", "0.5852193", "0.5831525", "0.5792228", "0.57909083", "0.57833153", "0.57763803", "0.57511264", "0.5734752", "0.57307106", "0.5707127", "0.5707127", "0.5682085", "0.56782496", "0.5678147", "0.5669481", "0.56322604", "0.5627271", "0.5616726", "0.56164926", "0.56158173", "0.5613885", "0.55813694", "0.5571407", "0.556792", "0.5552846", "0.5521433", "0.55130345", "0.5511635", "0.5508261", "0.5506645", "0.54975396", "0.5485105", "0.5482569", "0.5479582", "0.5468573", "0.5424697", "0.54210335", "0.5407986", "0.540576", "0.54057574", "0.5403227", "0.5397199", "0.53890026", "0.53793484", "0.5378704", "0.53718853", "0.53709626", "0.5358943", "0.5348475", "0.53420365", "0.5317753", "0.52981716", "0.5292329", "0.5286838", "0.5279789", "0.5279789", "0.5233766", "0.52278394", "0.5227387", "0.5206821", "0.5206237", "0.5194162", "0.5190563", "0.51871", "0.51821315", "0.5179087", "0.5156082", "0.5153847", "0.5129466", "0.51263255", "0.5124452", "0.5120781", "0.5116036", "0.5112841", "0.50962245", "0.50898355" ]
0.562365
41
NewRobertaForTokenClassification creates a new RobertaForTokenClassification model.
func NewRobertaForTokenClassification(p *nn.Path, config *bert.BertConfig) *RobertaForTokenClassification { roberta := bert.NewBertModel(p.Sub("roberta"), config) dropout := util.NewDropout(config.HiddenDropoutProb) numLabels := int64(len(config.Id2Label)) classifier := nn.NewLinear(p.Sub("classifier"), config.HiddenSize, numLabels, nn.DefaultLinearConfig()) return &RobertaForTokenClassification{ roberta: roberta, dropout: dropout, classifier: classifier, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRobertaForSequenceClassification(p *nn.Path, config *bert.BertConfig) *RobertaForSequenceClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tclassifier := NewRobertaClassificationHead(p.Sub(\"classifier\"), config)\n\n\treturn &RobertaForSequenceClassification{\n\t\troberta: roberta,\n\t\tclassifier: classifier,\n\t}\n}", "func NewRobertaClassificationHead(p *nn.Path, config *bert.BertConfig) *RobertaClassificationHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\tnumLabels := int64(len(config.Id2Label))\n\toutProj := nn.NewLinear(p.Sub(\"out_proj\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\n\treturn &RobertaClassificationHead{\n\t\tdense: dense,\n\t\tdropout: dropout,\n\t\toutProj: outProj,\n\t}\n}", "func NewTokenizer(r io.Reader) (*Tokenizer, error) {\n\tinput := bufio.NewReader(r)\n\tclassifier := NewDefaultClassifier()\n\ttokenizer := &Tokenizer{\n\t\tinput: input,\n\t\tclassifier: classifier}\n\treturn tokenizer, nil\n}", "func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tdropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tnumLabels := int64(len(config.(*bert.BertConfig).Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\ttc.roberta = roberta\n\ttc.dropout = dropout\n\ttc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newToken(sub, role string) Token {\n\treturn Token{\n\t\tID: id.New(),\n\t\tSubject: sub,\n\t\tRole: role,\n\t\tCreatedAt: time.Now().UTC(),\n\t}\n}", "func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tlmHead := NewRobertaLMHead(p.Sub(\"lm_head\"), config)\n\n\treturn &RobertaForMaskedLM{\n\t\troberta: roberta,\n\t\tlmHead: lmHead,\n\t}\n}", "func NewRobertaForMultipleChoice(p *nn.Path, config *bert.BertConfig) *RobertaForMultipleChoice {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, 1, nn.DefaultLinearConfig())\n\n\treturn &RobertaForMultipleChoice{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewDefaultClassifier() *TokenClassifier {\n\ttypeMap := map[int32]RuneTokenType{}\n\taddRuneClass(&typeMap, RUNE_CHAR, RUNETOKEN_CHAR)\n\taddRuneClass(&typeMap, RUNE_SPACE, RUNETOKEN_SPACE)\n\taddRuneClass(&typeMap, RUNE_ESCAPING_QUOTE, RUNETOKEN_ESCAPING_QUOTE)\n\taddRuneClass(&typeMap, RUNE_NONESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE)\n\taddRuneClass(&typeMap, RUNE_ESCAPE, RUNETOKEN_ESCAPE)\n\taddRuneClass(&typeMap, RUNE_COMMENT, RUNETOKEN_COMMENT)\n\treturn &TokenClassifier{\n\t\ttypeMap: typeMap}\n}", "func NewToken(tokenType string, resource string, id interface{}, exprire time.Time) (string, error) {\n\tvar t = Token{\n\t\tText: core.GenerateToken(core.WebLetterRunes, 64),\n\t\tType: tokenType,\n\t\tResouceType: resource,\n\t\tResourceID: id,\n\t\tExpire: exprire,\n\t}\n\n\tif err := CreateDocument(&t); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn t.Text, nil\n}", "func NewClassifier(model Model) Classifier {\n\treturn Classifier{\n\t\tModel: model,\n\t\tLearningResults: make(map[string]map[Class]int),\n\t\tPriorProbabilities: make(map[Class]float64),\n\t\tNDocumentByClass: make(map[Class]int),\n\t\tNFrequencyByClass: make(map[Class]int),\n\t}\n}", "func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\n\tlayerNormConfig := nn.DefaultLayerNormConfig()\n\tlayerNormConfig.Eps = 1e-12\n\tlayerNorm := nn.NewLayerNorm(p.Sub(\"layer_norm\"), []int64{config.HiddenSize}, layerNormConfig)\n\n\tdecoder := util.NewLinearNoBias(p.Sub(\"decoder\"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig())\n\n\tbias := p.NewVar(\"bias\", []int64{config.VocabSize}, nn.NewKaimingUniformInit())\n\n\treturn &RobertaLMHead{\n\t\tdense: dense,\n\t\tdecoder: decoder,\n\t\tlayerNorm: layerNorm,\n\t\tbias: bias,\n\t}\n}", "func NewClassifierFromReader(r io.Reader) (c *Classifier, err error) {\n\tdec := gob.NewDecoder(r)\n\tw := new(Classifier)\n\terr = dec.Decode(w)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode as Classifier: %w\", err)\n\t}\n\n\treturn w, nil\n}", "func NewMit-raToken(address common.Address, backend bind.ContractBackend) (*Mit-raToken, error) {\n\tcontract, err := bindMit-raToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mit-raToken{Mit-raTokenCaller: Mit-raTokenCaller{contract: contract}, Mit-raTokenTransactor: Mit-raTokenTransactor{contract: contract}, Mit-raTokenFilterer: Mit-raTokenFilterer{contract: contract}}, nil\n}", "func NewToken(tokenType *tokenType, m map[string]interface{}) (string, error) {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, buildClaim(tokenType, m))\n\treturn token.SignedString(secret)\n}", "func NewDecisionTreeClassifier(maxDepth, minLeafSize int, criteria splitCriteria, splitFinder splitFinder) DecisionTree {\n\treturn DecisionTree{predictor: ClassificationPredictor{}, maxDepth: maxDepth, minLeafSize: minLeafSize, criteria: criteria, splitFinder: splitFinder}\n}", "func NewClassifierFromFile(name string) (c *Classifier, err error) {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %q: %w\", name, err)\n\t}\n\tdefer file.Close()\n\n\treturn NewClassifierFromReader(file)\n}", "func NewRandomForestClassifier(maxDepth, minLeafSize int, criteria splitCriteria, splitFinder splitFinder, numberOfEstimators int) RandomForest {\n\treturn RandomForest{predictor: ClassificationPredictor{}, maxDepth: maxDepth, minLeafSize: minLeafSize, criteria: criteria, splitFinder: splitFinder, numberOfEstimators: numberOfEstimators}\n}", "func NewMit-raTokenCaller(address common.Address, caller bind.ContractCaller) (*Mit-raTokenCaller, error) {\n\tcontract, err := bindMit-raToken(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mit-raTokenCaller{contract: contract}, nil\n}", "func NewCrToken(address common.Address, backend bind.ContractBackend) (*CrToken, error) {\n\tcontract, err := bindCrToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CrToken{CrTokenCaller: CrTokenCaller{contract: contract}, CrTokenTransactor: CrTokenTransactor{contract: contract}, CrTokenFilterer: CrTokenFilterer{contract: contract}}, nil\n}", "func NewClassifierFromFile(path string) (Classifier, error) {\n\tclassifier := Classifier{}\n\n\tfl, err := os.Open(path)\n\tif err != nil {\n\t\treturn classifier, err\n\t}\n\tdefer fl.Close()\n\n\terr = gob.NewDecoder(fl).Decode(&classifier)\n\tif err != nil {\n\t\treturn classifier, err\n\t}\n\n\treturn classifier, err\n}", "func NewToken() Token {\n\treturn Token{\n\t\tData: GenerateToken(1),\n\t\tTimestamp: time.Now().UTC(),\n\t}\n}", "func NewToken(uid int32) (string, string, error) {\n\ttoken := jwtgo.New(jwtgo.SigningMethodES256)\n\n\tclaims := token.Claims.(jwtgo.MapClaims)\n\tclaims[claimUID] = uid\n\tclaims[claimExpire] = time.Now().Add(time.Hour * tokenExpireInHour).Unix()\n\n\tt, err := token.SignedString([]byte(TokenHMACKey))\n\treturn respTokenKey, t, err\n}", "func NewTokenLTE(v string) predicate.User {\n\treturn predicate.User(sql.FieldLTE(FieldNewToken, v))\n}", "func NewClassifierWithConfig(graphPath, labelPath string,\n\tconfig Config) (*Classifier, error) {\n\t// Read the passed inception model file\n\tbytes, err := ioutil.ReadFile(graphPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Populate a new graph using the read model\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(bytes, \"\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new execution session using the graph\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Read all labels in the passed labelPath\n\tlabels, err := readLabels(labelPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Return a fully populated Classifier\n\treturn &Classifier{config: config, graph: graph, session: session,\n\t\tlabels: labels}, nil\n}", "func NewVppToken()(*VppToken) {\n m := &VppToken{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewToken(v string) predicate.User {\n\treturn predicate.User(sql.FieldEQ(FieldNewToken, v))\n}", "func NewToken(usr *users.User) ([]byte, error) {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, &tokenClaims{\n\t\tStandardClaims: jwt.StandardClaims{\n\t\t\tExpiresAt: time.Now().Add(time.Hour).Unix(),\n\t\t\tIssuedAt: time.Now().Unix(),\n\t\t},\n\t\tUserID: usr.ID(),\n\t\tAdmin: usr.Admin(),\n\t})\n\n\tkey, _ := jwtKey(nil)\n\ttokenStr, err := token.SignedString(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn []byte(tokenStr), nil\n}", "func (bridge *Bridge) NewToken(details plutus.CardDetails, kind plutus.CardTokenType) (*plutus.CardToken, error) {\n\tif err := validateCardDetails(details); err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch kind {\n\tcase plutus.OneUseToken:\n\t\ttoken, err := bridge.generateNewOneUseToken(details)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[from culqi] %s\", err.Error())\n\t\t}\n\n\t\tencodedNumberCard := \"\"\n\t\tif len(details.Number) >= 4 {\n\t\t\tencodedNumberCard = details.Number[len(details.Number)-4:]\n\t\t\tencodedNumberCard = strings.Repeat(\"*\", len(details.Number)-4) + encodedNumberCard\n\t\t}\n\n\t\treturn &plutus.CardToken{\n\t\t\tCreatedAt: time.Now(),\n\t\t\tType: kind,\n\t\t\tValue: token.Value,\n\t\t\tWithCard: plutus.EncodedCardDetails{\n\t\t\t\tNumber: encodedNumberCard,\n\t\t\t\tCustomer: details.Customer,\n\t\t\t\tExpirationYear: details.Expiration.Year,\n\t\t\t},\n\t\t}, nil\n\n\tcase plutus.RecurrentToken:\n\t\ttoken, err := bridge.generateNewOneUseToken(details)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[from culqi] %s\", err.Error())\n\t\t}\n\n\t\tcard, err := bridge.generateNewRecurrentToken(token.Value, details)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[from culqi] %s\", err.Error())\n\t\t}\n\n\t\tencodedNumberCard := \"\"\n\t\tif len(details.Number) >= 4 {\n\t\t\tencodedNumberCard = details.Number[len(details.Number)-4:]\n\t\t\tencodedNumberCard = strings.Repeat(\"*\", len(details.Number)-4) + encodedNumberCard\n\t\t}\n\n\t\treturn &plutus.CardToken{\n\t\t\tCreatedAt: time.Now(),\n\t\t\tType: kind,\n\t\t\tValue: card.ID,\n\t\t\tWithCard: plutus.EncodedCardDetails{\n\t\t\t\tNumber: encodedNumberCard,\n\t\t\t\tCustomer: details.Customer,\n\t\t\t\tExpirationYear: details.Expiration.Year,\n\t\t\t},\n\t\t}, nil\n\tdefault:\n\t\tbreak\n\t}\n\n\treturn nil, errors.New(\"invalid token type\")\n\n}", "func NewToken(claims map[string]interface{}, privatekeyFilename string) (*jwt.Token, error) {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.MapClaims(claims))\n\t// use the test private key to sign the token\n\tkey, err := PrivateKey(privatekeyFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsigned, err := token.SignedString(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoken.Raw = signed\n\tlog.Debug(nil, map[string]interface{}{\"signed_token\": signed, \"claims\": claims}, \"generated test token with custom sub\")\n\treturn token, nil\n}", "func NewclassifyLexer(input antlr.CharStream) *classifyLexer {\n\tl := new(classifyLexer)\n\tlexerDeserializer := antlr.NewATNDeserializer(nil)\n\tlexerAtn := lexerDeserializer.DeserializeFromUInt16(serializedLexerAtn)\n\tlexerDecisionToDFA := make([]*antlr.DFA, len(lexerAtn.DecisionToState))\n\tfor index, ds := range lexerAtn.DecisionToState {\n\t\tlexerDecisionToDFA[index] = antlr.NewDFA(ds, index)\n\t}\n\tl.BaseLexer = antlr.NewBaseLexer(input)\n\tl.Interpreter = antlr.NewLexerATNSimulator(l, lexerAtn, lexerDecisionToDFA, antlr.NewPredictionContextCache())\n\n\tl.channelNames = lexerChannelNames\n\tl.modeNames = lexerModeNames\n\tl.RuleNames = lexerRuleNames\n\tl.LiteralNames = lexerLiteralNames\n\tl.SymbolicNames = lexerSymbolicNames\n\tl.GrammarFileName = \"classify.g4\"\n\t// TODO: l.EOF = antlr.TokenEOF\n\n\treturn l\n}", "func NewClassifier(ctx *pulumi.Context,\n\tname string, args *ClassifierArgs, opts ...pulumi.ResourceOption) (*Classifier, error) {\n\tif args == nil {\n\t\targs = &ClassifierArgs{}\n\t}\n\n\tvar resource Classifier\n\terr := ctx.RegisterResource(\"aws:glue/classifier:Classifier\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (KNN *KNNRegressor) New(name string, labels []float64, numbers []float64, x int, y int) {\n\n\tKNN.Data = *mat.MakeDenseMatrix(numbers, x, y)\n\tKNN.Name = name\n\tKNN.Labels = labels\n}", "func New() *Classifier {\n\treturn &Classifier{\n\t\tNewFrequencyStorage(),\n\t}\n}", "func NewNGram(n int, tokens []string, class string) nGram {\n\treturn nGram{n, tokens, genhash(tokens), map[string]int{class: 1}}\n}", "func NewRecognizer(modelDir string) (rec *Recognizer, err error) {\n\tcModelDir := C.CString(modelDir)\n\tdefer C.free(unsafe.Pointer(cModelDir))\n\tptr := C.facerec_init(cModelDir)\n\n\tif ptr.err_str != nil {\n\t\tdefer C.facerec_free(ptr)\n\t\tdefer C.free(unsafe.Pointer(ptr.err_str))\n\t\terr = makeError(C.GoString(ptr.err_str), int(ptr.err_code))\n\t\treturn\n\t}\n\n\trec = &Recognizer{ptr}\n\treturn\n}", "func New(user *user.Model) *jwt.Token {\n\ttoken := jwt.New(jwt.GetSigningMethod(\"RS256\"))\n\ttoken.Claims[\"uid\"] = user.Id.Int64\n\ttoken.Claims[\"user\"] = user\n\ttoken.Claims[\"exp\"] = time.Now().Add(time.Minute * tokenExpTime).Unix()\n\treturn token\n}", "func newToken(tokenType TokenType, literal byte) Token {\n\treturn Token{Type: tokenType, Literal: string(literal)}\n}", "func NewTokenizer() *Tokenizer {\n\ttokenizer := Tokenizer {\n\t\tavailableTokens: maxTokens,\n\t\ttotalTokens: maxTokens,\n\t\tcurrentUsers: make(map[string]bool),\n\t\tsignal: make(chan bool),\n\t}\n\tgo tokenizer.refreshTokens();\n\treturn &tokenizer;\n}", "func NewRoar(author string, text string) *Roar {\n return &Roar{Author: author, Text: text,\n CreationDate: time.LocalTime().Format(time.RFC1123)}\n}", "func (b batchPredictor) NewPredictor() predHelp.Predictor {\n\treturn b\n}", "func (s *TokenService) New(ctx context.Context, req *v1pb.NewTokenReq) (resp *v1pb.NewTokenResp, err error) {\n\t// Must be live's bucket.\n\t_, ok := s.conf.Bucket[req.Bucket]\n\tif !ok {\n\t\terr = ecode.UploadBucketErr\n\t\treturn\n\t}\n\n\tvar token string\n\tif token, err = s.dao.RequestUploadToken(ctx, req.Bucket, req.Operator, time.Now().Unix()); err != nil {\n\t\tlog.Error(\"New a upload token failure: %v\", err)\n\t\terr = ecode.UploadTokenGenErr\n\t\treturn\n\t}\n\n\tresp = &v1pb.NewTokenResp{\n\t\tToken: token,\n\t}\n\n\treturn\n}", "func NewToken() jwt.Token {\n\treturn jwt.New()\n}", "func NewClass(r *http.Request) (class Class, err error) {\n\terr = r.ParseMultipartForm(utilities.MAX_STORAGE)\n\tif err != nil {\n\t\treturn\n\t}\n\tdecoder := schema.NewDecoder()\n\terr = decoder.Decode(&class, r.PostForm)\n\treturn\n}", "func NewToken(\n\tsmc sdk.ISmartContract,\n\taddress types.Address, //代币地址\n\towner types.Address, //代币拥有者的账户地址\n\tname string, //代币的名称\n\tsymbol string, //代币的符号\n\ttotalSupply bn.Number, //代币的总供应量\n\taddSupplyEnabled bool, //代币是否支持增发\n\tburnEnabled bool, //代币是否支持燃烧\n\tgasPrice int64) sdk.IToken { //代币燃料价格\n\to := Token{\n\t\tsmc: smc,\n\t\ttk: std.Token{\n\t\t\tAddress: address,\n\t\t\tOwner: owner,\n\t\t\tName: name,\n\t\t\tSymbol: symbol,\n\t\t\tTotalSupply: totalSupply,\n\t\t\tAddSupplyEnabled: addSupplyEnabled,\n\t\t\tBurnEnabled: burnEnabled,\n\t\t\tGasPrice: gasPrice,\n\t\t},\n\t}\n\treturn &o\n}", "func NewTokenizer(input []byte) *Tokenizer {\n\treturn &Tokenizer{in: input}\n}", "func (a *Authenticator) requestNewToken() (jwt.Token, error) {\n\trestRequest, err := a.getAuthRequest()\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error during auth request creation: %w\", err)\n\t}\n\n\tgetMethod := rest.PostMethod\n\n\thttpRequest, err := restRequest.GetHTTPRequest(a.BasePath, getMethod.Method)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error constructing token http request: %w\", err)\n\t}\n\tbodyToSign, err := restRequest.GetJSONBody()\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error marshalling token request: %w\", err)\n\t}\n\tsignature, err := signWithKey(bodyToSign, a.PrivateKeyBody)\n\tif err != nil {\n\t\treturn jwt.Token{}, err\n\t}\n\thttpRequest.Header.Add(signatureHeader, signature)\n\n\thttpResponse, err := a.HTTPClient.Do(httpRequest)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error requesting token: %w\", err)\n\t}\n\n\tdefer httpResponse.Body.Close()\n\n\t// read entire response body\n\tb, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error requesting token: %w\", err)\n\t}\n\n\trestResponse := rest.Response{\n\t\tBody: b,\n\t\tStatusCode: httpResponse.StatusCode,\n\t\tMethod: getMethod,\n\t}\n\n\tvar tokenToReturn tokenResponse\n\terr = restResponse.ParseResponse(&tokenToReturn)\n\tif err != nil {\n\t\treturn jwt.Token{}, fmt.Errorf(\"error requesting token: %w\", err)\n\t}\n\n\treturn jwt.New(tokenToReturn.Token)\n}", "func NewRobertaForQuestionAnswering(p *nn.Path, config *bert.BertConfig) *RobertaForQuestionAnswering {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForQuestionAnswering{\n\t\troberta: roberta,\n\t\tqaOutputs: qaOutputs,\n\t}\n}", "func NewToken(id int, role string) (string, error) {\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\"role\": role,\n\t\t\"userID\": id,\n\t\t\"nbf\": time.Now().Unix(),\n\t\t\"iat\": time.Now().Unix(),\n\t\t\"exp\": time.Now().Local().Add(time.Hour*time.Duration(JWT_EXP_HOUR) + time.Minute*time.Duration(JWT_EXP_MIN) + time.Second*time.Duration(JWT_EXP_SEC)).Unix(),\n\t})\n\t// Sign and get the complete encoded token as a string using the secret\n\tsToken, err := token.SignedString([]byte(JWT_SECRET))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn sToken, nil\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Terms) NewTerm(Id string) (*OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Terms_Term, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Term == nil {\n\t\tt.Term = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Terms_Term)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Term[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Term\", key)\n\t}\n\n\tt.Term[key] = &OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Terms_Term{\n\t\tId: &Id,\n\t}\n\n\treturn t.Term[key], nil\n}", "func NewTokenizer(r io.Reader) (t *Tokenizer) {\n\tt = &Tokenizer{\n\t\tr: bufio.NewReader(r),\n\t\tlineno: 0, offset: 0,\n\t\tline: nil,\n\t\tlastToken: nilToken,\n\t\tindentStack: list.List{},\n\t}\n\n\tt.indentStack.PushBack([]byte{})\n\n\treturn\n}", "func (t *Token) New() *Token {\n\treturn NewToken()\n}", "func NewTokenController() *TokenController {\n\treturn &TokenController{mySigningKey}\n}", "func newMaxentClassifier(\n\tweights []float64,\n\tmapping map[string]int,\n\tlabels []string) *binaryMaxentClassifier {\n\n\tset := mapset.NewSet()\n\tfor label := range mapping {\n\t\tset.Add(strings.Split(label, \"-\")[0])\n\t}\n\n\treturn &binaryMaxentClassifier{\n\t\tset.Cardinality() + 1,\n\t\tlabels,\n\t\tmapping,\n\t\tweights}\n}", "func (t *OpenconfigQos_Qos_Classifiers) NewClassifier(Name string) (*OpenconfigQos_Qos_Classifiers_Classifier, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Classifier == nil {\n\t\tt.Classifier = make(map[string]*OpenconfigQos_Qos_Classifiers_Classifier)\n\t}\n\n\tkey := Name\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Classifier[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Classifier\", key)\n\t}\n\n\tt.Classifier[key] = &OpenconfigQos_Qos_Classifiers_Classifier{\n\t\tName: &Name,\n\t}\n\n\treturn t.Classifier[key], nil\n}", "func newCSRFToken() CSRFToken {\n\treturn CSRFToken{\n\t\tValue: cipher.RandByte(csrfTokenLength),\n\t\tExpiresAt: time.Now().Add(CSRFMaxAge),\n\t}\n}", "func newTokenHandler(w http.ResponseWriter, r *http.Request) {\n\t// Read the bytes from the body\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tresultErrorJSON(w, http.StatusInternalServerError, err.Error())\n\t}\n\n\t// Schema Validation:\n\tjsonErrors, err := validateRequestSchema(tokenRequestSchema, bodyBytes)\n\t// General validation error\n\tif err != nil {\n\t\tcode := http.StatusInternalServerError\n\t\tif err == errInvalidJSON {\n\t\t\tcode = http.StatusBadRequest\n\t\t}\n\t\tresultErrorJSON(w, code, err.Error())\n\t\treturn\n\t}\n\n\t// JSON Schema errors\n\tif jsonErrors != nil {\n\t\tresultSchemaErrorJSON(w, jsonErrors)\n\t\treturn\n\t}\n\n\tvar payload tokenPayload\n\terr = json.Unmarshal(bodyBytes, &payload)\n\tif err != nil {\n\t\tresultErrorJSON(w, http.StatusBadRequest, errInvalidPayload.Error())\n\t\treturn\n\t}\n\n\t// TODO: Use your own methods to log someone in and then return a new Token\n\n\tif response, err := bjwt.Generate(123456); err != nil {\n\t\tresultErrorJSON(w, http.StatusInternalServerError, err.Error())\n\t} else {\n\t\tresultResponseJSON(w, http.StatusOK, response)\n\t}\n}", "func newTrainedEntityExtracter(model *binaryMaxentClassifier) *entityExtracter {\n\treturn &entityExtracter{model: model}\n}", "func NewMit-raTokenFilterer(address common.Address, filterer bind.ContractFilterer) (*Mit-raTokenFilterer, error) {\n\tcontract, err := bindMit-raToken(address, nil, nil, filterer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mit-raTokenFilterer{contract: contract}, nil\n}", "func New() Token {\n\treturn &jwtToken{}\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Output_Classifers_Classifier_Terms) NewTerm(Id string) (*OpenconfigQos_Qos_Interfaces_Interface_Output_Classifers_Classifier_Terms_Term, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Term == nil {\n\t\tt.Term = make(map[string]*OpenconfigQos_Qos_Interfaces_Interface_Output_Classifers_Classifier_Terms_Term)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Term[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Term\", key)\n\t}\n\n\tt.Term[key] = &OpenconfigQos_Qos_Interfaces_Interface_Output_Classifers_Classifier_Terms_Term{\n\t\tId: &Id,\n\t}\n\n\treturn t.Term[key], nil\n}", "func NewToken() *Token {\n\tthis := Token{}\n\treturn &this\n}", "func (cat *Category) TrainToken(word string, count int) {\n\t// Creating the token if it doesn't exist, otherwise incrementing it\n\tif _, ok := cat.Tokens[word]; ok {\n\t\tcat.Tokens[word] += count\n\t} else {\n\t\tcat.Tokens[word] = count\n\t}\n\n\tcat.Tally += count\n}", "func NewRandomToken(length int) ([]byte, error) {\n\tl := big.NewInt(int64(len(randomCharSet)))\n\n\tresult := make([]byte, length, length)\n\tfor i := 0; i < length; i++ {\n\t\tn, err := rand.Int(rand.Reader, l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[i] = randomCharSet[n.Int64()]\n\t}\n\treturn result, nil\n}", "func NewToken(header *Header, body *Body, secret *pbauth.Secret) (string, error) {\n\tif err := ValidateHeader(header); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err := ValidateBody(body); err != nil {\n\t\treturn \"\", err\n\t}\n\tif err := ValidateSecret(secret); err != nil {\n\t\treturn \"\", err\n\t}\n\tif body.Permission == Admin && header.Alg != Hs512 {\n\t\treturn \"\", consts.ErrInvalidPermission\n\t}\n\t// Currently supports JWT, JET\n\tif header.TokenTyp != Jwt && header.TokenTyp != Jet {\n\t\treturn \"\", consts.ErrUnknownTokenType\n\t}\n\ttokenString, err := getTokenSignature(header, body, secret)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn tokenString, nil\n}", "func NewToken(token string) *Token {\n\tthis := Token{}\n\tthis.Token = token\n\treturn &this\n}", "func NewToken(t TokenType, v string) *Token {\n\treturn &Token{Type: t, Value: v}\n}", "func New(questionsPath string, textPath string) *Truman {\n\tt := &Truman{}\n\n\tquestionsFilePath, _ := filepath.Abs(questionsPath)\n\ttextFilePath, _ := filepath.Abs(textPath)\n\n\tt.loadQuestions(questionsFilePath)\n\tt.loadText(textFilePath)\n\n\treturn t\n}", "func newToken(linum, col uint, s string, tt TokenType) (t Token) {\n\tt.Linum = linum\n\tt.Column = col\n\tt.Type = tt\n\tt.Sub = None\n\tt.writeString(s)\n\treturn\n}", "func NewTokenFlow(ctx *cli.Context, typ int, subject string, sans []string, caURL, root string, notBefore, notAfter time.Time, certNotBefore, certNotAfter provisioner.TimeDuration) (string, error) {\n\t// Get audience from ca-url\n\taudience, err := parseAudience(ctx, typ)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tprovisioners, err := pki.GetProvisioners(caURL, root)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tp, err := provisionerPrompt(ctx, provisioners)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tswitch p := p.(type) {\n\tcase *provisioner.OIDC: // Run step oauth\n\t\targs := []string{\"oauth\", \"--oidc\", \"--bare\",\n\t\t\t\"--provider\", p.ConfigurationEndpoint,\n\t\t\t\"--client-id\", p.ClientID, \"--client-secret\", p.ClientSecret}\n\t\tif ctx.Bool(\"console\") {\n\t\t\targs = append(args, \"--console\")\n\t\t}\n\t\tif p.ListenAddress != \"\" {\n\t\t\targs = append(args, \"--listen\", p.ListenAddress)\n\t\t}\n\t\tout, err := exec.Step(args...)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn strings.TrimSpace(string(out)), nil\n\tcase *provisioner.GCP: // Do the identity request to get the token\n\t\tsharedContext.DisableCustomSANs = p.DisableCustomSANs\n\t\treturn p.GetIdentityToken(subject, caURL)\n\tcase *provisioner.AWS: // Do the identity request to get the token\n\t\tsharedContext.DisableCustomSANs = p.DisableCustomSANs\n\t\treturn p.GetIdentityToken(subject, caURL)\n\tcase *provisioner.Azure: // Do the identity request to get the token\n\t\tsharedContext.DisableCustomSANs = p.DisableCustomSANs\n\t\treturn p.GetIdentityToken(subject, caURL)\n\tcase *provisioner.ACME: // Return an error with the provisioner ID\n\t\treturn \"\", &ErrACMEToken{p.GetName()}\n\t}\n\n\t// JWK provisioner\n\tprov, ok := p.(*provisioner.JWK)\n\tif !ok {\n\t\treturn \"\", errors.Errorf(\"unknown provisioner type %T\", p)\n\t}\n\n\tkid := prov.Key.KeyID\n\tissuer := prov.Name\n\n\tvar opts []jose.Option\n\tif passwordFile := ctx.String(\"password-file\"); len(passwordFile) != 0 {\n\t\topts = append(opts, jose.WithPasswordFile(passwordFile))\n\t}\n\n\tvar jwk *jose.JSONWebKey\n\tif keyFile := ctx.String(\"key\"); len(keyFile) == 0 {\n\t\t// Get private key from CA\n\t\tencrypted, err := pki.GetProvisionerKey(caURL, root, kid)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t// Add template with check mark\n\t\topts = append(opts, jose.WithUIOptions(\n\t\t\tui.WithPromptTemplates(ui.PromptTemplates()),\n\t\t))\n\n\t\tdecrypted, err := jose.Decrypt(\"Please enter the password to decrypt the provisioner key\", []byte(encrypted), opts...)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tjwk = new(jose.JSONWebKey)\n\t\tif err := json.Unmarshal(decrypted, jwk); err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"error unmarshalling provisioning key\")\n\t\t}\n\t} else {\n\t\t// Get private key from given key file\n\t\tjwk, err = jose.ParseKey(keyFile, opts...)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t// Generate token\n\ttokenGen := NewTokenGenerator(kid, issuer, audience, root, notBefore, notAfter, jwk)\n\tswitch typ {\n\tcase SignType:\n\t\treturn tokenGen.SignToken(subject, sans)\n\tcase RevokeType:\n\t\treturn tokenGen.RevokeToken(subject)\n\tcase SSHUserSignType:\n\t\treturn tokenGen.SignSSHToken(subject, provisioner.SSHUserCert, sans, certNotBefore, certNotAfter)\n\tcase SSHHostSignType:\n\t\treturn tokenGen.SignSSHToken(subject, provisioner.SSHHostCert, sans, certNotBefore, certNotAfter)\n\tdefault:\n\t\treturn tokenGen.Token(subject)\n\t}\n}", "func newReloadingTokenSource(getToken func() []byte) *reloadingTokenSource {\n\treturn &reloadingTokenSource{\n\t\tgetToken: getToken,\n\t}\n}", "func NewClassifier(graphPath, labelPath string) (*Classifier, error) {\n\treturn NewClassifierWithConfig(graphPath, labelPath, DefaultConfig)\n}", "func New(r io.Reader) (*Cxt, error) {\n\tvar conf *config.Config\n\tvar err error\n\tif r != nil {\n\t\tconf, err = config.Decode(r)\n\t\tif err != nil {\n\t\t\treturn nil, errs.Wrap(err, \"\")\n\t\t}\n\t}\n\tc := &Cxt{graph: dot.NewGraph(dot.Directed).ID(\"G\"), nodeList: newNodes(conf)}\n\treturn c, nil\n}", "func ModelToToken(tt *models.TwitchToken) *oauth2.Token {\n\treturn &oauth2.Token{\n\t\tAccessToken: tt.AccessToken,\n\t\tTokenType: tt.TokenType,\n\t\tRefreshToken: tt.RefreshToken,\n\t\tExpiry: tt.Expiry,\n\t}\n}", "func New[T float.DType](c Config) *RAdam[T] {\n\tadam := &RAdam[T]{\n\t\tConfig: c,\n\t\tRoMax: 2.0/(1.0-c.Beta2) - 1.0,\n\t\tTimeStep: 1.0,\n\t}\n\treturn adam\n}", "func NewLifTokenCaller(address common.Address, caller bind.ContractCaller) (*LifTokenCaller, error) {\n\tcontract, err := bindLifToken(address, caller, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LifTokenCaller{contract: contract}, nil\n}", "func (l *Lexer) newToken(tokenType token.TokenType, lit string) token.Token {\n\treturn token.Token{\n\t\tType: tokenType,\n\t\tLine: l.line,\n\t\tColumn: l.column,\n\t\tPosition: l.position,\n\t\tLiteral: lit,\n\t}\n}", "func NewToken(rawToken string) (*Token, error) {\n\tparts := strings.Split(rawToken, TokenSeparator)\n\tif len(parts) != 3 {\n\t\treturn nil, ErrMalformedToken\n\t}\n\n\tvar (\n\t\trawHeader, rawClaims = parts[0], parts[1]\n\t\theaderJSON, claimsJSON []byte\n\t\terr error\n\t)\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Infof(\"error while unmarshalling raw token: %s\", err)\n\t\t}\n\t}()\n\n\tif headerJSON, err = joseBase64UrlDecode(rawHeader); err != nil {\n\t\terr = fmt.Errorf(\"unable to decode header: %s\", err)\n\t\treturn nil, ErrMalformedToken\n\t}\n\n\tif claimsJSON, err = joseBase64UrlDecode(rawClaims); err != nil {\n\t\terr = fmt.Errorf(\"unable to decode claims: %s\", err)\n\t\treturn nil, ErrMalformedToken\n\t}\n\n\ttoken := new(Token)\n\ttoken.Header = new(Header)\n\ttoken.Claims = new(ClaimSet)\n\n\ttoken.Raw = strings.Join(parts[:2], TokenSeparator)\n\tif token.Signature, err = joseBase64UrlDecode(parts[2]); err != nil {\n\t\terr = fmt.Errorf(\"unable to decode signature: %s\", err)\n\t\treturn nil, ErrMalformedToken\n\t}\n\n\tif err = json.Unmarshal(headerJSON, token.Header); err != nil {\n\t\treturn nil, ErrMalformedToken\n\t}\n\n\tif err = json.Unmarshal(claimsJSON, token.Claims); err != nil {\n\t\treturn nil, ErrMalformedToken\n\t}\n\n\treturn token, nil\n}", "func (tm *TokenManager) New(pool, namespace, token, description string) (string, error) {\n\tif exists := engine.ExistsPool(pool); !exists {\n\t\treturn \"\", ErrPoolNotExist\n\t}\n\tok, err := tm.cli.HSetNX(dummyCtx, tokenKey(pool, namespace), token, description).Result()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif !ok {\n\t\treturn \"\", ErrTokenExist\n\t}\n\ttm.rwmu.Lock()\n\ttm.cache[cacheKey(pool, namespace, token)] = true\n\ttm.rwmu.Unlock()\n\tif tm.isDefaultPool(pool) {\n\t\treturn token, nil\n\t}\n\treturn pool + \":\" + token, nil\n}", "func CrearToken(usuario, rol string) (string, error) {\n\t// Create token\n\tbtoken := jwt.New(jwt.SigningMethodHS256)\n\n\t// Set claims\n\tclaims := btoken.Claims.(jwt.MapClaims)\n\tclaims[\"user\"] = usuario\n\tclaims[\"role\"] = rol\n\tclaims[\"exp\"] = time.Now().Add(time.Hour * 3).Unix()\n\n\t// Generate encoded token and send it as response.\n\ttoken, err := btoken.SignedString([]byte(Secret))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfmt.Printf(\"Token: %s\\n\", token)\n\treturn token, nil\n}", "func NewTokenGTE(v string) predicate.User {\n\treturn predicate.User(sql.FieldGTE(FieldNewToken, v))\n}", "func (clf *ClfDef) getModel(stream chan base.TextDatapoint) *text.NaiveBayes {\n\tclassCount := uint8(len(clf.Labels))\n\tif clf.Typ == \"only_words_and_numbers\" {\n\t\t// OnlyWordsAndNumbers is a transform function that will only let 0-1a-zA-Z, and spaces through\n\t\t// https://godoc.org/github.com/cdipaolo/goml/base#OnlyWordsAndNumbers\n\t\treturn text.NewNaiveBayes(stream, classCount, base.OnlyWordsAndNumbers)\n\t}\n\t// OnlyWords is a transform function that will only let a-zA-Z, and spaces through\n\t// https://godoc.org/github.com/cdipaolo/goml/base#OnlyWords\n\treturn text.NewNaiveBayes(stream, classCount, base.OnlyWords)\n\n}", "func newTokenCaller(address common.Address, caller bind.ContractCaller) (*tokenCaller, error) {\n\tcontract, err := bindToken(address, caller, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &tokenCaller{contract: contract}, nil\n}", "func NewToken(ttype TokenType, lexeme string, literal interface{}, line int) Token {\n\treturn Token{\n\t\tttype: ttype,\n\t\tlexeme: lexeme,\n\t\tliteral: literal,\n\t\tline: line,\n\t}\n}", "func New(value interface{}, comparator comparator.Less) *RBTree {\n\treturn &RBTree{value: value, less: comparator, color: \"black\"}\n}", "func (b batchPredictor) NewPredictor() Predictor {\n\tprevOutput, tmpOutput := newPredictMemory(b.neurons)\n\treturn predictor{\n\t\tneurons: b.neurons,\n\t\tparameters: b.parameters,\n\t\ttmpOutput: tmpOutput,\n\t\tprevTmpOutput: prevOutput,\n\t\tinputDim: b.inputDim,\n\t\toutputDim: b.outputDim,\n\t}\n}", "func NewToken(tt TokenType, lexeme string, literal interface{}, line int) *Token {\n\treturn &Token{\n\t\tType: tt,\n\t\tLexeme: lexeme,\n\t\tLiteral: literal,\n\t\tLine: line,\n\t}\n}", "func NewMit-raTokenTransactor(address common.Address, transactor bind.ContractTransactor) (*Mit-raTokenTransactor, error) {\n\tcontract, err := bindMit-raToken(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Mit-raTokenTransactor{contract: contract}, nil\n}", "func NewTrainCar() TrainCar {\n c := TrainCar{name: \"TrainCar\", vehicle: \"TrainCar\", speed: 30, capacity: 30, railway: \"CNR\"}\n return c\n}", "func NewTokenLT(v string) predicate.User {\n\treturn predicate.User(sql.FieldLT(FieldNewToken, v))\n}", "func NewRTree() *RTree { //TODO could take M (and m) as input?\n\treturn &RTree{\n\t\troot: &node{\n\t\t\tparent: nil,\n\t\t\tentries: make([]entry, 0, RTree_M+1),\n\t\t\theight: 0,\n\t\t},\n\t}\n}", "func MakeTokenObject(claims jwt.MapClaims) *jwt.Token {\n\tmerged := jwt.MapClaims{}\n\tfor name, value := range MakeClaims() {\n\t\tmerged[name] = value\n\t}\n\tfor name, value := range claims {\n\t\tif value == nil {\n\t\t\tdelete(merged, name)\n\t\t} else {\n\t\t\tmerged[name] = value\n\t\t}\n\t}\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, merged)\n\ttoken.Header[\"kid\"] = \"123\"\n\tvar err error\n\ttoken.Raw, err = token.SignedString(jwtPrivateKey)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn token\n}", "func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) {\n\tcontract, err := bindToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil\n}", "func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) {\n\tcontract, err := bindToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil\n}", "func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) {\n\tcontract, err := bindToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil\n}", "func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) {\n\tcontract, err := bindToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil\n}", "func NewToken(address common.Address, backend bind.ContractBackend) (*Token, error) {\n\tcontract, err := bindToken(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Token{TokenCaller: TokenCaller{contract: contract}, TokenTransactor: TokenTransactor{contract: contract}, TokenFilterer: TokenFilterer{contract: contract}}, nil\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers) NewClassifier(Type E_OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Config_Type) (*OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Classifier == nil {\n\t\tt.Classifier = make(map[E_OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier_Config_Type]*OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier)\n\t}\n\n\tkey := Type\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Classifier[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Classifier\", key)\n\t}\n\n\tt.Classifier[key] = &OpenconfigQos_Qos_Interfaces_Interface_Input_Classifers_Classifier{\n\t\tType: Type,\n\t}\n\n\treturn t.Classifier[key], nil\n}", "func NewToken() *Token {\n\treturn &Token{}\n}", "func ExampleNew() {\n\ttoken := \"0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac\"\n\twallet := \"0x9ea0c535b3eb166454c8ccbaba86850c8df3ee57\"\n\texample, _ = New(token, wallet)\n\tfmt.Printf(\"This wallet has %v %v tokens\", example.BalanceString(), example.Name)\n\t// Output: This wallet has 7.282 StorjToken tokens\n}", "func (s *Trainer) NewFeaturizer() train.Featurizer {\n\t// The sink featurize method can be called in parallel normally, so\n\t// nothing is created\n\treturn s\n}" ]
[ "0.61778885", "0.5740375", "0.5316356", "0.51405746", "0.5083584", "0.49698022", "0.49512434", "0.49267012", "0.48441488", "0.48201382", "0.4790092", "0.47371662", "0.46439788", "0.46233004", "0.4608998", "0.45439917", "0.4526471", "0.45263392", "0.4505784", "0.44961753", "0.44959134", "0.44790816", "0.44452965", "0.44258934", "0.4399698", "0.4379564", "0.43716604", "0.4356026", "0.43262234", "0.43208998", "0.43198484", "0.43140253", "0.43112436", "0.43004608", "0.4297689", "0.42937586", "0.42895627", "0.42854908", "0.42709413", "0.4270095", "0.42569187", "0.42266583", "0.42232728", "0.42173898", "0.42071432", "0.4196975", "0.41945297", "0.41900256", "0.4188819", "0.41846114", "0.41781372", "0.41770622", "0.41766173", "0.4169015", "0.41532055", "0.4133979", "0.41326845", "0.41095084", "0.4104192", "0.41025943", "0.41017166", "0.41012743", "0.40940905", "0.409252", "0.4090553", "0.408314", "0.40827972", "0.40824282", "0.40824014", "0.4079496", "0.40608966", "0.4057725", "0.40566084", "0.40558162", "0.40462413", "0.40424898", "0.4039569", "0.40158245", "0.40109795", "0.40106818", "0.40077072", "0.399638", "0.3988449", "0.39722198", "0.39712444", "0.3956229", "0.3954848", "0.39418012", "0.39328578", "0.3924952", "0.3916418", "0.39146996", "0.39146996", "0.39146996", "0.39146996", "0.39146996", "0.39136073", "0.39099342", "0.39095673", "0.39027748" ]
0.817786
0
Load loads model from file or model name. It also updates default configuration parameters if provided. This method implements `PretrainedModel` interface.
func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error { var urlOrFilename string // If modelName, infer to default configuration filename: if modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok { urlOrFilename = modelFile } else { // Otherwise, just take the input urlOrFilename = modelNameOrPath } cachedFile, err := util.CachedPath(urlOrFilename) if err != nil { return err } vs := nn.NewVarStore(device) p := vs.Root() roberta := bert.NewBertModel(p.Sub("roberta"), config.(*bert.BertConfig)) dropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb) numLabels := int64(len(config.(*bert.BertConfig).Id2Label)) classifier := nn.NewLinear(p.Sub("classifier"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig()) tc.roberta = roberta tc.dropout = dropout tc.classifier = classifier err = vs.Load(cachedFile) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load(fileName string, src interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tdecoder := gob.NewDecoder(file)\n\t\tif err = decoder.Decode(src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Restore parameters\n\tswitch src.(type) {\n\tcase Model:\n\t\tmodel := src.(Model)\n\t\tmodel.SetParams(model.GetParams())\n\tdefault:\n\t\treturn errors.New(\"the file is not a model dump\")\n\t}\n\treturn nil\n}", "func (mlm *RobertaForMaskedLM) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmlm.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmlm.lmHead = NewRobertaLMHead(p.Sub(\"lm_head\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mc *RobertaForMultipleChoice) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmc.dropout = util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, 1, nn.DefaultLinearConfig())\n\tmc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sc *RobertaForSequenceClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tsc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tsc.classifier = NewRobertaClassificationHead(p.Sub(\"classifier\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Model) Load(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\tif err := json.Unmarshal(data, m); err != nil {\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\treturn nil\n}", "func Load(modelArchive string, framework Framework, flags ModelFlags) (*Model, error) {\n\tf, _ := os.Open(modelArchive)\n\tdefer f.Close()\n\tvar outDir string\n\tif fi, err := f.Stat(); err == nil && fi.IsDir() {\n\t\toutDir = modelArchive\n\t} else if err == nil && !fi.IsDir() {\n\t\ttmpDir := os.TempDir()\n\t\toutDir = filepath.Join(tmpDir, utils.PseudoUuid())\n\t\tif err := utils.Unzip(modelArchive, outDir); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to extract model archive: %v\", err)\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s does not exist\", modelArchive)\n\t}\n\n\tmodelFilename := filepath.Join(outDir, \"saved_model.pb\")\n\tif _, err := os.Stat(modelFilename); err != nil {\n\t\t// This if is here for when we can read pbtxt files\n\t\tif _, err2 := os.Stat(modelFilename + \"txt\"); err2 == nil {\n\t\t\tmodelFilename = modelFilename + \"txt\"\n\t\t\treturn nil, errors.New(\"Currently loading saved_model.pbtxt is not supported\")\n\t\t\t//comment the return when we can read pbtxt\n\t\t} else {\n\t\t\treturn nil, errors.New(\"saved_model.pb does not exist\")\n\t\t}\n\t}\n\n\tflags.ModelPath = outDir\n\tflags.ModelFile = modelFilename\n\tvar model Model\n\terr := framework.Load(&model, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &model, nil\n}", "func (am *AssetManager) LoadModel(name, iname string) {\n\tif strings.Contains(name, \".obj\") {\n\t\tam.Models[iname] = NewWavefrontModelFromFile(am.modelsDir + name)\n\t} else {\n\t\tlog.Fatal(\"cannot find \" + name)\n\t}\n}", "func (qa *RobertaForQuestionAnswering) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tnumLabels := int64(2)\n\tqaOutputs := nn.NewLinear(p.Sub(\"qa_outputs\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\tqa.roberta = roberta\n\tqa.qaOutputs = qaOutputs\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(model interface{}, provider Provider, strict bool) error {\n\treturn load(model, provider, strict)\n}", "func LoadModel(r io.Reader) (Model, error) {\n\tdec := json.NewDecoder(r)\n\tvar m Model\n\tif err := dec.Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\tm.setWeightVec()\n\treturn m, nil\n}", "func Load(modelName string) (r *pb.TextResponse, err error) {\n\tif modelName == \"\" {\n\t\tmodelName = defaultModel\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tr, err = grpcClient.LoadModel(ctx, &pb.TextRequest{Text: modelName})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}", "func (s *DataStore) Load() error {\n\tfile, err := os.Open(s.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = json.NewDecoder(file).Decode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadModelFile(path string) (Model, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fp.Close()\n\treturn LoadModel(fp)\n}", "func Load(filename string) (*SvmModel, error) {\n\n\tcfn := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cfn))\n\n\tmdl := C.svm_load_model(cfn)\n\tif mdl == nil {\n\t\treturn nil, SvmError{Message: fmt.Sprintf(\"unable to load model file: %s\", filename)}\n\t}\n\n\treturn &SvmModel{object: mdl}, nil\n}", "func (wrapper *TvmWrapper) LoadModel(modelParam *ModelParam) (*moduleInfo, error) {\n\tdefer runtime.GC()\n\n\t// debug model parameters\n\tfmt.Print(modelParam.DebugStr())\n\n\t// load module library\n\tfmt.Print(\"start to load module library...\\n\")\n\tmodLibP, err := gotvm.LoadModuleFromFile(modelParam.ModelLibPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// read module json file\n\tfmt.Print(\"start to read module json file...\\n\")\n\tbytes, err := ioutil.ReadFile(modelParam.ModelJSONPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tmodJsonStr := string(bytes)\n\n\t// create graph module of tvm\n\tfmt.Print(\"start to create graph module of tvm...\\n\")\n\tfuncp, err := gotvm.GetGlobalFunction(\"tvm.graph_runtime.create\")\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t\treturn nil, err\n\t}\n\t// graph_runtime.create\n\t// arg[0] : model json text\n\t// arg[1] : model library\n\t// arg[2] : device type (ex. KDLCPU, KDLGPU...)\n\t// arg[3] : device id\n\tgraphrt, err := funcp.Invoke(modJsonStr, modLibP, wrapper.config.DeviceType, (int64)(0))\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tgraphmod := graphrt.AsModule()\n\n\t// import params to graph module\n\tfmt.Print(\"start to import params to graph module...\\n\")\n\tbytes, err = ioutil.ReadFile(modelParam.ModelParamsPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tfuncp, err = graphmod.GetFunction(\"load_params\")\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\t_, err = funcp.Invoke(bytes)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// create module information\n\tfmt.Print(\"start to create module information...\\n\")\n\tinfo := newModuleInfo(graphmod, modelParam.InputShape, modelParam.OutputShape)\n\treturn info, nil\n}", "func loadModel(modelName string) (multilayer.MultiLayerPerceptron, error) {\n\tf, err := os.Open(\"models/\" + modelName + \".model.gob\")\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, fmt.Errorf(\"failed opening model: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\n\tnn := multilayer.MultiLayerPerceptron{}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\terr = nn.UnmarshalBinary(data)\n\treturn nn, err\n}", "func (t *TOMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif t.Reader != nil {\n\t\tr = t.Reader\n\t} else if t.Path != \"\" {\n\t\tfile, err := getConfig(t.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tif _, err := toml.DecodeReader(r, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (env *Environment) LoadExistingModel(m string) *text.NaiveBayes {\n\t// get the classifier definition to make sure it is well defined\n\tclf := env.GetClassifierDefinition(m)\n\tclf.panicErrors()\n\n\tstreamChan := make(chan base.TextDatapoint, clf.TextChannelSize)\n\tmodel := clf.getModel(streamChan)\n\terr := model.RestoreFromFile(env.baseModelPath(clf.ModelOut))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn model\n}", "func Load(fileName string) (*openapi3.Swagger, error) {\n\tmodel, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = model.Validate(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"Loaded OpenAPI 3 Specification file:\", fileName)\n\treturn model, nil\n}", "func Load(r io.Reader) error {\n\treturn DefaultInstance.Load(r)\n}", "func (l *OptionalTOMLLoader) Load(s interface{}) error {\n\tif _, err := os.Stat(l.Path); err == nil {\n\t\treturn l.TOMLLoader.Load(s)\n\t}\n\treturn nil\n}", "func (e *CachedEnforcer) LoadModel() error {\n\tif e.autoClear {\n\t\tdefer e.InvalidateCache()\n\t}\n\treturn e.base.LoadModel()\n}", "func (c *IntentClassifier) Load(filePath string) error {\n\tlog.Printf(\"Loading Classifier from %s...\", filePath)\n\tmeta := persist.Load(filePath)\n\t//get the classifier current meta data\n\tname, version := c.getMeta()\n\tif meta.Name != name {\n\t\treturn fmt.Errorf(\"This file doesn't contain a KNearestNeighbors classifier\")\n\t}\n\tif meta.Version != version {\n\t\treturn fmt.Errorf(\"Can't understand this file format\")\n\t}\n\n\tdecoder := gob.NewDecoder(bytes.NewBuffer(meta.Data))\n\terr := decoder.Decode(&c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding RNN checkpoint file: %s\", err)\n\t}\n\n\tcheckpointFile = filePath\n\treturn nil\n}", "func (k *KMP) Load(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(b, k)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid load format, %s\", format)\n\t}\n\treturn err\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(filename string) (*Params, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar params Params\n\tif err := json.Unmarshal(file, &params); err != nil {\n\t\tlog.Printf(\"failed to parse %s: %s\", file, string(file))\n\t\treturn nil, err\n\t}\n\treturn &params, nil\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func (lm *LocalMeta) Load() error {\n\t// initialize gset\n\tvar err error\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, \"\")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfile, err := os.Open(lm.filename)\n\tif err != nil && !os.IsNotExist(errors.Cause(err)) {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif os.IsNotExist(errors.Cause(err)) {\n\t\treturn nil\n\t}\n\tdefer file.Close()\n\n\t_, err = toml.DecodeReader(file, lm)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, lm.BinlogGTID)\n\treturn errors.Trace(err)\n}", "func InitModel(modelDir string, modelFile string) *TfModel {\n\tmodelpath := filepath.Join(modelDir, modelFile)\n\tmodel, err := ioutil.ReadFile(modelpath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Construct an in-memory graph from the serialized form.\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toperations := graph.Operations()\n\tfor _, op := range operations {\n\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t}\n\t// Create a session for inference over graph.\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &TfModel{Model: &tf.SavedModel{Graph: graph, Session: session}}\n}", "func (e *Definition) Load(path, entity string) error {\n\n\tfullPath := filepath.Join(path, entity)\n\n\tb, err := ioutil.ReadFile(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontent := string(b)\n\te.json = jsonutil.NewFromString(content)\n\te.byteRead = 0\n\n\ts, err := schema.Read(e)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read schema: %s\", err)\n\t\treturn err\n\t}\n\n\te.schema = s\n\tv := validator.New(s)\n\te.validator = v\n\treturn nil\n}", "func Load(reader io.Reader, configuration interface{}) error {\n\tif err := FromYAML(reader, configuration); err != nil {\n\t\treturn err\n\t}\n\treturn FromEnv(configuration)\n}", "func Init(path string, tags []string) *TfModel {\n\tmodel, err := tf.LoadSavedModel(path, tags, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading Saved Model:%v\\n\", err.Error())\n\t\treturn nil\n\t}\n\toperations := model.Graph.Operations()\n\tfor _, op := range operations {\n\t\tname := op.Name()\n\t\tif strings.HasPrefix(name, \"sentence\") || strings.HasPrefix(name, \"dropout\") || strings.HasPrefix(name, \"inference\") {\n\t\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t\t}\n\t}\n\tlog.Println(\"op loading finished\")\n\treturn &TfModel{Model: model}\n}", "func Load(filename string, v interface{}) {\n\tParse(read(filename), v)\n}", "func (trm *TrmConfig) Load(pathTrm, pathVoice string) {\n\tfmt.Println(\"trm config load\")\n\ttrm.OpenJSON(pathTrm)\n\ttrm.OpenJSON(pathVoice)\n}", "func Load() error {\n\treturn def.Load()\n}", "func LoadModel(args ...interface{}) (*WordModel, error) {\n\tvar arg interface{}\n\tif len(args) == 0 {\n\t\targ = \"https://raw.githubusercontent.com/go-ego/gse/master/data/dict/dictionary.txt\"\n\t} else {\n\t\targ = args[0]\n\t}\n\n\tr, err := readerFromAnything(arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodel := NewWordModel()\n\n\tscanner := bufio.NewScanner(r)\n\tvar words []WordFreq\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, errors.New(\"Error: not enough fields\")\n\t\t}\n\t\tword := fields[0]\n\t\tfreq, _ := strconv.ParseFloat(fields[1], 32)\n\t\tif len([]rune(word)) < 2 {\n\t\t\t//freq = 2\n\t\t}\n\t\twords = append(words, WordFreq{\n\t\t\tWord: word,\n\t\t\tLogProbability: float32((freq)),\n\t\t})\n\t}\n\n\tsort.Slice(words, func(a, b int) bool {\n\t\treturn words[a].Word < words[b].Word\n\t})\n\n\tprev := \"\"\n\tfor _, word := range words {\n\t\tif word.Word == prev {\n\t\t\tcontinue\n\t\t}\n\t\tprev = word.Word\n\t\tmodel.AddWord(word.Word, word.LogProbability)\n\t}\n\n\tmodel.Finish()\n\n\treturn model, nil\n}", "func (self *LSHforest) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn msgpack.Unmarshal(b, self)\n}", "func Load() models.Language {\n\tif models.ConfigFile != \"\" {\n\t\tlangFile = models.ConfigFile\n\t} else {\n\t\tmodels.ConfigFile = langFile\n\t}\n\n\tlang := language.LoadLanguages(langFile)\n\treturn lang\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func Load(config interface{}, configPath string) error {\n\tswitch fileExtension(configPath) {\n\tcase \"yaml\":\n\t\treturn loadYaml(config, configPath)\n\tcase \"json\":\n\t\treturn loadJson(config, configPath)\n\tdefault:\n\t\treturn ero.Newf(\"Can not support load file %s\", configPath)\n\t}\n}", "func (lf LoaderFunc) Load(serverType string) (Input, error) {\n\treturn lf(serverType)\n}", "func Load(v interface{}, loadFrom string) error {\n\tcfg, err := ini.Load(loadFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.NameMapper = ini.TitleUnderscore\n\n\treturn cfg.MapTo(v)\n}", "func Load(filePath string, t Tomler) error {\n\ttomlValue := t.TOMLValue()\n\tvar err error\n\tif _, err = toml.DecodeFile(filePath, tomlValue); err != nil {\n\t\treturn err\n\t}\n\treturn t.FromTOML(tomlValue)\n}", "func (p *BaseProvider) Load() error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (b *baseLoader) Load(ctx context.Context, src *url.URL) (*Schema, error) {\n\t// open IO\n\tvar r io.ReadCloser\n\tswitch src.Scheme {\n\tcase \"file\":\n\t\tvar err error\n\t\tif r, err = os.Open(src.Path); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q from %q: %w\", src.Path, src, err)\n\t\t}\n\tcase \"http\", \"https\":\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, src.String(), nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create request for %q: %w\", src, err)\n\t\t}\n\t\tresp, err := b.client.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed requesting %q: %w\", src, err)\n\t\t}\n\t\tr = resp.Body\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme: %v\", src.Scheme)\n\t}\n\tdefer func() {\n\t\t_ = r.Close()\n\t}()\n\n\t// read and init schema\n\tvar s Schema\n\tif err := json.NewDecoder(r).Decode(&s); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding %q failed: %w\", src, err)\n\t}\n\tif s.ID == nil {\n\t\treturn nil, fmt.Errorf(\"no ID set on %q\", src)\n\t}\n\ts.calculateID()\n\ts.setSrc(src)\n\n\treturn &s, nil\n}", "func Load(path string) (*OBJFile, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\treturn Decode(in)\n}", "func (dto *GetAdapterModelResponse) Load(data base.ModelInterface) error {\n\tm, ok := data.(*model.AdapterModel)\n\tif !ok {\n\t\tlog.Error(\"GetAdapterModelResponse.Load() failed, convert interface failed.\")\n\t\treturn base.ErrorDataConvert\n\t}\n\tdto.GetResponse.Load(&m.Model)\n\tdto.Name = m.Name\n\tdto.Type = m.Type\n\tdto.Capability.Load(m.Capability)\n\treturn nil\n}", "func (l *Loader) LoadObjModel(file string) models.RawModel {\n\tdat, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvertices := make([]mgl32.Vec3, 0)\n\ttextures := make([]mgl32.Vec2, 0)\n\tnormals := make([]mgl32.Vec3, 0)\n\tvar verticesArray []float32\n\tvar texturesArray []float32\n\tvar normalsArray []float32\n\tindicesArray := make([]uint32, 0)\n\tlines := strings.Split(string(dat), \"\\n\")\n\tvar fStart int\n\tfor i, line := range lines {\n\t\tsplited := strings.Split(line, \" \")\n\t\tif len(splited) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := splited[0]\n\t\tif t == \"v\" {\n\t\t\tvertices = append(vertices, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vn\" {\n\t\t\tnormals = append(normals, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vt\" {\n\t\t\ttextures = append(textures, mgl32.Vec2{toFloat(splited[1]), toFloat(splited[2])})\n\t\t}\n\t\tif t == \"f\" {\n\t\t\tfStart = i\n\t\t\ttexturesArray = make([]float32, len(vertices)*2)\n\t\t\tnormalsArray = make([]float32, len(vertices)*3)\n\t\t\tverticesArray = make([]float32, len(vertices)*3)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor i := fStart; i < len(lines); i++ {\n\t\tsplited := strings.Split(lines[i], \" \")\n\t\tif len(splited) == 0 || splited[0] != \"f\" {\n\t\t\tbreak\n\t\t}\n\t\tvertex1 := strings.Split(splited[1], \"/\")\n\t\tvertex2 := strings.Split(splited[2], \"/\")\n\t\tvertex3 := strings.Split(splited[3], \"/\")\n\t\tindicesArray = processVertex(vertex1, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex2, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex3, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t}\n\tcolors := make([]float32, len(normalsArray))\n\tfor i := range colors {\n\t\tcolors[i] = 1\n\t}\n\treturn l.LoadToVAO(verticesArray, texturesArray, indicesArray, normalsArray, colors)\n}", "func (f *Flow) Load(cacheDir string) (err error) {\n\tif f.FlowFile == \"\" {\n\t\treturn nil\n\t}\n\tvar content []byte\n\tswitch getURLType(f.FlowFile) {\n\tcase \"local\":\n\t\tcontent, err = ioutil.ReadFile(f.FlowFile)\n\tcase \"web\":\n\t\tcontent, err = get(cacheDir, f.FlowFile)\n\t// TODO git - including the branch\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognised floe file type: <%s>\", f.FlowFile)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal into a flow\n\tnewFlow := &Flow{}\n\terr = yaml.Unmarshal(content, &newFlow)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up the flow, and copy bits into this flow\n\terr = newFlow.zero()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(newFlow.Name) != 0 {\n\t\tf.Name = newFlow.Name\n\t}\n\tf.ReuseSpace = newFlow.ReuseSpace\n\tif len(newFlow.HostTags) != 0 {\n\t\tf.HostTags = newFlow.HostTags\n\t}\n\tif len(newFlow.ResourceTags) != 0 {\n\t\tf.ResourceTags = newFlow.ResourceTags\n\t}\n\tif len(newFlow.Env) != 0 {\n\t\tf.Env = newFlow.Env\n\t}\n\tif len(newFlow.Tasks) != 0 {\n\t\tf.Tasks = newFlow.Tasks\n\t}\n\t// Pointless overriding triggers - as they are what caused this load\n\treturn nil\n}", "func (s *CommandLineSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.callback != nil {\n\t\treturn s.koanf.Load(posflag.ProviderWithFlag(s.flags, \".\", s.koanf, s.callback), nil)\n\t}\n\n\treturn s.koanf.Load(posflag.Provider(s.flags, \".\", s.koanf), nil)\n}", "func (s *YAMLFileSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.path == \"\" {\n\t\treturn errors.New(\"invalid yaml path source configuration\")\n\t}\n\n\treturn s.koanf.Load(file.Provider(s.path), yaml.Parser())\n}", "func Load(p string) (Spec, error) {\n\tvar spec Spec\n\n\tbuf, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to read file: %s - %w\", p, err)\n\t}\n\n\terr = yaml.Unmarshal(buf, &spec)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to parse spec: %s - %w\", p, err)\n\t}\n\n\tspec.Path = p\n\n\treturn spec, nil\n}", "func Load(config *Config) error {\n\treturn NewLoader(config).Load()\n}", "func Load(path string, target interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn load(formatter, data, target)\n}", "func Load(filepath string, config interface{}) error {\n\tmagazine := make(map[string]interface{})\n\tfileBytes, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := yaml.Unmarshal(fileBytes, &magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagazine = flatten(magazine)\n\tif err := applyEnv(magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagBytes, err := yaml.Marshal(bellows.Expand(magazine))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(magBytes, config)\n}", "func (m *SynapsesPersist) Load() {\n\tdataPath, err := filepath.Abs(m.relativePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teFile, err := os.Open(dataPath + m.file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer eFile.Close()\n\n\tbytes, err := ioutil.ReadAll(eFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(bytes, &m.Synapses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (defaultStorage) Load() error {\n\tpanic(noConfigStorage)\n}", "func (function *Function) Load() (err error) {\n\tdefinition, err := ioutil.ReadFile(function.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfunction.Definition = string(definition)\n\n\treturn\n}", "func Load(state *state.State, driverName string, name string, config map[string]string, logger logger.Logger, volIDFunc func(volType VolumeType, volName string) (int64, error), commonRulesFunc func() map[string]func(string) error) (Driver, error) {\n\t// Locate the driver loader.\n\tdriverFunc, ok := drivers[driverName]\n\tif !ok {\n\t\treturn nil, ErrUnknownDriver\n\t}\n\n\td := driverFunc()\n\terr := d.init(state, name, config, logger, volIDFunc, commonRulesFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (vm *BFVM) LoadFromString(source string) error {\n\treturn vm.LoadFromStream(strings.NewReader(source))\n}", "func (appConf *AppConf) Load(filename string, forceReload bool) (*AppConf, error){\n\t// appConf is load and force reload is false return direction\n\tif isLoad && !forceReload{\n\t\treturn appConf, nil\n\t}\n\tfilename, err := appConf.getEnvConfigPath(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = toml.DecodeFile(filename, appConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"使用配置文件: %s\", filename)\n\t// mark appConf as loaded\n\tisLoad = true\n\treturn appConf, nil\n}", "func (d *Datastore) Load() (Object, error) {\n\td.localLock.Lock()\n\tdefer d.localLock.Unlock()\n\n\t// clear Object first, as mapstructure's decoder doesn't have ZeroFields set to true for merging purposes\n\td.meta.Object = d.meta.Object[:0]\n\n\terr := d.kv.LoadConfig(d.meta)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = d.meta.unmarshall()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.meta.object, nil\n}", "func (ctx *AppContext) Load(env string) {\n\tlog.Println(\"Load app context\")\n\n\t// Load env specific config\n\tenvConfig := viper.Sub(env)\n\tctx.Env = env\n\tctx.ProjectID = envConfig.GetString(\"project_id\")\n\tctx.SuffixOfKind = envConfig.GetString(\"datastore.kind_suffix\")\n\tctx.EtcdServers = envConfig.GetStringSlice(\"etcd\")\n\n\t// Load common config\n\tctx.CommonConfig = viper.Sub(\"common\")\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tif err == nil {\n\t\tdecoder := json.NewDecoder(file)\n\t\terr = decoder.Decode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func Load() {\n\tvar err error\n\n\tconfLen := len(FilePath)\n\tif confLen != 0 {\n\t\terr = readFromJSON(FilePath)\n\t}\n\tif err == nil {\n\t\terr = readFromENV()\n\t}\n\tif err != nil {\n\t\tpanic(`Configuration not found. Please specify configuration`)\n\t}\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func TestDnn_LoadModel(t *testing.T) {\n\t//MODEL_PARAM=tmodel.pb,input_1,reshape_3/Reshape\n\tparam := os.Getenv(\"MODEL_PARAM\")\n\tif param == \"\" {\n\t\tt.Skip(\"Skipping model loading test; no MODEL_PARAM set\")\n\t\t//t.Error(\"no MODEL_PARAM set\")\n\t}\n\tstr2dnnfilter := func(inp string) VideoProfile {\n\t\tdnnfilter := VideoProfile{}\n\t\tstrs := strings.Split(inp, \",\")\n\t\tif len(strs) != 3 {\n\t\t\treturn dnnfilter\n\t\t}\n\t\tdnnfilter.Detector.ModelPath = strs[0]\n\t\tdnnfilter.Detector.Input = strs[1]\n\t\tdnnfilter.Detector.Output = strs[2]\n\t\treturn dnnfilter\n\t}\n\n\t_, dir := setupTest(t)\n\tdefer os.RemoveAll(dir)\n\n\tdnncfg := str2dnnfilter(param)\n\n\tif len(dnncfg.Detector.ModelPath) <= 0 || len(dnncfg.Detector.Input) <= 0 || len(dnncfg.Detector.Output) <= 0 {\n\t\tt.Errorf(\"invalid MODEL_PARAM set %v\", param)\n\t}\n\n\tdnnfilter := NewDnnFilter()\n\tdnnfilter.dnncfg = dnncfg\n\tif dnnfilter.InitDnnFilter(dnncfg) != true {\n\t\tt.Errorf(\"Can not load model file %v\", dnncfg.Detector.ModelPath)\n\t}\n\tdnnfilter.StopDnnFilter()\n}", "func (p *Puck) Load(name ...string) error {\n\tcmd := []byte(\"load();\\n\")\n\terr := p.command(name, cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *tomlLoader) Load(out interface{}) error {\n\tif _, err := toml.DecodeReader(l.r, out); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load(key string, data []byte) Entity {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tentity Entity\n\t)\n\n\tbuffer.Write(data)\n\tdecoder := gob.NewDecoder(&buffer)\n\tentityType := strings.Split(key, \".\")[0]\n\n\tswitch entityType {\n\tcase \"player\":\n\t\tentity = new(Player)\n\tcase \"planet\":\n\t\tentity = new(Planet)\n\tcase \"mission\":\n\t\tentity = new(Mission)\n\tcase \"sun\":\n\t\tentity = new(Sun)\n\tcase \"ss\":\n\t\tentity = new(SolarSlot)\n\tcase \"spy_report\":\n\t\tentity = new(SpyReport)\n\tdefault:\n\t\treturn nil\n\t}\n\tdecoder.Decode(entity)\n\treturn entity\n}", "func Load(r io.Reader, v interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSONLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\tif j.Reader != nil {\n\t\tr = j.Reader\n\t} else if j.Path != \"\" {\n\t\tfile, err := getConfig(j.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\treturn json.NewDecoder(r).Decode(s)\n}", "func (y *YAMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif y.Reader != nil {\n\t\tr = y.Reader\n\t} else if y.Path != \"\" {\n\t\tfile, err := getConfig(y.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(data, s)\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func (m *Method) TrainModel(c *gin.Context) {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(c.Request.Body)\n\tJSONStr := buf.String()\n\tm.GoPython(`ml.py`, JSONStr)\n\n\tvar response Response = Response{Status: `model training started`}\n\tc.JSON(http.StatusOK, response)\n}", "func (tfl tiltfileLoader) Load(ctx context.Context, tf *corev1alpha1.Tiltfile, prevResult *TiltfileLoadResult) TiltfileLoadResult {\n\tstart := time.Now()\n\tfilename := tf.Spec.Path\n\tabsFilename, err := ospath.RealAbs(tf.Spec.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn TiltfileLoadResult{\n\t\t\t\tConfigFiles: []string{filename},\n\t\t\t\tError: fmt.Errorf(\"No Tiltfile found at paths '%s'. Check out https://docs.tilt.dev/tutorial.html\", filename),\n\t\t\t}\n\t\t}\n\t\tabsFilename, _ = filepath.Abs(filename)\n\t\treturn TiltfileLoadResult{\n\t\t\tConfigFiles: []string{absFilename},\n\t\t\tError: err,\n\t\t}\n\t}\n\n\ttiltignorePath := watch.TiltignorePath(absFilename)\n\ttlr := TiltfileLoadResult{\n\t\tConfigFiles: []string{absFilename, tiltignorePath},\n\t}\n\n\ttiltignore, err := watch.ReadTiltignore(tiltignorePath)\n\n\t// missing tiltignore is fine, but a filesystem error is not\n\tif err != nil {\n\t\ttlr.Error = err\n\t\treturn tlr\n\t}\n\n\ttlr.Tiltignore = tiltignore\n\n\ts := newTiltfileState(ctx, tfl.dcCli, tfl.webHost, tfl.execer, tfl.k8sContextPlugin, tfl.versionPlugin,\n\t\ttfl.configPlugin, tfl.extensionPlugin, tfl.ciSettingsPlugin, feature.FromDefaults(tfl.fDefaults))\n\n\tmanifests, result, err := s.loadManifests(tf)\n\n\ttlr.BuiltinCalls = result.BuiltinCalls\n\ttlr.DefaultRegistry = s.defaultReg\n\n\t// All data models are loaded with GetState. We ignore the error if the state\n\t// isn't properly loaded. This is necessary for handling partial Tiltfile\n\t// execution correctly, where some state is correctly assembled but other\n\t// state is not (and should be assumed empty).\n\tws, _ := watch.GetState(result)\n\ttlr.WatchSettings = ws\n\n\t// NOTE(maia): if/when add secret settings that affect the engine, add them to tlr here\n\tss, _ := secretsettings.GetState(result)\n\ts.secretSettings = ss\n\n\tioState, _ := io.GetState(result)\n\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, ioState.Paths...)\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, s.postExecReadFiles...)\n\ttlr.ConfigFiles = sliceutils.DedupedAndSorted(tlr.ConfigFiles)\n\n\tdps, _ := dockerprune.GetState(result)\n\ttlr.DockerPruneSettings = dps\n\n\taSettings, _ := tiltfileanalytics.GetState(result)\n\ttlr.AnalyticsOpt = aSettings.Opt\n\n\ttlr.Secrets = s.extractSecrets()\n\ttlr.FeatureFlags = s.features.ToEnabled()\n\ttlr.Error = err\n\ttlr.Manifests = manifests\n\ttlr.TeamID = s.teamID\n\n\tobjectSet, _ := v1alpha1.GetState(result)\n\ttlr.ObjectSet = objectSet\n\n\tvs, _ := version.GetState(result)\n\ttlr.VersionSettings = vs\n\n\ttelemetrySettings, _ := telemetry.GetState(result)\n\ttlr.TelemetrySettings = telemetrySettings\n\n\tus, _ := updatesettings.GetState(result)\n\ttlr.UpdateSettings = us\n\n\tci, _ := cisettings.GetState(result)\n\ttlr.CISettings = ci\n\n\tconfigSettings, _ := config.GetState(result)\n\tif tlr.Error == nil {\n\t\ttlr.EnabledManifests, tlr.Error = configSettings.EnabledResources(tf, manifests)\n\t}\n\n\tduration := time.Since(start)\n\tif tlr.Error == nil {\n\t\ts.logger.Infof(\"Successfully loaded Tiltfile (%s)\", duration)\n\t}\n\textState, _ := tiltextension.GetState(result)\n\thashState, _ := hasher.GetState(result)\n\n\tvar prevHashes hasher.Hashes\n\tif prevResult != nil {\n\t\tprevHashes = prevResult.Hashes\n\t}\n\ttlr.Hashes = hashState.GetHashes()\n\n\ttfl.reportTiltfileLoaded(s.builtinCallCounts, s.builtinArgCounts, duration,\n\t\textState.ExtsLoaded, prevHashes, tlr.Hashes)\n\n\tif len(aSettings.CustomTagsToReport) > 0 {\n\t\treportCustomTags(tfl.analytics, aSettings.CustomTagsToReport)\n\t}\n\n\treturn tlr\n}", "func (k *Kluster) Load() error {\n\tif err := k.LoadSummary(); err != nil {\n\t\treturn err\n\t}\n\n\t// DEBUG:\n\t// fmt.Printf(\"DEBUG: cluster %s config version: %s\\tMin: %s\\tMax: %s\\n\", k.Name, k.Version, MinSemVersion, SemVersion)\n\n\tver, err := version.NewSemVer(k.Version)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"the cluster version (%s) is not well formed or not SemVer compliance. %s\", k.Version, err)\n\t}\n\tif ver.LT(MinSemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is not supported by this KubeKit, the minimun version supported is %s\", k.Version, MinVersion)\n\t}\n\tif ver.GT(SemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is greater than the cluster version supported by this KubeKit (%s)\", k.Version, Version)\n\t}\n\n\tk.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tname := k.Platform()\n\tconfig := k.Platforms[name]\n\n\tcred, err := k.GetCredentials()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tplatform, err := provisioner.NewPlatform(name, k.Name, config, cred, k.ui, k.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.provisioner[name] = platform\n\n\treturn nil\n}", "func (c *Info) Load() error {\n\tb, err := ioutil.ReadFile(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Lock()\n\terr = json.Unmarshal(b, c)\n\tc.Unlock()\n\n\treturn err\n}", "func Load(filename string) (*Beam, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treader := bufio.NewReader(f)\n\tdecoder := json.NewDecoder(reader)\n\tdecoder.DisallowUnknownFields()\n\tcfg := new(Beam)\n\t// This **Beam double-pointer appears to be required to detect an invalid\n\t// input of \"null\". See Test_Load/file_contains_null test.\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding JSON value in %v: %v\", filename, err)\n\t}\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"loading %v resulted in nil config\", filename)\n\t}\n\tif decoder.More() {\n\t\treturn nil, fmt.Errorf(\"found unexpected data after config in %v\", filename)\n\t}\n\treturn cfg, nil\n}", "func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}", "func (s *Startup) Load() error {\n\n\t// TODO: parameterize startup config file name\n\tjsonFile, err := ioutil.ReadFile(\"startup.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(jsonFile, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil // no error\n}", "func (component *Component) Load(filename string) error {\n\treturn util.LoadYAML(filename, component)\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func (s *EnvironmentSource) Load(_ *schema.StructValidator) (err error) {\n\tkeyMap, ignoredKeys := getEnvConfigMap(schema.Keys, s.prefix, s.delimiter)\n\n\treturn s.koanf.Load(env.ProviderWithValue(s.prefix, constDelimiter, koanfEnvironmentCallback(keyMap, ignoredKeys, s.prefix, s.delimiter)), nil)\n}", "func Load(filename string, data any, validation bool) error {\n\tisJSON := strings.HasSuffix(filename, \".json\")\n\n\tbs, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif validation {\n\t\terr := validate(bs, data, isJSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn unmarshal(bs, data, isJSON)\n}", "func Load(env string) *Configuration {\n\t_, filePath, _, _ := runtime.Caller(0)\n\tconfigName := \"config.\" + env + \".yaml\"\n\tconfigPath := filePath[:len(filePath)-9] + \"files\" + string(filepath.Separator)\n\n\tviper.SetConfigName(configName)\n\tviper.AddConfigPath(configPath)\n\tviper.SetConfigType(\"yaml\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Configuration\n\tviper.Unmarshal(&config)\n\tsetGinMode(config.Server.Mode)\n\n\treturn &config\n}", "func Load(path string) (*LevelDB, error) {\n\treturn LoadWithOptions(path, DefaultOptions)\n}", "func Load(name string, data interface{}) error {\n\tp := jsonPath(name)\n\t// Don't load anything if the file doesn't exist\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"File %s didn't exist, loading with fresh data\\n\", p)\n\t\treturn nil\n\t}\n\n\t// Read and unmarshal the json\n\tif b, err := ioutil.ReadFile(p); err != nil {\n\t\treturn err\n\t} else if len(b) == 0 {\n\t\tlog.Printf(\"File %s was empty, loading with fresh data\\n\", p)\n\t\treturn nil\n\t} else if err := json.Unmarshal(b, data); err != nil {\n\t\treturn fmt.Errorf(\"failed to load file %s error: %s\", p, err)\n\t}\n\n\tlog.Printf(\"Loaded %s\\n\", p)\n\treturn nil\n}", "func (rs *Restake) LoadProto(pbAct *iotextypes.StakeRestake) error {\n\tif pbAct == nil {\n\t\treturn ErrNilProto\n\t}\n\n\trs.bucketIndex = pbAct.GetBucketIndex()\n\trs.payload = pbAct.GetPayload()\n\trs.duration = pbAct.GetStakedDuration()\n\trs.autoStake = pbAct.GetAutoStake()\n\n\treturn nil\n}", "func (config *Config) Load() error {\n\tvar env string\n\tflag.StringVar(&env, \"env\", \"dev\", \"environment\")\n\n\tflag.Parse()\n\n\tviperRegistry := viper.New()\n\tviperRegistry.AddConfigPath(\"./config\")\n\tviperRegistry.SetConfigName(env)\n\tviperRegistry.SetConfigType(\"json\")\n\tviperRegistry.SetEnvPrefix(\"todo\")\n\tviperRegistry.AutomaticEnv()\n\n\tconfig.Env = env\n\n\tif err := viperRegistry.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureApplication(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureDB(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureAuth(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (wlt *Wallet) Load(dir string) error {\n\tr := &ReadableWallet{}\n\tif err := r.Load(filepath.Join(dir, wlt.GetFilename())); err != nil {\n\t\treturn err\n\t}\n\tr.Meta[\"filename\"] = wlt.GetFilename()\n\t*wlt = NewWalletFromReadable(r)\n\treturn nil\n}", "func Load(filepath string, startTag, endTag string, vars map[string]string) (result string, err error) {\n\tvar data []byte\n\tif data, err = ioutil.ReadFile(filepath); err == nil {\n\t\tvar tpl *Engine\n\t\tif tpl, err = New(string(data), startTag, endTag); err == nil {\n\t\t\tif result, err = tpl.Process(vars); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if err == errs.TmplVarsNotFoundError {\n\t\t\terr = nil\n\t\t\tresult = string(data)\n\t\t}\n\t}\n\treturn\n}", "func (l *Loader) Load(cfg *config.Config) {\n\tcfg.Address = os.Getenv(\"BRCEP_ADDRESS\")\n\tcfg.LogLevel = os.Getenv(\"BRCEP_LOG_LEVEL\")\n\tcfg.PreferredAPI = os.Getenv(\"BRCEP_PREFERRED_API\")\n\tcfg.ViaCepURL = os.Getenv(\"BRCEP_VIACEP_URL\")\n\tcfg.CepAbertoURL = os.Getenv(\"BRCEP_CEPABERTO_URL\")\n\tcfg.CepAbertoToken = os.Getenv(\"BRCEP_CEPABERTO_TOKEN\")\n\tcfg.CorreiosURL = os.Getenv(\"BRCEP_CORREIOS_URL\")\n}", "func Load(cfg interface{}, configPath string) error {\n\tif err := readConfigFile(configPath, cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ClusterState == nil {\n\t\tcfg.ClusterState = &ClusterState{}\n\t}\n\tif cfg.ALBIngressController == nil {\n\t\tcfg.ALBIngressController = &ALBIngressController{}\n\t}\n\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.ClusterState.UpTook != \"\" {\n\t\tcfg.ClusterState.upTook, err = time.ParseDuration(cfg.ClusterState.UpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif cfg.ALBIngressController.IngressUpTook != \"\" {\n\t\tcfg.ALBIngressController.ingressUpTook, err = time.ParseDuration(cfg.ALBIngressController.IngressUpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}" ]
[ "0.7085643", "0.69431984", "0.6932099", "0.6917992", "0.6769626", "0.6714895", "0.66320646", "0.65712345", "0.6427181", "0.63659275", "0.6345356", "0.621093", "0.6208571", "0.6141206", "0.61269116", "0.5931221", "0.59096044", "0.5825058", "0.5803748", "0.57919365", "0.5693847", "0.5683366", "0.56767374", "0.56292784", "0.5624385", "0.55193293", "0.5495749", "0.5493969", "0.5485269", "0.54705644", "0.5465092", "0.54615253", "0.5448914", "0.54356927", "0.5431235", "0.541998", "0.53928435", "0.5383786", "0.537842", "0.536521", "0.5361996", "0.5340348", "0.53098965", "0.5309197", "0.52518165", "0.52435017", "0.52435017", "0.52092385", "0.520087", "0.5190345", "0.518786", "0.51790744", "0.5176909", "0.5174301", "0.51731753", "0.5158658", "0.5153371", "0.51488847", "0.51428366", "0.5137322", "0.5135956", "0.51350635", "0.51174474", "0.51038814", "0.51012915", "0.50976473", "0.5095744", "0.5080098", "0.50709814", "0.50226396", "0.50183856", "0.50166696", "0.50137836", "0.5002305", "0.49860403", "0.49712187", "0.49673748", "0.4961709", "0.4961118", "0.49562728", "0.4945565", "0.49444407", "0.49324235", "0.4930704", "0.492458", "0.49196434", "0.49171466", "0.490406", "0.49027896", "0.4899536", "0.48968464", "0.48820436", "0.48750725", "0.48724598", "0.4869488", "0.48687747", "0.48672825", "0.48576173", "0.48449257", "0.48351178" ]
0.6648425
6
ForwardT forwards pass through the model.
func (tc *RobertaForTokenClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) { hiddenState, _, hiddenStates, attentions, err := tc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train) if err != nil { return ts.None, nil, nil, err } appliedDO := hiddenState.ApplyT(tc.dropout, train) output = appliedDO.Apply(tc.classifier) appliedDO.MustDrop() return output, hiddenStates, attentions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mod *backendModule) Forward(f *gatepb.Forward) error {\n\treturn mod.send(proto.Type(f.Typ), f)\n}", "func (m *Model) Forward(qkv attention.QKV) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: m.Key.Forward(qkv.Keys...),\n\t\tValues: m.Value.Forward(qkv.Values...),\n\t}\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (m *Model) Forward(x *Node, states States) (rv *Node, err error) {\n\trv = x\n\tfor _, l := range m.Layers {\n\t\tif rv, err = l.Forward(rv, states); err != nil {\n\t\t\treturn nil, errors.Wrap(err, l.Name())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\th := nn.Affine(g, m.B, m.W, x)\n\tif yPrev != nil {\n\t\th = g.Add(h, g.Prod(m.WRec, yPrev))\n\t}\n\ts.Y = g.Invoke(m.Activation, h)\n\treturn\n}", "func (obj *Doc) Forward(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"Forward\", nil)\n\treturn err\n}", "func (t *Type) ForwardType() *ForwardType", "func (ch *RobertaClassificationHead) ForwardT(hiddenStates *ts.Tensor, train bool) *ts.Tensor {\n\tappliedDO1 := hiddenStates.MustSelect(1, 0, false).ApplyT(ch.dropout, train)\n\tappliedDense := appliedDO1.Apply(ch.dense)\n\ttanhTs := appliedDense.MustTanh(false)\n\tappliedDO2 := tanhTs.ApplyT(ch.dropout, train)\n\tretVal := appliedDO2.Apply(ch.outProj)\n\n\tappliedDO1.MustDrop()\n\tappliedDense.MustDrop()\n\ttanhTs.MustDrop()\n\tappliedDO2.MustDrop()\n\n\treturn retVal\n}", "func (f *Forwarder) Forward(data *call.CallData) {\n\tf.transferAgents.Range(func(key interface{}, value interface{}) bool {\n\t\tstreamId := key.(userid.ID)\n\t\tstream := value.(TransferAgent)\n\t\tif streamId == userid.ID(data.UserId) { // Don't need to forward data back to sender\n\t\t\treturn true\n\t\t}\n\n\t\tif err := stream.Send(data); err != nil {\n\t\t\tf.logger.Error(err)\n\t\t}\n\n\t\treturn true\n\t})\n}", "func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Ensure our request client does not follow redirects\n\thttpClient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tif config.TLS != nil {\n\t\ttlsConfig, err := config.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\ttracing.SetErrorAndDebugLog(r, \"Unable to configure TLS to call %s. Cause %s\", config.Address, err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(http.MethodGet, config.Address, http.NoBody)\n\ttracing.LogRequest(tracing.GetSpan(r), forwardReq)\n\tif err != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause %s\", config.Address, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteHeader(r, forwardReq, config.TrustForwardHeader)\n\n\ttracing.InjectRequestHeaders(forwardReq)\n\n\tforwardResponse, forwardErr := httpClient.Do(forwardReq)\n\tif forwardErr != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause: %s\", config.Address, forwardErr)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbody, readError := ioutil.ReadAll(forwardResponse.Body)\n\tif readError != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error reading body %s. Cause: %s\", config.Address, readError)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer forwardResponse.Body.Close()\n\n\t// Pass the forward response's body and selected headers if it\n\t// didn't return a response within the range of [200, 300).\n\tif forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {\n\t\tlog.Debugf(\"Remote error %s. StatusCode: %d\", config.Address, forwardResponse.StatusCode)\n\n\t\tutils.CopyHeaders(w.Header(), forwardResponse.Header)\n\t\tutils.RemoveHeaders(w.Header(), forward.HopHeaders...)\n\n\t\t// Grab the location header, if any.\n\t\tredirectURL, err := forwardResponse.Location()\n\n\t\tif err != nil {\n\t\t\tif err != http.ErrNoLocation {\n\t\t\t\ttracing.SetErrorAndDebugLog(r, \"Error reading response location header %s. Cause: %s\", config.Address, err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if redirectURL.String() != \"\" {\n\t\t\t// Set the location in our response if one was sent back.\n\t\t\tw.Header().Set(\"Location\", redirectURL.String())\n\t\t}\n\n\t\ttracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)\n\t\tw.WriteHeader(forwardResponse.StatusCode)\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tfor _, headerName := range config.AuthResponseHeaders {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tr.Header.Del(headerKey)\n\t\tif len(forwardResponse.Header[headerKey]) > 0 {\n\t\t\tr.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)\n\t\t}\n\t}\n\n\tr.RequestURI = r.URL.RequestURI()\n\tnext(w, r)\n}", "func (q *CQPU) forward(predicate []*pbUtils.AttributePredicate, streamRec *pbQPU.ResponseStreamRecord, streamOut pbQPU.QPU_QueryServer, seqID *int64, respond bool) error {\n\tif respond {\n\t\terr := streamOut.Send(\n\t\t\tprotoutils.ResponseStreamRecord(\n\t\t\t\t*seqID,\n\t\t\t\tstreamRec.GetType(),\n\t\t\t\tstreamRec.GetLogOp(),\n\t\t\t))\n\t\t(*seqID)++\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *Transaction) forwardTransaction() {\n\tif t.tx == nil {\n\t\tpanic(\"tx is nil while forward was being called\")\n\t}\n\tselect {\n\tcase t.sendTxFound <- t.tx:\n\tcase <-t.shutdown:\n\t\treturn\n\t}\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\ts.InG = g.Sigmoid(nn.Affine(g, m.BIn, m.WIn, x, m.WInRec, yPrev))\n\ts.ForG = g.Sigmoid(nn.Affine(g, m.BFor, m.WFor, x, m.WForRec, yPrev))\n\ts.Cand = g.Tanh(g.Mul(m.WCand, x))\n\ts.Y = g.Prod(s.InG, s.Cand)\n\tif yPrev != nil {\n\t\ts.Y = g.Add(s.Y, g.Prod(g.Tanh(yPrev), s.ForG))\n\t}\n\treturn\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func (rt *Router) forward() {\n\tfor i, v := range rt.InInterfaceL {\n\t\t//pktS := \"\"\n\n\t\t// TRYE\n\t\t// get packet from interface i\n\t\tif pktS, err := v.Get(); err == nil {\n\t\t\t//fmt.Println(\"in routher forward, packet from Get(): \", pktS)\n\t\t\t// if packet exists make a forwarding decision\n\t\t\tp, err := FromByteS(pktS)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not get packet\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// HERE you will need to implement a lookup into the\n\t\t\t// forwarding table to find the appropriate outgoing interface\n\t\t\t// for now we assume the outgoing interface is also i\n\t\t\tfmt.Printf(\"%s: forwarding packet %s from interface %d to %d with mtu %d\\n\", rt.Str(), p.Str(), i, i, rt.OutInterfaceL[i].Mtu)\n\n\t\t\tif err = rt.OutInterfaceL[i].Put(p.ToByteS(), false); err != nil {\n\t\t\t\t//log.Printf(\"Could not put packet %s in router %s, into outInterface %d. Error: %s\", p.str, rt.forward, i, err)\n\t\t\t\tlog.Printf(\"%s: packet '%s' lost on interface %d\\n\", rt.Str(), i)\n\t\t\t}\n\t\t}\n\t\t//log.Println(\"no packet to forard in router\")\n\t}\n}", "func (ph *Handler) Forward() {\n\terr := recover()\n\tph.forward(err)\n}", "func (tr *Peer) FastForward(ctx context.Context, target string,\n\treq *FastForwardRequest, resp *FastForwardResponse) error {\n\n\tif tr.isShutdown() {\n\t\treturn ErrTransportStopped\n\t}\n\n\ttr.wg.Add(1)\n\tdefer tr.wg.Done()\n\n\treturn tr.fastForward(ctx, target, req, resp)\n}", "func (inst *instance) Forward(port int) (string, error) {\n\tvar reply proxyrpc.ForwardResult\n\terr := inst.ProxyApp.Call(\n\t\t\"ProxyVM.Forward\",\n\t\tproxyrpc.ForwardParams{\n\t\t\tID: inst.ID,\n\t\t\tPort: port,\n\t\t},\n\t\t&reply)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reply.ManagerAddress, nil\n}", "func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tlabels = sc.classifier.ForwardT(hiddenState, train)\n\thiddenState.MustDrop()\n\n\treturn labels, hiddenStates, attentions, nil\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tg := m.Graph()\n\thalfSize := xs[0].Value().Size() / 2\n\n\tres := make([]ag.Node, len(xs))\n\tgate := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tres[i] = g.View(x, 0, 0, halfSize, 1)\n\t\tgate[i] = g.View(x, halfSize, 0, halfSize, 1)\n\t}\n\n\tgate = m.Norm.Forward(gate...)\n\tgate = m.Proj.Forward(gate...)\n\n\tif m.Act != nil {\n\t\tgate = m.Act.Forward(gate...)\n\t}\n\n\ty := make([]ag.Node, len(gate))\n\tfor i := range y {\n\t\ty[i] = g.Prod(gate[i], res[i])\n\t}\n\treturn y\n}", "func (a *provisionApp) forward(app *App, args ...interface{}) error {\n\tvar units uint\n\tif len(args) > 0 {\n\t\tswitch args[0].(type) {\n\t\tcase int:\n\t\t\tunits = uint(args[0].(int))\n\t\tcase int64:\n\t\t\tunits = uint(args[0].(int64))\n\t\tcase uint:\n\t\t\tunits = args[0].(uint)\n\t\tcase uint64:\n\t\t\tunits = uint(args[0].(uint64))\n\t\tdefault:\n\t\t\tunits = 1\n\t\t}\n\t}\n\terr := Provisioner.Provision(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif units > 1 {\n\t\t_, err = Provisioner.AddUnits(app, units-1)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *Model) Forward(cache Cache, q, x []mat.Tensor) ([]mat.Tensor, []mat.Tensor, Cache) {\n\tvar pk, pv mat.Tensor\n\n\tpq := m.Query.Forward(q...)\n\n\tif hasCache := cache.HasValues(); hasCache && m.IsCrossAttention {\n\t\tpk = cache[0]\n\t\tpv = cache[1]\n\t} else {\n\t\tk := m.Key.Forward(x...)\n\t\tv := m.Value.Forward(x...)\n\n\t\tif hasCache {\n\t\t\tpk = ag.AppendRows(cache[0], k...)\n\t\t\tpv = ag.AppendRows(cache[1], v...)\n\t\t} else {\n\t\t\tpk = ag.Stack(k...)\n\t\t\tpv = ag.Stack(v...)\n\t\t}\n\t}\n\n\tresult, weights := attention.ScaledDotProductAttention(pq, pk, pv, m.ScaleFactor, m.UseCausalMask)\n\n\treturn result, weights, Cache{pk, pv}\n}", "func (b *TestDriver) Forward(val int) error {\n\tlog.Printf(\"Forward: %d\", val)\n\n\treturn nil\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train)\n\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tpredictionScores := mlm.lmHead.Forward(hiddenState)\n\n\treturn predictionScores, allHiddenStates, allAttentions, nil\n}", "func (rh *RobertaLMHead) Forward(hiddenStates *ts.Tensor) *ts.Tensor {\n\tgelu := util.NewGelu()\n\tappliedDense := hiddenStates.Apply(rh.dense)\n\tgeluFwd := gelu.Fwd(appliedDense)\n\tappliedLN := geluFwd.Apply(rh.layerNorm)\n\tappliedDecoder := appliedLN.Apply(rh.decoder)\n\tappliedBias := appliedDecoder.MustAdd(rh.bias, true)\n\n\tgeluFwd.MustDrop()\n\tappliedDense.MustDrop()\n\tappliedLN.MustDrop()\n\n\treturn appliedBias\n}", "func (ti *TimeIndex) iterForward(t time.Time) index.Iter {\n i := ti.IndexNear(t)\n return &forwardIter{\n at: i,\n ti: ti,\n }\n}", "func (req *RequestData) Forward(client *http.Client, config BasketConfig, basket string) (*http.Response, error) {\n\tforwardURL, err := url.ParseRequestURI(config.ForwardURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid forward URL: %s - %s\", config.ForwardURL, err)\n\t}\n\n\t// expand path\n\tif config.ExpandPath && len(req.Path) > len(basket)+1 {\n\t\tforwardURL.Path = expandURL(forwardURL.Path, req.Path, basket)\n\t}\n\n\t// append query\n\tif len(req.Query) > 0 {\n\t\tif len(forwardURL.RawQuery) > 0 {\n\t\t\tforwardURL.RawQuery += \"&\" + req.Query\n\t\t} else {\n\t\t\tforwardURL.RawQuery = req.Query\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(req.Method, forwardURL.String(), strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create forward request: %s\", err)\n\t}\n\n\t// copy headers\n\tfor header, vals := range req.Header {\n\t\tfor _, val := range vals {\n\t\t\tforwardReq.Header.Add(header, val)\n\t\t}\n\t}\n\t// headers cleanup\n\tforwardHeadersCleanup(forwardReq)\n\t// set do not forward header\n\tforwardReq.Header.Set(DoNotForwardHeader, \"1\")\n\n\t// forward request\n\tresponse, err := client.Do(forwardReq)\n\tif err != nil {\n\t\t// HTTP issue during forwarding - HTTP 502 Bad Gateway\n\t\tlog.Printf(\"[warn] failed to forward request for basket: %s - %s\", basket, err)\n\t\tbadGatewayResp := &http.Response{\n\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(\"Failed to forward request: %s\", err)))}\n\t\tbadGatewayResp.Header.Set(\"Content-Type\", \"text/plain\")\n\n\t\treturn badGatewayResp, nil\n\t}\n\n\treturn response, nil\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (l *AffineLayer) Forward(x mat.Matrix) mat.Matrix {\n\t_, c := x.Dims()\n\tif c != l.dimIn {\n\t\tpanic(fmt.Sprintf(\"expect %d but got %d\", l.dimIn, c))\n\t}\n\tl.x = x\n\tvar ret mat.Dense\n\tret.Mul(x, l.Weight)\n\tret.Apply(func(i, j int, val float64) float64 {\n\t\treturn l.Bias.At(j, 0) + val\n\t}, &ret)\n\treturn &ret\n}", "func (r *Lachesis) FastForward(\n\treq *net.FastForwardRequest, resp *net.FastForwardResponse) error {\n\tresult, err := r.process(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, ok := result.(*net.FastForwardResponse)\n\tif !ok {\n\t\treturn ErrBadResult\n\t}\n\t*resp = *item\n\treturn nil\n}", "func (n *Network) Forward() {\n\tif !n.constructed() {\n\t\tlog.Panic(\"Cannot run an emtpy Network\")\n\t}\n\n\tfor l := range n.layers {\n\t\tcandy.Must(parallel.For(0, len(n.layers[l]), 1, func(g int) {\n\t\t\tgate := n.layers[l][g]\n\t\t\tgate.forward(gate)\n\t\t}))\n\t}\n}", "func (m *Linear) Forward(x mat.Tensor) mat.Tensor {\n\treturn ag.Add(ag.Mul(m.W, x), m.B)\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (a *insertApp) forward(app *App, args ...interface{}) error {\n\tapp.State = \"pending\"\n\treturn db.Session.Apps().Insert(app)\n}", "func (o *OutboundDispatcher) Forward(msg interface{}, des *service.Destination) error {\n\tfor _, v := range o.outboundTransports {\n\t\tif !v.AcceptRecipient(des.RecipientKeys) {\n\t\t\tif !v.Accept(des.ServiceEndpoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treq, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed marshal to bytes: %w\", err)\n\t\t}\n\n\t\t_, err = v.Send(req, des)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send msg using outbound transport: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no outbound transport found for serviceEndpoint: %s\", des.ServiceEndpoint)\n}", "func (m *Model) StepForward(ns Nodes) (rv Nodes, err error) {\n\tstates := States{}\n\tvar tmp *Node\n\tfor _, x := range ns {\n\t\tif tmp, err = m.Forward(x, states); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trv = append(rv, tmp)\n\t}\n\treturn rv, nil\n}", "func (c *ManetConnection) forward(bytes []byte) {\n\tincomingHeader := data.PacketHeaderFromBytes(bytes)\n\n\tcached := c.inCache(incomingHeader.SequenceNumber, incomingHeader.SendKey)\n\tfmt.Println(\"CACHE: \", incomingHeader.SequenceNumber, incomingHeader.SendKey, cached)\n\n\tif cached || incomingHeader.TTL <= 1 {\n\t\tfmt.Println(\"DROP!\")\n\t\treturn\n\t}\n\n\tc.cache[incomingHeader.SequenceNumber] = incomingHeader.SendKey\n\tdelete(c.cache, incomingHeader.SequenceNumber-cacheDepth)\n\n\toutgoingHeader := &data.PacketHeader{\n\t\tSourceAddress: incomingHeader.SourceAddress,\n\t\tDestinationAddress: incomingHeader.DestinationAddress,\n\t\tPreviousHop: GetMyAddress(),\n\t\tTTL: incomingHeader.TTL - 1,\n\t\tPacketType: incomingHeader.PacketType,\n\t\tSequenceNumber: incomingHeader.SequenceNumber,\n\t\tNumBytes: incomingHeader.NumBytes,\n\t\tSendKey: incomingHeader.SendKey,\n\t}\n\n\tfor i, b := range outgoingHeader.ToBytes() {\n\t\tbytes[i] = b\n\t}\n\n\tfor neighbor := range myNeighbors {\n\t\tif neighbor == incomingHeader.PreviousHop {\n\t\t\tcontinue\n\t\t}\n\t\traddr := ToUDPAddr(neighbor)\n\t\tfmt.Println(\"FORWARD to\", neighbor, \"DEST: \", incomingHeader.DestinationAddress, \"aka\", raddr)\n\t\tif _, err := c.conn.WriteToUDP(bytes, raddr); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (s *Service) Forward(topicID, msgID, targetAddr, text string) error {\n\tpayload := map[string]interface{}{\n\t\t\"id\": msgID,\n\t\t\"address\": targetAddr,\n\t\t\"text\": text,\n\t}\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpf, err := s.client.Publish(topicID, b, 2, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pf.Wait(5 * time.Second)\n}", "func (r *RotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := Rotate(fx, r.angle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func (mc *RobertaForMultipleChoice) ForwardT(inputIds, mask, tokenTypeIds, positionIds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\tnumChoices := inputIds.MustSize()[1]\n\n\tinputIdsSize := inputIds.MustSize()\n\tflatInputIds := inputIds.MustView([]int64{-1, inputIdsSize[len(inputIdsSize)-1]}, false)\n\n\tflatPositionIds := ts.None\n\tif positionIds.MustDefined() {\n\t\tpositionIdsSize := positionIds.MustSize()\n\t\tflatPositionIds = positionIds.MustView([]int64{-1, positionIdsSize[len(positionIdsSize)-1]}, false)\n\t}\n\n\tflatTokenTypeIds := ts.None\n\tif tokenTypeIds.MustDefined() {\n\t\ttokenTypeIdsSize := tokenTypeIds.MustSize()\n\t\tflatTokenTypeIds = tokenTypeIds.MustView([]int64{-1, tokenTypeIdsSize[len(tokenTypeIdsSize)-1]}, false)\n\t}\n\n\tflatMask := ts.None\n\tif mask.MustDefined() {\n\t\tflatMaskSize := flatMask.MustSize()\n\t\tflatMask = mask.MustView([]int64{-1, flatMaskSize[len(flatMaskSize)-1]}, false)\n\t}\n\n\tvar pooledOutput *ts.Tensor\n\t_, pooledOutput, hiddenStates, attentions, err = mc.roberta.ForwardT(flatInputIds, flatMask, flatTokenTypeIds, flatPositionIds, ts.None, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := pooledOutput.ApplyT(mc.dropout, train)\n\tappliedCls := appliedDO.Apply(mc.classifier)\n\toutput = appliedCls.MustView([]int64{-1, numChoices}, true)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (b *BaseController) Forward(title, templateName string) {\n\tb.Layout = filepath.Join(prefixNg, \"layout.htm\")\n\tb.TplName = filepath.Join(prefixNg, templateName)\n\tb.Data[\"Title\"] = b.Tr(title)\n\tb.LayoutSections = make(map[string]string)\n\tb.LayoutSections[\"HeaderInclude\"] = filepath.Join(prefixNg, viewPath, \"header-include.htm\")\n\n\tif b.UseCompressedJS {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-min-include.htm\")\n\t} else {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-include.htm\")\n\t}\n\n\tlog.Debugf(\"Loaded HeaderScriptInclude file: %s\", b.LayoutSections[\"HeaderScriptInclude\"])\n\n\tb.LayoutSections[\"FooterInclude\"] = filepath.Join(prefixNg, viewPath, \"footer-include.htm\")\n\tb.LayoutSections[\"HeaderContent\"] = filepath.Join(prefixNg, viewPath, \"header-content.htm\")\n\tb.LayoutSections[\"FooterContent\"] = filepath.Join(prefixNg, viewPath, \"footer-content.htm\")\n\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (lay *Layer) Forward(x *mat.Dense) (a *mat.Dense) {\n\t// x is (n x in )\n\trow, _ := x.Dims()\n\n\txx := new(mat.Dense)\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\tz.Apply(func(i, j int, v float64) float64 { return lay.act.f(v) }, z)\n\treturn z\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tys := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = m.forward(x)\n\t}\n\treturn ys\n}", "func processForward(forward *chproto.ChangeForward) {\n\n\t// If we are already trying to forward a change forward message with\n\t// the same requesting node and request ID, discard this message.\n\tif _, exists := getForwardTimeout(uint16(*forward.Request.RequestNode),\n\t\t*forward.Request.RequestId); exists {\n\t\treturn\n\t}\n\n\t// Everything else in this function runs in a transaction.\n\t// We are read-only.\n\tstore.StartTransaction()\n\tdefer store.EndTransaction()\n\n\t// If this is a core node and this node stopped being leader less than\n\t// a Change Timeout Period ago, always add us to the ignore list.\n\tif config.IsCore() && !isIgnored(forward, config.Id()) {\n\t\tdiff := time.Now().Sub(store.StoppedLeading())\n\t\tif diff < config.CHANGE_TIMEOUT_PERIOD {\n\t\t\tforward.Ignores = append(forward.Ignores,\n\t\t\t\tuint32(config.Id()))\n\t\t}\n\t}\n\n\t// If all core node IDs are in the forward's ignore list, discard it.\n\tif len(forward.Ignores) == len(config.CoreNodes()) {\n\t\tlog.Print(\"shared/chrequest: dropped msg due to full ignores\")\n\t\treturn\n\t}\n\n\t// Otherwise, choose a potential leader node.\n\t// This is O(n^2) in the number of core nodes,\n\t// but we don't expect to have many.\n\tchosenNode := uint16(0)\n\t_, leader := store.Proposal()\n\tif leader != 0 && !isIgnored(forward, leader) {\n\t\tchosenNode = leader\n\t} else {\n\t\tfor _, node := range config.CoreNodes() {\n\t\t\tif !isIgnored(forward, node) {\n\t\t\t\tchosenNode = node\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif chosenNode == 0 {\n\t\t// Shouldn't happen.\n\t\tlog.Print(\"shared/chrequest: bug, \" +\n\t\t\t\"couldn't find candidate leader node\")\n\t\treturn\n\t}\n\n\t// If we are the selected leader, construct an external change request,\n\t// and send it on our change request channel.\n\tif chosenNode == config.Id() {\n\t\tintRequest := forward.Request\n\t\tchrequest := new(store.ChangeRequest)\n\t\tchrequest.RequestEntity = *intRequest.RequestEntity\n\t\tchrequest.RequestNode = uint16(*intRequest.RequestNode)\n\t\tchrequest.RequestId = *intRequest.RequestId\n\t\tchrequest.Changeset = make([]store.Change,\n\t\t\tlen(intRequest.Changeset))\n\n\t\tfor i, ch := range intRequest.Changeset {\n\t\t\tchrequest.Changeset[i].TargetEntity = *ch.TargetEntity\n\t\t\tchrequest.Changeset[i].Key = *ch.Key\n\t\t\tchrequest.Changeset[i].Value = *ch.Value\n\t\t}\n\n\t\tfor _, cb := range changeCallbacks {\n\t\t\tcb(chrequest)\n\t\t}\n\n\t\treturn\n\t}\n\n\t// Otherwise, we send it on to the selected leader,\n\t// add the selected leader to the ignore list,\n\t// and set a timeout to retry.\n\tsendForward(chosenNode, forward)\n\tforward.Ignores = append(forward.Ignores, uint32(chosenNode))\n\taddForwardTimeout(forward)\n}", "func (f *Forward) Forward(state request.Request) (*dns.Msg, error) {\n\tif f == nil {\n\t\treturn nil, ErrNoForward\n\t}\n\n\tfails := 0\n\tvar upstreamErr error\n\tfor _, proxy := range f.List() {\n\t\tif proxy.Down(f.maxfails) {\n\t\t\tfails++\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// All upstream proxies are dead, assume healtcheck is complete broken and randomly\n\t\t\t// select an upstream to connect to.\n\t\t\tproxy = f.List()[0]\n\t\t}\n\n\t\tret, err := proxy.Connect(context.Background(), state, f.opts)\n\n\t\tret, err = truncated(state, ret, err)\n\t\tupstreamErr = err\n\n\t\tif err != nil {\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if the reply is correct; if not return FormErr.\n\t\tif !state.Match(ret) {\n\t\t\treturn state.ErrorMessage(dns.RcodeFormatError), nil\n\t\t}\n\n\t\treturn ret, err\n\t}\n\n\tif upstreamErr != nil {\n\t\treturn nil, upstreamErr\n\t}\n\n\treturn nil, ErrNoHealthy\n}", "func (r *LeakyReLU[O]) Forward() (mat.Tensor, error) {\n\treturn r.x.Value().(mat.Matrix).ApplyWithAlpha(leakyReLU, r.alpha.Value().Item().F64()), nil\n}", "func (s *Server) Forward(id int64, event api.Event) {\n\tif event.Type == \"logging\" {\n\t\t// Parse the message\n\t\tlogEntry := api.EventLogging{}\n\t\terr := json.Unmarshal(event.Metadata, &logEntry)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && logEntry.Level == \"dbug\" {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && !s.verbose && logEntry.Level == \"info\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := s.broadcast(event, true)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to forward event from member %d: %v\", id, err)\n\t}\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func (t *TimeLine) forward(num, denom uint32, runCallbacks bool) {\n\tend := t.cursor + t.Ticks(num, denom)\n\tif runCallbacks {\n\t\tt.lastDelta = t.runCallbacks(t.cursor, end)\n\t}\n\tt.cursor = end\n}", "func (la *Lattice) Forward(m TokenizeMode) {\n\tfor i, size := 1, len(la.list); i < size; i++ {\n\t\tcurrentList := la.list[i]\n\t\tfor index, target := range currentList {\n\t\t\tprevList := la.list[target.Start]\n\t\t\tif len(prevList) == 0 {\n\t\t\t\tla.list[i][index].Cost = maximumCost\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j, n := range prevList {\n\t\t\t\tvar c int16\n\t\t\t\tif n.Class != USER && target.Class != USER {\n\t\t\t\t\tc = la.dic.Connection.At(int(n.Right), int(target.Left))\n\t\t\t\t}\n\t\t\t\ttotalCost := int64(c) + int64(target.Weight) + int64(n.Cost)\n\t\t\t\tif m != Normal {\n\t\t\t\t\ttotalCost += int64(additionalCost(n))\n\t\t\t\t}\n\t\t\t\tif totalCost > maximumCost {\n\t\t\t\t\ttotalCost = maximumCost\n\t\t\t\t}\n\t\t\t\tif j == 0 || int32(totalCost) < la.list[i][index].Cost {\n\t\t\t\t\tla.list[i][index].Cost = int32(totalCost)\n\t\t\t\t\tla.list[i][index].prev = la.list[target.Start][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (g *game) forward() {\n\tg.player.Parse(g.input)\n\n\tif g.player.IsQuitting() {\n\t\tg.next = g.newMenu()\n\t}\n}", "func (m *EventItemRequestBuilder) Forward()(*i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.ForwardRequestBuilder) {\n return i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.NewForwardRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (fl *follow) forward(r io.Reader) (cont bool) {\n\tfl.Decoder.Reset(r)\n\treturn fl.Forwarder.Do(fl.Watcher, fl.Decoder)\n}", "func (b *RequiredArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) ArgumentNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tif p.RequiresFullSeq() {\n\t\treturn p.fullSeqForward(xs)\n\t}\n\treturn p.incrementalForward(xs)\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tif len(xs) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tmean := ag.ReduceMean(x)\n\t\tdev := ag.SubScalar(x, mean)\n\t\tstdDev := ag.Sqrt(ag.Add(ag.ReduceMean(ag.Square(dev)), m.Eps))\n\t\tout[i] = ag.Add(ag.Prod(ag.DivScalar(dev, stdDev), m.W), m.B)\n\t}\n\treturn out\n}", "func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {\n\tlState := makeFBOLockState()\n\tfbo.headLock.RLock(lState)\n\tdefer fbo.headLock.RUnlock(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t// We're already up to date.\n\t\treturn\n\t}\n\tif !fbo.hasBeenCleared {\n\t\t// No reason to fast-forward here if it hasn't ever been\n\t\t// cleared.\n\t\treturn\n\t}\n\n\tfbo.forcedFastForwards.Add(1)\n\tfbo.goTracked(func() {\n\t\tdefer fbo.forcedFastForwards.Done()\n\t\tctx, cancelFunc := fbo.newCtxWithFBOID()\n\t\tdefer cancelFunc()\n\n\t\tfbo.log.CDebugf(ctx, \"Forcing a fast-forward\")\n\t\tvar currHead ImmutableRootMetadata\n\t\tvar err error\n\tgetMD:\n\t\tfor i := 0; ; i++ {\n\t\t\tcurrHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)\n\t\t\tswitch errors.Cause(err).(type) {\n\t\t\tcase nil:\n\t\t\t\tbreak getMD\n\t\t\tcase kbfsmd.ServerErrorUnauthorized:\n\t\t\t\t// The MD server connection might not be authorized\n\t\t\t\t// yet, so give it a few chances to go through.\n\t\t\t\tif i > 5 {\n\t\t\t\t\tfbo.log.CDebugf(ctx,\n\t\t\t\t\t\t\"Still unauthorized for TLF %s; giving up fast-forward\",\n\t\t\t\t\t\tfbo.id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i == 0 {\n\t\t\t\t\tfbo.log.CDebugf(\n\t\t\t\t\t\tctx, \"Got unauthorized error when fast-forwarding %s; \"+\n\t\t\t\t\t\t\t\"trying again after a delay\", fbo.id())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tdefault:\n\t\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif currHead == (ImmutableRootMetadata{}) {\n\t\t\tfbo.log.CDebugf(ctx, \"No MD yet\")\n\t\t\treturn\n\t\t}\n\t\tfbo.log.CDebugf(ctx, \"Current head is revision %d\", currHead.Revision())\n\n\t\tlState := makeFBOLockState()\n\t\t// Kick off partial prefetching once the latest merged\n\t\t// revision is set.\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tfbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)\n\t\t\t}\n\t\t}()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\tfbo.headLock.Lock(lState)\n\t\tdefer fbo.headLock.Unlock(lState)\n\n\t\tif !fbo.hasBeenCleared {\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t\tfbo.hasBeenCleared = false\n\t\t\t}\n\t\t}()\n\n\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t// We're already up to date.\n\t\t\tfbo.log.CDebugf(ctx, \"Already up-to-date: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = fbo.doFastForwardLocked(ctx, lState, currHead)\n\t\tif err != nil {\n\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %v\", err)\n\t\t}\n\t})\n}", "func (p *Player) Forward() mgl32.Vec3 {\n\treturn p.Speed\n}", "func (n *Node) Forward() FloatXX {\n\tif n.myoutCached {\n\t\treturn n.myout\n\t}\n\n\tif n.myType == InputNode {\n\t\tn.myout = n.inputValue\n\t} else {\n\t\tn.myout = FloatXX(0.0)\n\t\tfor index, otherNode := range n.inputNodes {\n\t\t\toutput := otherNode.Forward()\n\t\t\tn.inputs = append(n.inputs, output)\n\t\t\tn.myout += n.weights[index] * output\n\t\t}\n\t\tn.myout += n.biasValue * n.biasWeight\n\t\tmyoutActivated := n.activation(n.myout)\n\t\tn.myout = myoutActivated\n\t}\n\n\tn.myoutCached = true\n\treturn n.myout\n}", "func (r *Sub[O]) Forward() (mat.Tensor, error) {\n\treturn r.x1.Value().(mat.Matrix).Sub(r.x2.Value().(mat.Matrix)), nil\n}", "func httpForward(store *ForwardStore) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tkey := mux.Vars(r)[\"uid\"]\n\t\tif key == \"\" {\n\t\t\tkey = \"0\"\n\t\t}\n\t\tforward, _ := store.get(key)\n\t\thttp.Redirect(w, r, forward.URL, 302)\n\t}\n}", "func Forward() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\terr := recover() // Have to do recover directly in deferred function\n\tinternalPanicHandler.forward(err)\n}", "func (ms *MVCCStats) Forward(nowNanos int64) {\n\tif ms.LastUpdateNanos >= nowNanos {\n\t\treturn\n\t}\n\tms.AgeTo(nowNanos)\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func (qa *RobertaForQuestionAnswering) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (startScores, endScores *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := qa.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, ts.None, nil, nil, err\n\t}\n\n\tsequenceOutput := hiddenState.Apply(qa.qaOutputs)\n\tlogits := sequenceOutput.MustSplit(1, -1, true)\n\tstartScores = logits[0].MustSqueeze1(-1, false)\n\tendScores = logits[1].MustSqueeze1(-1, false)\n\n\tfor _, x := range logits {\n\t\tx.MustDrop()\n\t}\n\n\treturn startScores, endScores, hiddenStates, attentions, nil\n}", "func (r *Redirect) Forward(conn net.Conn) {\n\tif conn == nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\trequest = []byte{}\n\t\trequestTmp = make([]byte, 1024)\n\t)\n\n\tfor {\n\t\tn, err := conn.Read(requestTmp)\n\t\tif err != nil {\n\t\t\tr.reply(conn, nil, \"\", err)\n\t\t\treturn\n\t\t}\n\t\trequest = append(request, requestTmp[:n]...)\n\t\tif n < 1024 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(request)))\n\n\tif err != nil {\n\t\tr.reply(conn, nil, \"\", err)\n\t\treturn\n\t}\n\n\tu, err := url.Parse(string(req.RequestURI[1:]))\n\tif err != nil {\n\t\tr.reply(conn, req, \"\", err)\n\t\treturn\n\t}\n\treq.URL = u\n\treq.Host = u.Host\n\n\treq.RequestURI = \"\"\n\trequestObj := r.requestPool.Get().(*RequestWrapper)\n\trequestObj.CreatedTime = time.Now()\n\trequestObj.request = req\n\trequestObj.TryCount = 0\n\trequestObj.ID = r.makeID()\n\n\tif !r.putTask(requestObj, false) {\n\t\tr.reply(conn, req, \"\", errors.New(\"request put into buffer timeout\"))\n\t\treturn\n\t}\n\n\tr.reply(conn, req, requestObj.ID, nil)\n}", "func (s *Service) forwardToLeader(w http.ResponseWriter, req *http.Request) {\n\turl, err := url.Parse(s.RaftConfig.RaftNodeConfig.NodeProtocol + req.RequestURI)\n\tif err != nil {\n\t\tpanic(\"parse leader host url failed: \" + err.Error())\n\t}\n\turl.Host = s.raftNode.GetLeaderHost()\n\n\t// without leader, then return special error\n\tif url.Host == \"\" {\n\t\trpc.ReplyErr(w, apierrors.CodeNoLeader, apierrors.ErrNoLeader.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"forward url: %v\", url)\n\n\tproxy := httpproxy.ReverseProxy{\n\t\tDirector: func(request *http.Request) {\n\t\t\trequest.URL = url\n\t\t},\n\t}\n\n\tproxy.ServeHTTP(w, req)\n}", "func forwardBox(ctx *Context, t *Tuple, w Writer) error {\n\tw.Write(ctx, t)\n\treturn nil\n}", "func (a *createBucketIam) forward(app *App, args ...interface{}) error {\n\tenv, err := createBucket(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _ := config.GetString(\"host\")\n\tenvVars := []bind.EnvVar{\n\t\t{Name: \"APPNAME\", Value: app.Name},\n\t\t{Name: \"TSURU_HOST\", Value: host},\n\t}\n\tvariables := map[string]string{\n\t\t\"ENDPOINT\": env.endpoint,\n\t\t\"LOCATIONCONSTRAINT\": strconv.FormatBool(env.locationConstraint),\n\t\t\"ACCESS_KEY_ID\": env.AccessKey,\n\t\t\"SECRET_KEY\": env.SecretKey,\n\t\t\"BUCKET\": env.bucket,\n\t}\n\tfor name, value := range variables {\n\t\tenvVars = append(envVars, bind.EnvVar{\n\t\t\tName: fmt.Sprintf(\"TSURU_S3_%s\", name),\n\t\t\tValue: value,\n\t\t\tInstanceName: s3InstanceName,\n\t\t})\n\t}\n\tapp.SetEnvsToApp(envVars, false, true)\n\treturn nil\n}", "func (v *SourceSearchContext) Forward(iter *gtk.TextIter) (*gtk.TextIter, *gtk.TextIter, bool, bool) {\n\n\tstart, end := new(gtk.TextIter), new(gtk.TextIter)\n\tvar hasWrappedAround C.gboolean\n\n\tc := C.gtk_source_search_context_forward(\n\t\tv.native(),\n\t\tnativeTextIter(iter),\n\t\tnativeTextIter(start),\n\t\tnativeTextIter(end),\n\t\t&hasWrappedAround)\n\n\treturn start, end, gobool(hasWrappedAround), gobool(c)\n}", "func (r *Threshold[O]) Forward() (mat.Tensor, error) {\n\ty := r.x.Value().(mat.Matrix).ApplyWithAlpha(\n\t\tthreshold,\n\t\tr.threshold.Value().Item().F64(),\n\t\tr.k.Value().Item().F64(),\n\t)\n\treturn y, nil\n}", "func (m *NN) Forward(x *gorgonia.Node) (err error) {\n\tl := make([]*gorgonia.Node, len(m.W)+1)\n\tldot := make([]*gorgonia.Node, len(m.W))\n\tp := make([]*gorgonia.Node, len(m.W))\n\n\t// initial the first layer\n\tl[0] = x\n\n\t// W X + B\n\tfor i := 0; i < len(m.W); i++ {\n\t\tif len(m.B) != 0 && i < len(m.W) {\n\t\t\tL1, err := gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(l[i].Shape(), m.W[i].Shape())\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tldot[i], err = gorgonia.BroadcastAdd(L1, m.B[i], nil, []byte{0})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tldot[i], err = gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"mul wrong \", err)\n\t\t\t}\n\t\t}\n\n\t\t// Dropout\n\t\tp[i], err = gorgonia.Dropout(ldot[i], m.D[i])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Can't drop!\")\n\t\t}\n\n\t\t//activation function\n\t\tl[i+1] = gorgonia.Must(m.A[i](p[i]))\n\t}\n\n\tm.Pred = gorgonia.Must(m.A[len(m.A)-1](l[len(l)-1]))\n\tgorgonia.Read(m.Pred, &m.PredVal)\n\treturn\n}", "func Forward(bus EventBus) EventHandler {\n\treturn Handler(func(evt Event) error {\n\t\tbus.Publish(evt)\n\t\treturn nil\n\t})\n}", "func forwardTlcAck(gossiperPtr *core.Gossiper, ack *core.TLCAck) {\n\n\tif ack.HopLimit == 0 {\n\t\t// if we have reached the HopLimit, drop the message\n\t\treturn\n\t}\n\n\tgossiperPtr.DestinationTable.DsdvLock.Lock()\n\tforwardingAddress := gossiperPtr.DestinationTable.Dsdv[ack.Destination]\n\tgossiperPtr.DestinationTable.DsdvLock.Unlock()\n\t// If current node has no information about next hop to the destination in question\n\tif strings.Compare(forwardingAddress, \"\") == 0 {\n\t\t// TODO: What to do if there is no 'next hop' known when peer has to forward a private packet\n\t}\n\n\t// Decrement the HopLimit right before forwarding the packet\n\tack.HopLimit--\n\t// Encode and send packet\n\tpacketToSend := core.GossipPacket{Ack: ack}\n\tpacketBytes, err := protobuf.Encode(&packetToSend)\n\thelpers.HandleErrorFatal(err)\n\tcore.ConnectAndSend(forwardingAddress, gossiperPtr.Conn, packetBytes)\n}", "func (m *ItemCalendarsItemCalendarViewEventItemRequestBuilder) Forward()(*ItemCalendarsItemCalendarViewItemForwardRequestBuilder) {\n return NewItemCalendarsItemCalendarViewItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func httpSetForward(store *ForwardStore) func(w http.ResponseWriter, r *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tf := &Forward{}\n\n\t\tif r.Body == nil {\n\t\t\thttp.Error(w, \"No Post body\", 400)\n\t\t\treturn\n\t\t}\n\n\t\terr := json.NewDecoder(r.Body).Decode(f)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\n\t\tnewForward := store.set(f)\n\t\tjson.NewEncoder(w).Encode(newForward)\n\t}\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (re *RandomEqualize) Forward(x *ts.Tensor) *ts.Tensor {\n\tr := randPvalue()\n\tvar out *ts.Tensor\n\tswitch {\n\tcase r < re.pvalue:\n\t\tout = equalize(x)\n\tdefault:\n\t\tout = x.MustShallowClone()\n\t}\n\n\treturn out\n}", "func (d *Dispatcher) HandleForward(address string, h ForwardDial) {\n\td.forwards[address] = h\n}", "func (p *ProcType) FastForward(rev int64) *ProcType {\n\treturn p.Dir.Snapshot.fastForward(p, rev).(*ProcType)\n}", "func (b *LiteralArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) LiteralNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (rr *RandRotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := RandomRotate(fx, rr.minAngle, rr.maxAngle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func Forward(in, out Link) rules.Rule {\n\treturn rules.Rule(fmt.Sprintf(\n\t\t\"-t filter -A fw-interfaces -j ACCEPT -i %v -o %v\",\n\t\tin.Name(), out.Name()))\n}", "func forward(backend *Backend, local *net.TCPConn, remote *net.TCPConn) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tlogDebug(\"<%s> Start transfer %s to %s\", remote.RemoteAddr(), local.LocalAddr(), remote.LocalAddr())\n\tgo copy_half(backend, local, remote, &wg)\n\tgo copy_half(backend, remote, local, &wg)\n\twg.Wait()\n\tlogDebug(\"<%s> Finished transfer from %s to %s done\", remote.RemoteAddr(), local.LocalAddr(), remote.LocalAddr())\n}", "func (n Neuron) FeedForward(previous_layer Layer) {\n sum := 0.0\n\n // Sum outputs from the previous layer.\n for _, neuron := range previous_layer {\n // TODO: there may be duplication issues here\n sum += neuron.output * neuron.output_weights[n.index].weight\n }\n\n n.output = n.Activation(sum)\n}", "func (matrix Matrix4) Forward() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[2][0],\n\t\tmatrix[2][1],\n\t\tmatrix[2][2],\n\t}.Unit()\n}", "func forwardRequest(originatorAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte, toNode Node) {\n\tif self.Addr.String() == toNode.Addr.String() {\n\t\tfmt.Println(\"Stop. Can't forward to self - \", toNode.Addr.String())\n\t\treturn\n\t}\n\n\tsendRequestToNode(msgID, reqPay, &toNode)\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tlength := len(xs)\n\tqs := p.query.Forward(xs...)\n\tks := make([]ag.Node, length)\n\tvs := p.value.Forward(xs...)\n\tmapk := make(map[int]*IndexedNodes)\n\tmapv := make(map[int]*IndexedNodes)\n\n\t// TODO: can it be implemented in a concurrent fashion?\n\tfor i, q := range qs {\n\t\tnorm := p.Graph.Sqrt(p.Graph.ReduceSum(p.Graph.Pow(q, 2.0)))\n\t\tks[i] = p.Graph.DivScalar(q, norm) // Euclidean norm\n\t\th := p.getHash(ks[i].Value().(*mat.Dense))\n\t\tinsertNode(mapk, ks[i], i, h)\n\t\tinsertNode(mapv, vs[i], i, h)\n\t}\n\n\tcontext := make([]ag.Node, length)\n\tprob := make([]mat.Matrix, length)\n\tfor i, q := range qs {\n\t\tj := p.getHash(q.Value().(*mat.Dense))\n\t\tc, p := p.lshScaledDotProductAttention(p.Graph, q, mapk[j], mapv[j], length, p.scaleFactor)\n\t\tcontext[i], prob[i] = c, p\n\t}\n\n\tp.Attention = &ContextProb{\n\t\tcontext: context,\n\t\tprob: prob,\n\t}\n\treturn context\n}", "func (q Quat) Forward() Vec3f {\n\treturn q.RotateVec(Vec3f{0, 0, -1})\n}", "func Forward(b Branch, distance float64) Branch {\n\tvar b_new Branch\n\tb_new.phase = b.phase\n\tb_new.xy = b.xy + cmplx.Rect(distance, b.phase)\n\treturn b_new\n}", "func (n *MLP) forward(x mat.Matrix) (as, zs []mat.Matrix) {\n\tas = append(as, x) // first activation is input\n\n\t_x := x\n\n\tfor i := 0; i < len(n.weights); i++ {\n\t\tw := n.weights[i]\n\t\tb := n.biases[i]\n\n\t\tdot := new(mat.Dense)\n\t\tdot.Mul(_x, w)\n\n\t\tz := new(mat.Dense)\n\t\taddB := func(_, col int, v float64) float64 { return v + b.At(col, 0) }\n\t\tz.Apply(addB, dot)\n\n\t\ta := new(mat.Dense)\n\t\ta.Apply(applySigmoid, z)\n\n\t\tzs = append(zs, z)\n\t\tas = append(as, a)\n\n\t\t_x = a\n\t}\n\n\treturn\n}", "func (c *chrono) Forward(skew time.Duration) {\n\tc.skew = skew\n}", "func (b *Brain) Forward(inputArray []float64) int {\r\n\tb.ForwardPasses++\r\n\tb.LastInputArray = inputArray // back this up\r\n\r\n\t// create network input\r\n\tvar (\r\n\t\tnetInput []float64\r\n\t\taction int\r\n\t)\r\n\tif b.ForwardPasses > b.TemporalWindow {\r\n\t\t// we have enough to actually do something reasonable\r\n\t\tnetInput = b.NetInput(inputArray)\r\n\r\n\t\tif b.Learning {\r\n\t\t\t// compute epsilon for the epsilon-greedy policy\r\n\t\t\tb.Epsilon = math.Min(1.0, math.Max(b.EpsilonMin, 1.0-float64(b.Age-b.LearningStepsBurnin)/float64(b.LearningStepsTotal-b.LearningStepsBurnin)))\r\n\t\t} else {\r\n\t\t\tb.Epsilon = b.EpsilonTestTime // use test-time value\r\n\t\t}\r\n\r\n\t\trf := b.Rand.Float64()\r\n\t\tif rf < b.Epsilon {\r\n\t\t\t// choose a random action with epsilon probability\r\n\t\t\taction = b.RandomAction()\r\n\t\t} else {\r\n\t\t\t// otherwise use our policy to make decision\r\n\t\t\taction, _ = b.Policy(netInput)\r\n\t\t}\r\n\t} else {\r\n\t\t// pathological case that happens first few iterations\r\n\t\t// before we accumulate window_size inputs\r\n\t\tnetInput = nil\r\n\t\taction = b.RandomAction()\r\n\t}\r\n\r\n\t// remember the state and action we took for backward pass\r\n\tcopy(b.NetWindow, b.NetWindow[1:])\r\n\tb.NetWindow[len(b.NetWindow)-1] = netInput\r\n\tcopy(b.StateWindow, b.StateWindow[1:])\r\n\tb.StateWindow[len(b.StateWindow)-1] = inputArray\r\n\tcopy(b.ActionWindow, b.ActionWindow[1:])\r\n\tb.ActionWindow[len(b.ActionWindow)-1] = action\r\n\r\n\treturn action\r\n}", "func ResetForwardContext(ctx context.Context) context.Context {\n\tmd, ok := metadata.FromIncomingContext(ctx)\n\tif !ok {\n\t\tlog.Error(\"failed to get forwarding metadata\")\n\t}\n\tmd.Set(ForwardMetadataKey, \"\")\n\treturn metadata.NewOutgoingContext(ctx, md)\n}", "func (xf *HttpEchoTransfer) Forward() (inbytes uint64, outbytes uint64, err error) {\n\txf.m.Lock()\n\tdefer xf.m.Unlock()\n\tif xf.forwarding {\n\t\terr = errors.New(\"already forwarding\")\n\t\treturn\n\t}\n\tvar wg sync.WaitGroup\n\t/*\n\t\t// CMsg\n\t\ttype CMsg struct {\n\t\t\tCode uint64\n\t\t\tId uint64\n\t\t\tMsg []byte\n\t\t\tErr error\n\t\t}\n\t*/\n\tvar msg *cmtp.CMsg\n\tvar rw *net.TCPConn\n\t/*\n\t\tnewrawio chan io.ReadWriteCloser\n\t\tlastIdx int\n\t\trawio []io.ReadWriteCloser\n\t\tidleslot *queues.LifoQ\n\t\tworkerMsg chan *cmtp.CMsg\n\t*/\n\tvar rwidx int\n\ttime.Sleep(1e9)\n\ttpf(\"HttpEchoTransfer forwarding ...\\n\")\n\tfor {\n\t\tselect {\n\t\tcase rw = <-xf.newrawio:\n\t\t\tidlecount := xf.idleslot.Pop()\n\t\t\tif idlecount == nil {\n\t\t\t\txf.lastIdx++\n\t\t\t\trwidx = xf.lastIdx\n\t\t\t\txf.rawio = append(xf.rawio, rw)\n\t\t\t} else {\n\t\t\t\trwidx = idlecount.(int)\n\t\t\t\txf.rawio[rwidx] = rw\n\t\t\t}\n\t\t\twg.Add(1)\n\t\t\tgo xf.echoserver(rwidx, &wg)\n\t\tcase msg = <-xf.workerMsg:\n\t\t\t//tpf(\"echoserver exit with msg %v\\n\", msg)\n\t\t\t//tpf(\"echoserver exit with msg %s\\n\", msg.String())\n\t\t\t//msg = <-xf.workerMsg\n\t\t\t//tpf(\"echoserver exit with msg2 %s\\n\", msg.String())\n\t\t\txf.rawio[msg.Id].Close()\n\t\t\txf.rawio[msg.Id] = nil\n\t\t\txf.idleslot.Push(int(msg.Id))\n\t\t\t// TODO: in/out bytes in msg.Msg\n\t\t}\n\t}\n\twg.Wait()\n\tclose(xf.closed)\n\treturn\n}", "func Forward(ctx context.Context, destination chan<- packet.Buf, source <-chan packet.Buf) {\n\tdefer contextack.Ack(ctx, ForwardDoneAck)\n\n\tvar p packet.Buf\n\n\tfor {\n\t\tvar (\n\t\t\tinput <-chan packet.Buf\n\t\t\toutput chan<- packet.Buf\n\t\t\tok bool\n\t\t)\n\n\t\tif p == nil {\n\t\t\tinput = source\n\t\t} else {\n\t\t\toutput = destination\n\t\t}\n\n\t\tselect {\n\t\tcase p, ok = <-input:\n\t\t\tif !ok {\n\t\t\t\t// EOF\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase output <- p:\n\t\t\t// ok\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (a *createRepository) forward(app *App, args ...interface{}) error {\n\tgUrl := repository.GitServerUri()\n\tvar users []string\n\tfor _, t := range app.GetTeams() {\n\t\tusers = append(users, t.Users...)\n\t}\n\tc := gandalf.Client{Endpoint: gUrl}\n\t_, err := c.NewRepository(app.Name, users, false)\n\treturn err\n}" ]
[ "0.6948116", "0.6622131", "0.6508866", "0.64886606", "0.6365477", "0.63336223", "0.61528224", "0.6133815", "0.6107234", "0.60896546", "0.60325277", "0.60204875", "0.60162234", "0.59912664", "0.59696406", "0.5964232", "0.5954961", "0.59260416", "0.59076136", "0.5899988", "0.5887434", "0.5878368", "0.5852504", "0.5851789", "0.58299047", "0.57919234", "0.5789817", "0.57823724", "0.5775919", "0.5750861", "0.5734637", "0.5730441", "0.57076967", "0.57076967", "0.5680986", "0.56787145", "0.5678286", "0.5670207", "0.5632474", "0.56270874", "0.5621981", "0.5616499", "0.5616371", "0.56158465", "0.5613355", "0.5582917", "0.557088", "0.5566881", "0.5553484", "0.55207276", "0.5513445", "0.5512134", "0.5508181", "0.5506436", "0.54977053", "0.54844487", "0.5482158", "0.5479578", "0.5468998", "0.54245377", "0.54213846", "0.54082716", "0.5405725", "0.5405242", "0.54034513", "0.5397328", "0.5386622", "0.53790325", "0.5377244", "0.53728414", "0.53700167", "0.53590226", "0.53487235", "0.53415453", "0.53172696", "0.529771", "0.52923477", "0.52867436", "0.5279087", "0.5279087", "0.52343154", "0.5227096", "0.52269226", "0.52064234", "0.5206051", "0.5194304", "0.51908225", "0.51868117", "0.5182171", "0.5179725", "0.51561046", "0.5153029", "0.51298326", "0.51263726", "0.5123732", "0.5119957", "0.5115004", "0.51131797", "0.5096588", "0.50891656" ]
0.59257644
18
NewRobertaQuestionAnswering creates a new RobertaForQuestionAnswering model.
func NewRobertaForQuestionAnswering(p *nn.Path, config *bert.BertConfig) *RobertaForQuestionAnswering { roberta := bert.NewBertModel(p.Sub("roberta"), config) numLabels := int64(2) qaOutputs := nn.NewLinear(p.Sub("qa_outputs"), config.HiddenSize, numLabels, nn.DefaultLinearConfig()) return &RobertaForQuestionAnswering{ roberta: roberta, qaOutputs: qaOutputs, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewQuestion() {\n\tNumAnswers = make(map[string]int)\n\n\tsetRandomQuestion()\n\tvar NewQuestionMessage = fmt.Sprintf(\"A new question, you have %d seconds to answer it!\", TimeToAnswer)\n\tsendMessageToActiveChannels(NewQuestionMessage)\n\tQuestionTimer = time.NewTimer(time.Second * TimeToAnswer)\n\tgo func() {\n\t\t<-QuestionTimer.C\n\t\tonTimeRanOut()\n\t}()\n\n\tmessageQuestionToAll()\n}", "func (a *App) NewQuestion(w http.ResponseWriter, r *http.Request) {\n\tuserID := r.Context().Value(models.ContextUserID).(int)\n\tvar question models.Question\n\terr := json.NewDecoder(r.Body).Decode(&question)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tquestion, err = a.Storage.Add(userID, question)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\taddJSONPayload(w, http.StatusOK, question)\n}", "func NewQuestion(answers []string, max int, min int, question string, resultType string, shortName string) (*Question, error) {\n\tif max < 0 || min < 0 || min > max {\n\t\treturn nil, errors.New(\"invalid question min and max\")\n\t}\n\n\tif resultType != \"absolute\" && resultType != \"relative\" {\n\t\treturn nil, errors.New(\"invalid result type\")\n\t}\n\n\tansURLs := make([]string, len(answers))\n\tans := make([]string, len(answers))\n\tcopy(ans, answers)\n\n\t// The only possible choice type is \"approval\", and the only possible\n\t// tally type is \"homomorphic\".\n\treturn &Question{ansURLs, ans, \"approval\", max, min, question, resultType, shortName, \"homomorphic\"}, nil\n}", "func NewRobertaForMultipleChoice(p *nn.Path, config *bert.BertConfig) *RobertaForMultipleChoice {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, 1, nn.DefaultLinearConfig())\n\n\treturn &RobertaForMultipleChoice{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewQuestion(name string) (*Message, error) {\n\tn := Name{}\n\tif err := n.SetName(name); err != nil {\n\t\treturn nil, err\n\t}\n\n\tq := Question{\n\t\tName: n,\n\t\tType: ANYQType,\n\t\tClass: INClass,\n\t}\n\th := Header{\n\t\tID: 1,\n\t\tOpcode: QueryOpcode,\n\t\tRD: true,\n\t\tRCode: NoErrorRCode,\n\t\tQuestionCount: 1,\n\t}\n\treturn &Message{\n\t\tHeader: h,\n\t\tQuestion: q,\n\t}, nil\n}", "func NewQuestion() *Question {\n\t// === Check the strings that represent a boolean.\n\t_, err := atob(QuestionTrueString)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"the string %q does not represent a boolean 'true'\",\n\t\t\tQuestionTrueString))\n\t}\n\n\tif _, err = atob(QuestionFalseString); err != nil {\n\t\tpanic(fmt.Sprintf(\"the string %q does not represent a boolean 'false'\",\n\t\t\tQuestionFalseString))\n\t}\n\n\treturn &Question{\n\t\tstrings.ToLower(QuestionTrueString),\n\t\tstrings.ToLower(QuestionFalseString),\n\t}\n}", "func NewQuiz(address common.Address, backend bind.ContractBackend) (*Quiz, error) {\n\tcontract, err := bindQuiz(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Quiz{QuizCaller: QuizCaller{contract: contract}, QuizTransactor: QuizTransactor{contract: contract}, QuizFilterer: QuizFilterer{contract: contract}}, nil\n}", "func NewRoar(author string, text string) *Roar {\n return &Roar{Author: author, Text: text,\n CreationDate: time.LocalTime().Format(time.RFC1123)}\n}", "func (h *ENUMHandler) createAnswer(request *dns.Msg) (answer *dns.Msg, err error) {\n\n\tif len(request.Question) != 1 {\n\t\terr = errors.New(\"Received more than one question\")\n\t\treturn\n\t}\n\n\tquestion := request.Question[0]\n\tif question.Qtype != dns.TypeNAPTR {\n\t\terr = errors.New(\"Received an unsupported query type '\" + dns.Type(question.Qtype).String() + \"'\")\n\t\treturn\n\t}\n\n\tvar number uint64\n\tif number, err = extractE164FromName(question.Name); err != nil {\n\t\treturn\n\t}\n\n\tvar numberrange enum.NumberRange\n\th.Trace.Printf(\"backend.RangesBetween(%d, %d, 1)\", number, number)\n\tranges, err := (*h.Backend).RangesBetween(number, number, 1)\n\tif err != nil || len(ranges) != 1 {\n\t\treturn\n\t}\n\tnumberrange = ranges[0]\n\n\tanswer = h.answerForRequest(request)\n\n\t// Create and populate the NAPTR answers.\n\tfor _, record := range numberrange.Records {\n\t\tnaptr := new(dns.NAPTR)\n\t\tnaptr.Hdr = dns.RR_Header{Name: question.Name, Rrtype: question.Qtype, Class: question.Qclass, Ttl: 0}\n\t\tnaptr.Regexp = record.Regexp\n\n\t\tnaptr.Preference = record.Preference\n\t\tnaptr.Service = record.Service\n\t\tnaptr.Flags = record.Flags\n\t\tnaptr.Order = record.Order\n\t\tnaptr.Replacement = record.Replacement\n\n\t\tanswer.Answer = append(answer.Answer, naptr)\n\t}\n\n\treturn\n\n}", "func NewEducationSubmissionResource()(*EducationSubmissionResource) {\n m := &EducationSubmissionResource{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewGetPruebaFromQuestion(ctx *middleware.Context, handler GetPruebaFromQuestionHandler) *GetPruebaFromQuestion {\n\treturn &GetPruebaFromQuestion{Context: ctx, Handler: handler}\n}", "func NewRobertaForMaskedLM(p *nn.Path, config *bert.BertConfig) *RobertaForMaskedLM {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tlmHead := NewRobertaLMHead(p.Sub(\"lm_head\"), config)\n\n\treturn &RobertaForMaskedLM{\n\t\troberta: roberta,\n\t\tlmHead: lmHead,\n\t}\n}", "func newGUIComputedQuestion(question interfaces.Question, expr interfaces.Expr, varID interfaces.VarID) *GUIComputedQuestion {\n\tguiQuestion := createDisabledGUIQuestion(question)\n\treturn &GUIComputedQuestion{GUIQuestion: guiQuestion, Expr: expr, VarID: varID}\n}", "func New(q *ast.Questionaire, toFrontend, fromFrontend chan *fe.Event) {\n\tv := &vm{\n\t\tquestionaire: q,\n\t\tsend: toFrontend,\n\t\treceive: fromFrontend,\n\t}\n\tv.loop()\n}", "func CreateNewQuiz(file *os.File) Quiz {\n\tvar questions []Question\n\n\terr := json.NewDecoder(file).Decode(&questions)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read the given questionnaire %v\", err)\n\t}\n\n\treturn Quiz{\n\t\tquestions,\n\t\tProgress{total: len(questions)},\n\t\tsync.Mutex{},\n\t}\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\tpeer2Progress := make(map[uint64]*Progress, len(c.peers))\n\tpeer2Vote := make(map[uint64]bool, len(c.peers))\n\tfor _, s := range c.peers {\n\t\tpeer2Vote[s] = false\n\t\tpeer2Progress[s] = &Progress{0, 0}\n\t}\n\trand.Seed(time.Now().UnixNano())\n\thardState, _, _ := c.Storage.InitialState()\n\treturn &Raft{id: c.ID, Term: hardState.Term, Vote: hardState.Vote, RaftLog: newLog(c.Storage), State: StateFollower, Prs: peer2Progress, votes: peer2Vote, Lead: 0, heartbeatTimeout: c.HeartbeatTick, electionTimeout: c.ElectionTick, heartbeatElapsed: 0, electionElapsed: 0, actualElectionTimeout: 0}\n}", "func CreateAnswer(form AnswerForm) {\n\ta := Answer{}\n\ta.Username = form.Username\n\tintQuestionID, _ := strconv.Atoi(form.QuestionID)\n\ta.QuestionID = intQuestionID\n\ta.Description = form.Description\n\ta.Rank = 0\n\tdb.Create(&a)\n}", "func NewParticipant(participant_number int) *Participant {\n\tp := new(Participant)\n\tp.i = participant_number\n\tp.pid = []byte(\"XXXsomethingunique\")\n\n\t// Generate long-term private/public keypair\n\tp.sk = rand_int(group_q)\n\tp.pk = new(big.Int).Exp(group_g, p.sk, group_p)\n\n\tdebug.Printf(\"Created participant %d:\\nsk = %x\\npk = %x\\n\",\n\t\tp.i, p.sk, p.pk)\n\n\treturn p\n}", "func newBook(r CreateRequest) *book.Book {\n\tb := new(book.Book)\n\tb.ID = db.NextID()\n\tb.Author = r.Author\n\tb.Title = r.Title\n\treturn b\n}", "func New() Model {\n\treturn Model{\n\t\tType: Arabic,\n\t\tPage: 0,\n\t\tPerPage: 1,\n\t\tTotalPages: 1,\n\t\tKeyMap: DefaultKeyMap,\n\t\tActiveDot: \"•\",\n\t\tInactiveDot: \"○\",\n\t\tArabicFormat: \"%d/%d\",\n\t}\n}", "func CreateAnswerObject(args []string) (Answer, error) {\n\tvar myAnswer Answer\n\n\tstrArr := []string{}\n\t// Check there are 10 Arguments provided as per the the struct\n\tif len(args) != 4 {\n\t\tfmt.Println(\"CreateAnswerObject(): Incorrect number of arguments. Expecting 4\")\n\t\treturn myAnswer, errors.New(\"CreateAnswerObject(): Incorrect number of arguments. Expecting 4\")\n\t}\n\n\tmyAnswer = Answer{args[0], args[1], args[2], args[3], strArr, 0, time.Now().Format(\"20060102150405\")}\n\treturn myAnswer, nil\n}", "func NewRobertaForSequenceClassification(p *nn.Path, config *bert.BertConfig) *RobertaForSequenceClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tclassifier := NewRobertaClassificationHead(p.Sub(\"classifier\"), config)\n\n\treturn &RobertaForSequenceClassification{\n\t\troberta: roberta,\n\t\tclassifier: classifier,\n\t}\n}", "func NewRobertaClassificationHead(p *nn.Path, config *bert.BertConfig) *RobertaClassificationHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\tnumLabels := int64(len(config.Id2Label))\n\toutProj := nn.NewLinear(p.Sub(\"out_proj\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\n\treturn &RobertaClassificationHead{\n\t\tdense: dense,\n\t\tdropout: dropout,\n\t\toutProj: outProj,\n\t}\n}", "func New(questionsPath string, textPath string) *Truman {\n\tt := &Truman{}\n\n\tquestionsFilePath, _ := filepath.Abs(questionsPath)\n\ttextFilePath, _ := filepath.Abs(textPath)\n\n\tt.loadQuestions(questionsFilePath)\n\tt.loadText(textFilePath)\n\n\treturn t\n}", "func NewQuizTransactor(address common.Address, transactor bind.ContractTransactor) (*QuizTransactor, error) {\n\tcontract, err := bindQuiz(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &QuizTransactor{contract: contract}, nil\n}", "func NewRulerBuilder(e e2e.Environment, name string) *RulerBuilder {\n\tf := e.Runnable(fmt.Sprintf(\"rule-%s\", name)).\n\t\tWithPorts(map[string]int{\"http\": 8080, \"grpc\": 9091}).\n\t\tFuture()\n\treturn &RulerBuilder{\n\t\treplicaLabel: name,\n\t\tLinkable: f,\n\t\tf: f,\n\t\timage: DefaultImage(),\n\t}\n}", "func New() QuizPractice {\n\treturn &quizPractice{\n\t\tArgs: os.Args,\n\t}\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\ts := c.Storage\n\thardStatus, confStatus, err := s.InitialState()\n\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tif c.peers == nil {\n\t\tc.peers = confStatus.Nodes\n\t}\n\n\tnodes := c.peers\n\t// init vote to false\n\tvotes := make(map[uint64]bool)\n\tfor _, nodeId := range nodes {\n\t\tvotes[nodeId] = false\n\t}\n\n\treturn &Raft{\n\t\tid: c.ID,\n\t\tTerm: hardStatus.Commit,\n\t\tVote: hardStatus.Vote,\n\t\tRaftLog: newLog(c.Storage),\n\t\tPrs: nil,\n\t\t// init as a follower\n\t\tState: StateFollower,\n\t\tvotes: nil,\n\t\tmsgs: nil,\n\t\tLead: None,\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\trandomElectionTimeout: randomTimeout(c.ElectionTick),\n\t\theartbeatElapsed: 0,\n\t\telectionElapsed: 0,\n\t\tleadTransferee: 0,\n\t\tPendingConfIndex: 0,\n\t\tnodes: nodes,\n\t}\n}", "func New(ctx context.Context, kb *input.KeyboardEventWriter, tconn *chrome.TestConn, a *arc.ARC) (*VoiceRecorder, error) {\n\tapp, err := apputil.NewApp(ctx, kb, tconn, a, \"Voice Recorder\", pkgName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &VoiceRecorder{app: app}, nil\n}", "func (t *OpenconfigOfficeAp_Radios) NewRadio(Id uint8) (*OpenconfigOfficeAp_Radios_Radio, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Radio == nil {\n\t\tt.Radio = make(map[uint8]*OpenconfigOfficeAp_Radios_Radio)\n\t}\n\n\tkey := Id\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Radio[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Radio\", key)\n\t}\n\n\tt.Radio[key] = &OpenconfigOfficeAp_Radios_Radio{\n\t\tId: &Id,\n\t}\n\n\treturn t.Radio[key], nil\n}", "func newChoiceBuilder(choiceDef *ChoiceDef) ChoiceBuilder {\n\treturn &chosenBuilder{\n\t\tchoiceDef: choiceDef,\n\t}\n}", "func RadioButtonNew(group *glib.SList) (*RadioButton, error) {\n\tc := C.gtk_radio_button_new(cGSList(group))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapRadioButton(obj), nil\n}", "func NewQuiz(file string) (*Quizes, error) {\n\tvar exercice Quizes\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := csv.NewReader(bufio.NewReader(f))\n\tr.Comma = ','\n\trecords, err := r.ReadAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, row := range records {\n\t\texercice.Quizes = append(exercice.Quizes, Quiz{Question: row[0], CorrectAnswer: row[1]})\n\t}\n\treturn &exercice, err\n}", "func New() *RabinKarp64 {\n\tp, err := RandomPolynomial(1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn NewFromPol(p)\n}", "func NewQuizDecoder(*http.Request) (Request, error) {\n\treturn emptyRequest{}, nil\n}", "func NewBallot(election *Election, answers [][]int64) (*Ballot, error) {\n\tif len(answers) != len(election.Questions) {\n\t\treturn nil, errors.New(\"wrong number of answers\")\n\t}\n\n\tpk := election.PublicKey\n\n\t//vote.ElectionHash = election.ElectionHash\n\t//vote.ElectionUuid = election.Uuid\n\n\tans := make([]*EncryptedAnswer, len(election.Questions))\n\n\tfor i, q := range election.Questions {\n\t\ta := answers[i]\n\t\tresults := make([]bool, len(q.Answers))\n\t\t//sum := int64(len(a))\n\n\t\t//min := q.Min\n\t\t//max := q.ComputeMax()\n\t\t//if sum < int64(min) || sum > int64(max) {\n\t\t//\tglog.Errorf(\"Sum was %d, min was %d, and max was %d\\n\", sum, min, max)\n\t\t//\treturn nil, errors.New(\"invalid answers: sum must lie between min and max\")\n\t\t//}\n\n\t\tch := make([]*Ciphertext, len(results))\n\t\t//ip := make([]DisjunctiveZKProof, len(results))\n\t\trs := make([]*big.Int, len(results))\n\t\tas := make([]int64, len(a))\n\t\tcopy(as, a)\n\n\t\t// Mark each selected value as being voted for.\n\t\tfor _, index := range a {\n\t\t\tresults[index] = true\n\t\t}\n\n\t\t// Encrypt and create proofs for the answers, then create an overall proof if required\n\t\ttally := &Ciphertext{big.NewInt(1), big.NewInt(1)}\n\t\trandTally := big.NewInt(0)\n\t\tfor j := range q.Answers {\n\t\t\tvar err error\n\t\t\tif ch[j], rs[j] = Encrypt(results[j], pk); err != nil {\n\t\t\t\t// glog.Errorf(\"Couldn't encrypt choice %d for question %d\\n\", j, i)\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\ttally.MulCiphertexts(ch[j], pk.Prime)\n\t\t\trandTally.Add(randTally, rs[j])\n\t\t\trandTally.Mod(randTally, pk.ExponentPrime)\n\t\t}\n\n\t\t//var op DisjunctiveZKProof\n\t\t//if q.Max != 0 {\n\t\t//\top = make([]*ZKProof, q.Max-q.Min+1)\n\t\t//\tfor j := q.Min; j <= q.Max; j++ {\n\t\t//\t\tif int64(j) != sum {\n\t\t//\t\t\t// Create a simulated proof for the case where the\n\t\t//\t\t\t// tally actually encrypts the value j.\n\t\t//\t\t\tif err := op.CreateFakeProof(int64(j-q.Min), int64(j), tally, pk); err != nil {\n\t\t//\t\t\t\tglog.Errorf(\"Couldn't create fake proof %d\\n\", j)\n\t\t//\t\t\t\treturn nil, err\n\t\t//\t\t\t}\n\t\t//\t\t}\n\t\t//\t}\n\t\t//\n\t\t//\tif err := op.CreateRealProof(sum-int64(q.Min), tally, randTally, pk); err != nil {\n\t\t//\t\tglog.Errorf(\"Couldn't create the real proof\")\n\t\t//\t\treturn nil, err\n\t\t//\t}\n\t\t//}\n\n\t\tans[i] = &EncryptedAnswer{ch, as, rs}\n\t}\n\n\treturn &Ballot{ans, election.ElectionHash, election.Uuid}, nil\n}", "func newRaft(c *Config) *Raft {\n\tif err := c.validate(); err != nil {\n\t\tpanic(err.Error())\n\t}\n\t// Your Code Here (2A).\n\tr := &Raft{\n\t\tid: c.ID,\n\t\tPrs: make(map[uint64]*Progress),\n\t\tvotes: make(map[uint64]bool),\n\t\theartbeatTimeout: c.HeartbeatTick,\n\t\telectionTimeout: c.ElectionTick,\n\t\tRaftLog: newLog(c.Storage),\n\t}\n\thardSt, confSt, _ := r.RaftLog.storage.InitialState()\n\tif c.peers == nil {\n\t\tc.peers = confSt.Nodes\n\t}\n\tlastIndex := r.RaftLog.LastIndex()\n\tfor _, peer := range c.peers {\n\t\tif peer == r.id {\n\t\t\tr.Prs[peer] = &Progress{Next: lastIndex + 1, Match: lastIndex}\n\t\t} else {\n\t\t\tr.Prs[peer] = &Progress{Next: lastIndex + 1}\n\t\t}\n\t}\n\tr.becomeFollower(0, None)\n\tr.randomElectionTimeout = r.electionTimeout + rand.Intn(r.electionTimeout)\n\tr.Term, r.Vote, r.RaftLog.committed = hardSt.GetTerm(), hardSt.GetVote(), hardSt.GetCommit()\n\tif c.Applied > 0 {\n\t\tr.RaftLog.applied = c.Applied\n\t}\n\treturn r\n}", "func newNGram(n int) *nGram {\n\tngram := new(nGram)\n\tngram.nValue = n\n\treturn ngram\n}", "func NewRaft(cfg *ServerConfig) *Raft {\n\treturn &Raft{\n\t\tServer: NewServer(cfg),\n\t\tLeaderID: NoLeader,\n\t}\n}", "func (app *HailingApp) QuestionToAsk(record *ReservationRecord, localizer *i18n.Localizer) Question {\n\t// step: init -> to -> from -> when -> final -> done\n\tswitch strings.ToLower(record.Waiting) {\n\tcase \"to\":\n\t\tbuttons := app.QuickReplyLocations(record)\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"WhereTo\",\n\t\t\t\t\tOther: \"Where to?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t\tLocationInput: true,\n\t\t}\n\tcase \"from\":\n\t\tbuttons := app.QuickReplyLocations(record)\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"PickupLocation\",\n\t\t\t\t\tOther: \"Pickup location?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t\tLocationInput: true,\n\t\t}\n\tcase \"when\":\n\t\tbuttons := []QuickReplyButton{\n\t\t\t{\n\t\t\t\tLabel: \"Now\",\n\t\t\t\tText: \"now\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\t\tID: \"InXMin\",\n\t\t\t\t\t\tOther: \"In {{.Min}} mins\",\n\t\t\t\t\t},\n\t\t\t\t\tTemplateData: map[string]string{\n\t\t\t\t\t\t\"Min\": \"15\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tText: \"+15min\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\t\tID: \"InXMin\",\n\t\t\t\t\t\tOther: \"In {{.Min}} mins\",\n\t\t\t\t\t},\n\t\t\t\t\tTemplateData: map[string]string{\n\t\t\t\t\t\t\"Min\": \"30\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tText: \"+30min\",\n\t\t\t},\n\t\t}\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"When\",\n\t\t\t\t\tOther: \"When?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t\tDatetimeInput: true,\n\t\t}\n\tcase \"num_of_passengers\":\n\t\tbuttons := []QuickReplyButton{\n\t\t\t{\n\t\t\t\tLabel: \"1\",\n\t\t\t\tText: \"1\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: \"2\",\n\t\t\t\tText: \"2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: \"3\",\n\t\t\t\tText: \"3\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabel: \"4\",\n\t\t\t\tText: \"4\",\n\t\t\t},\n\t\t}\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"HowManyPassengers\",\n\t\t\t\t\tOther: \"How many passengers?\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tButtons: buttons,\n\t\t}\n\tcase \"final\":\n\t\treturn Question{\n\t\t\tText: localizer.MustLocalize(&i18n.LocalizeConfig{\n\t\t\t\tDefaultMessage: &i18n.Message{\n\t\t\t\t\tID: \"Confirm\",\n\t\t\t\t\tOther: \"Confirm\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tYesInput: true,\n\t\t}\n\t}\n\treturn Question{\n\t\tText: \"n/a\",\n\t}\n}", "func NewCopyQuestion(ctx *middleware.Context, handler CopyQuestionHandler) *CopyQuestion {\n\treturn &CopyQuestion{Context: ctx, Handler: handler}\n}", "func newReply(ctx *Context) *Reply {\n\treturn &Reply{\n\t\tCode: http.StatusOK,\n\t\tgzip: true,\n\t\tctx: ctx,\n\t}\n}", "func NewRadio(guildID string) *Radio {\n\treturn &Radio{\n\t\tGuildID: guildID,\n\t\tQueue: NewSongQueue(),\n\t\tcontrol: make(chan int),\n\t\tAutoPlay: true,\n\t\tSilent: false,\n\t}\n}", "func NewProvidedAnswer(id string, text string) ProvidedAnswer {\n\treturn ProvidedAnswer{\n\t\tID: id,\n\t\tText: text,\n\t}\n}", "func (db GAEDatabase) NewTrainer(t pkmn.Trainer) database.Trainer {\n\treturn &GAETrainer{Trainer: t}\n}", "func NewTask(from string, groupSuggestions []string) Task {\n t := Task{}\n\n t.Set(from)\n\n if t.UserDueDate.IsZero() {\n t.PromptDueDate()\n }\n if t.Group == \"\" {\n t.PromptGroup(groupSuggestions)\n }\n\n return t\n}", "func (c *RBController) NewRecipe(w http.ResponseWriter, r *http.Request) (err error) {\n\t// build data with anonymous struct\n\tdata := struct {\n\t\t*Recipe\n\t\tNewRecipe bool\n\t}{\n\t\tnew(Recipe),\n\t\ttrue,\n\t}\n\n\t// pass data to render\n\tc.HTML(w, http.StatusOK, \"recipes/edit\", data)\n\treturn nil\n}", "func New(randomized bool) *RF1R {\n\tres := RF1R{}\n\n\tif randomized {\n\t\tres.hasher1 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t\tres.hasher2 = func(b []byte) uint64 { return siphash.Hash(2, 3, b) }\n\t} else {\n\t\tres.hasher1 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t\tres.hasher2 = func(b []byte) uint64 { return siphash.Hash(0, 0, b) }\n\t}\n\n\treturn &res\n}", "func NewQuranize(t Transliteration, q Quran) Quranize {\n\tquranize := Quranize{t: t, q: q}\n\tquranize.buildIndex()\n\treturn quranize\n}", "func NewRobertaLMHead(p *nn.Path, config *bert.BertConfig) *RobertaLMHead {\n\tdense := nn.NewLinear(p.Sub(\"dense\"), config.HiddenSize, config.HiddenSize, nn.DefaultLinearConfig())\n\n\tlayerNormConfig := nn.DefaultLayerNormConfig()\n\tlayerNormConfig.Eps = 1e-12\n\tlayerNorm := nn.NewLayerNorm(p.Sub(\"layer_norm\"), []int64{config.HiddenSize}, layerNormConfig)\n\n\tdecoder := util.NewLinearNoBias(p.Sub(\"decoder\"), config.HiddenSize, config.VocabSize, util.DefaultLinearNoBiasConfig())\n\n\tbias := p.NewVar(\"bias\", []int64{config.VocabSize}, nn.NewKaimingUniformInit())\n\n\treturn &RobertaLMHead{\n\t\tdense: dense,\n\t\tdecoder: decoder,\n\t\tlayerNorm: layerNorm,\n\t\tbias: bias,\n\t}\n}", "func NewBot() TipBot {\n\t// create sqlite databases\n\tdb, txLogger := migration()\n\treturn TipBot{\n\t\tDatabase: db,\n\t\tClient: lnbits.NewClient(internal.Configuration.Lnbits.AdminKey, internal.Configuration.Lnbits.Url),\n\t\tlogger: txLogger,\n\t\tBunt: createBunt(),\n\t\tTelegram: newTelegramBot(),\n\t}\n}", "func NewSignalingAnswerer(address, host string, server *Server, insecure bool, logger golog.Logger) *SignalingAnswerer {\n\tcloseCtx, cancel := context.WithCancel(context.Background())\n\treturn &SignalingAnswerer{\n\t\taddress: address,\n\t\thost: host,\n\t\tserver: server,\n\t\tinsecure: insecure,\n\t\tcancelBackgroundWorkers: cancel,\n\t\tcloseCtx: closeCtx,\n\t\tlogger: logger,\n\t}\n}", "func NewRTGProtocol(n int, q, p []uint64, sigma float64) *RTGProtocol {\n\trtg := new(RTGProtocol)\n\trtg.ringQModCount = len(q)\n\trtg.ringPModulusBigint = big.NewInt(1)\n\tfor _, pi := range p {\n\t\trtg.ringPModulusBigint.Mul(rtg.ringPModulusBigint, new(big.Int).SetUint64(pi))\n\t}\n\trtg.alpha = len(p)\n\tif rtg.alpha != 0 {\n\t\trtg.beta = int(math.Ceil(float64(len(q)) / float64(len(p))))\n\t} else {\n\t\trtg.beta = 1\n\t}\n\tvar err error\n\trtg.ringQP, err = ring.NewRing(n, append(q, p...))\n\tif err != nil {\n\t\tpanic(err) // TODO error\n\t}\n\n\tprng, err := utils.NewPRNG()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trtg.gaussianSampler = ring.NewGaussianSampler(prng)\n\trtg.sigma = sigma\n\n\trtg.tmpPoly = [2]*ring.Poly{rtg.ringQP.NewPoly(), rtg.ringQP.NewPoly()}\n\n\treturn rtg\n}", "func NewRBAC(address common.Address, backend bind.ContractBackend) (*RBAC, error) {\n\tcontract, err := bindRBAC(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBAC{RBACCaller: RBACCaller{contract: contract}, RBACTransactor: RBACTransactor{contract: contract}, RBACFilterer: RBACFilterer{contract: contract}}, nil\n}", "func QuestionCreateView(req helios.Request) {\n\tuser, ok := req.GetContextData(auth.UserContextKey).(auth.User)\n\tif !ok {\n\t\treq.SendJSON(helios.ErrInternalServerError.GetMessage(), helios.ErrInternalServerError.GetStatusCode())\n\t\treturn\n\t}\n\n\tvar eventSlug string = req.GetURLParam(\"eventSlug\")\n\tvar questionData QuestionData\n\tvar question Question\n\tvar err helios.Error\n\terr = req.DeserializeRequestData(&questionData)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\terr = DeserializeQuestion(questionData, &question)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\tquestion.ID = 0\n\terr = UpsertQuestion(user, eventSlug, &question)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\n\treq.SendJSON(SerializeQuestion(question), http.StatusCreated)\n}", "func (r *Poll) NewRelationshipRecord(field string) (kallax.Record, error) {\n\tswitch field {\n\tcase \"Options\":\n\t\treturn new(PollOption), nil\n\n\t}\n\treturn nil, fmt.Errorf(\"kallax: model Poll has no relationship %s\", field)\n}", "func (eb EntertainmentBusiness) AsAnswer() (*Answer, bool) {\n\treturn nil, false\n}", "func NewPartita(id, squadraA, squadraB string) (p Partita, err error) {\n\tp = Partita{id: \"\", squadraA: \"\", squadraB: \"\"}\n\tif su.IsBlank(id) {\n\t\terr = errors.New(\"L'ID partita non è valido.\")\n\t\treturn\n\t}\n\tif su.IsBlank(squadraA) {\n\t\terr = errors.New(\"La squadra A non è valida.\")\n\t\treturn\n\t}\n\tif su.IsBlank(squadraB) {\n\t\terr = errors.New(\"La squadra B non è valida.\")\n\t\treturn\n\t}\n\tp.id = id\n\tp.squadraA = squadraA\n\tp.squadraB = squadraB\n\terr = nil\n\treturn\n}", "func (l *LNCChallenger) NewChallenge(price int64) (string, lntypes.Hash,\n\terror) {\n\n\treturn l.lndChallenger.NewChallenge(price)\n}", "func New(ac *apictx.Context, router *httprouter.Router) {\n\t// Handle the routes\n\trouter.POST(\"/api/v1/email\", HandlePost(ac))\n}", "func NewRobertaForTokenClassification(p *nn.Path, config *bert.BertConfig) *RobertaForTokenClassification {\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config)\n\tdropout := util.NewDropout(config.HiddenDropoutProb)\n\tnumLabels := int64(len(config.Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\treturn &RobertaForTokenClassification{\n\t\troberta: roberta,\n\t\tdropout: dropout,\n\t\tclassifier: classifier,\n\t}\n}", "func NewPlanner()(*Planner) {\n m := &Planner{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewProgram(cfg *client.Config, parentName string) *tea.Program {\n\tm := NewModel(cfg)\n\tm.standalone = true\n\tm.parentName = parentName\n\treturn tea.NewProgram(m)\n}", "func NewRR(backends ...Backend) *RR {\n\treturn &RR{backends, 0}\n}", "func NewAnswerRepository(dbConn *gorm.DB) AnswerRepository {\n\treturn &answerConnection{\n\t\tconnection: dbConn,\n\t}\n}", "func NewHub(ctx context.Context, cancel context.CancelFunc) *hub {\n\tlog.Println(\"Creating new Arke hub.\")\n\tnew_root := newTopicNode(ctx, cancel, []string{rootName})\n\n\th := &hub{\n\t\troot: new_root,\n\t\tpub: make(chan *publication, hubBufferSize),\n\t\tsub: make(chan *subscription, hubBufferSize),\n\t\tcleanup: make(chan []string, hubBufferSize),\n\t}\n\n\th.start()\n\treturn h\n}", "func NewChoice() Choice {\n\treturn new(ChoiceImpl)\n}", "func NewPhonebook(name string) *Phonebook {\n\tp := &Phonebook{\n\t\tName: name,\n\t}\n\treturn p\n}", "func (bbo *TabularBBO) NewEpisode() {}", "func NewUserAnswer(postID, user string, answers []string) UserAnswer {\n\treturn UserAnswer{\n\t\tPostID: postID,\n\t\tUser: user,\n\t\tAnswers: answers,\n\t}\n}", "func NewAppConsentApprovalRoute()(*AppConsentApprovalRoute) {\n m := &AppConsentApprovalRoute{\n Entity: *NewEntity(),\n }\n return m\n}", "func (lb LodgingBusiness) AsAnswer() (*Answer, bool) {\n\treturn nil, false\n}", "func NewRBACTransactor(address common.Address, transactor bind.ContractTransactor) (*RBACTransactor, error) {\n\tcontract, err := bindRBAC(address, nil, transactor, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RBACTransactor{contract: contract}, nil\n}", "func NewReview() *Review {\n\treturn &Review{}\n}", "func NewRHT() *RHT {\n\treturn &RHT{\n\t\telementQueueMapByKey: make(map[string]*PriorityQueue),\n\t\titemMapByCreatedAt: make(map[string]*PQItem),\n\t}\n}", "func NewQuizCaller(address common.Address, caller bind.ContractCaller) (*QuizCaller, error) {\n\tcontract, err := bindQuiz(address, caller, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &QuizCaller{contract: contract}, nil\n}", "func newTaskBuilder(b *jobBuilder, name string) *taskBuilder {\n\tparts, err := b.jobNameSchema.ParseJobName(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &taskBuilder{\n\t\tjobBuilder: b,\n\t\tparts: parts,\n\t\tName: name,\n\t\tSpec: &specs.TaskSpec{},\n\t\trecipeProperties: map[string]string{},\n\t}\n}", "func New(conf *Config) Rclone {\n\treturn Rclone{config: conf}\n}", "func (n *Builder) NewReply(parent interface{}, content string, metadata []byte) (*Reply, error) {\n\tqcontent, err := fields.NewQualifiedContent(fields.ContentTypeUTF8String, []byte(content))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create qualified content of type %d from %s\", fields.ContentTypeUTF8String, content)\n\t}\n\tqmeta, err := fields.NewQualifiedContent(fields.ContentTypeTwig, metadata)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create qualified content of type %d from %s\", fields.ContentTypeTwig, metadata)\n\t}\n\treturn n.NewReplyQualified(parent, qcontent, qmeta)\n}", "func NewReceipt() *Receipt {\n return &Receipt{}\n}", "func NewJourneyPlanner(database db.Database) (*journeyPlanner,error) {\n\n\t// Create planner\n\tjp := new(journeyPlanner)\n\n\t// Create or open table\n\ttable,err := database.OpenTable(journeyPlannerTableName)\n\tif err == db.ETABLENOTFOUND { \n\t\ttable,err = database.CreateTable(journeyPlannerTableName)\n\t}\n\tif err != nil {\n\t\treturn jp,err\n\t}\n\tjp.table = table\n\treturn jp,nil\n}", "func New(in io.Reader, out, err io.Writer) Interface {\n\tvar surv Survey\n\n\tif v, ok := in.(terminal.FileReader); ok {\n\t\tsurv.In = v\n\t}\n\n\tif v, ok := out.(terminal.FileWriter); ok {\n\t\tsurv.Out = v\n\t}\n\n\tif v, ok := err.(terminal.FileWriter); ok {\n\t\tsurv.Err = v\n\t}\n\n\treturn &surv\n}", "func NewRelation(writter http.ResponseWriter, request *http.Request) {\n\tID := request.URL.Query().Get(\"id\")\n\tif len(ID) < 1 {\n\t\thttp.Error(writter, \"ID parameter missing\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar relation models.Relation\n\trelation.UserId = UserId\n\trelation.UserRelationId = ID\n\n\tstatus, err := db.NewRelation(relation)\n\tif err != nil {\n\t\thttp.Error(writter, \"Error while creating new relation\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !status {\n\t\thttp.Error(writter, \"Error while creating new relation\", http.StatusBadRequest)\n\t\treturn\n\t}\n\twritter.Header().Set(\"content-type\", \"application/json\")\n\twritter.WriteHeader(http.StatusCreated)\n}", "func NewPoll(\n\tquestion string, endDate time.Time, providedAnswers []ProvidedAnswer, allowMultipleAnswers, allowsAnswerEdits bool,\n) *Poll {\n\treturn &Poll{\n\t\tQuestion: question,\n\t\tEndDate: endDate,\n\t\tProvidedAnswers: providedAnswers,\n\t\tAllowsMultipleAnswers: allowMultipleAnswers,\n\t\tAllowsAnswerEdits: allowsAnswerEdits,\n\t}\n}", "func newKartaDiagram(w, h float64, c, r int) *diagram.Diagram {\n\tbbox := voronoi.NewBBox(0, w, 0, h)\n\tsites := randomSites(bbox, c)\n\n\t// Compute voronoi diagram.\n\td := voronoi.ComputeDiagram(sites, bbox, true)\n\n\t// Max number of iterations is 16\n\tif r > 16 {\n\t\tr = 16\n\t}\n\n\t// Relax using Lloyd's algorithm\n\tfor i := 0; i < r; i++ {\n\t\tsites = utils.LloydRelaxation(d.Cells)\n\t\td = voronoi.ComputeDiagram(sites, bbox, true)\n\t}\n\n\tcenter := voronoi.Vertex{float64(w / 2), float64(h / 2)}\n\n\treturn &diagram.Diagram{d, center}\n}", "func NewARPReply(src *Addr, dst *Addr) ([]byte, error) {\n\treturn buildPacket(src, dst, layers.ARPReply)\n}", "func NewBusinessScenarioPlanner()(*BusinessScenarioPlanner) {\n m := &BusinessScenarioPlanner{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewPlannerAssignedToTaskBoardTaskFormat()(*PlannerAssignedToTaskBoardTaskFormat) {\n m := &PlannerAssignedToTaskBoardTaskFormat{\n Entity: *NewEntity(),\n }\n return m\n}", "func NewFAQBot() *Bot {\n\tcommands := []cmd.Command{\n\t\tcmd.NewStatus(),\n\t\t// cmd.NewRomans(),\n\t\t// cmd.NewThanks(),\n\t\tcmd.NewGameNotAvailable(),\n\t\tcmd.NewUpdateLauncher(),\n\t\tcmd.NewInstallLinux(),\n\t\tcmd.NewGameDoesntStart(),\n\t\tcmd.NewChatEmpty(),\n\t\tcmd.NewChangeUsername(),\n\t}\n\t// targetedCmd := cmd.CreateTargetedCommands()\n\t// commands = append(commands, targetedCmd...)\n\t// globalCmd := cmd.CreateGlobalCommands()\n\t// commands = append(commands, globalCmd...)\n\tbot := &Bot{\n\t\tCommands: commands,\n\t}\n\treturn bot\n}", "func getAnswerCipher() cipher.AEAD {\n\tblock, err := aes.NewCipher([]byte(\"HideEulerAnswer!\"))\n\tFatalOnError(err, \"aes.NewCipher\")\n\tgcm, err := cipher.NewGCM(block)\n\tFatalOnError(err, \"cipher.NewGCM\")\n\treturn gcm\n}", "func NewRaid(inputPlanes ...Plane) (Raid, error) {\n\tif len(inputPlanes) == 0 {\n\t\treturn Raid{}, errors.New(\"no planes to launch\")\n\t}\n\tvar planes []Plane\n\tfor _, plane := range inputPlanes {\n\t\tplanes = append(planes, plane)\n\t}\n\treturn Raid{Planes: planes}, nil\n}", "func New[T float.DType](c Config) *RAdam[T] {\n\tadam := &RAdam[T]{\n\t\tConfig: c,\n\t\tRoMax: 2.0/(1.0-c.Beta2) - 1.0,\n\t\tTimeStep: 1.0,\n\t}\n\treturn adam\n}", "func New(logger *zap.Logger, cfg config.Alerts) *Alerter {\n\treturn &Alerter{\n\t\tlogger: logger.Named(\"alerter\"),\n\t\tcfg: cfg,\n\t\ttwilio: twilio.NewClient(cfg.SID, cfg.AuthToken, nil),\n\t}\n}", "func NewLLRB(name string, setts s.Settings) *LLRB {\n\tllrb := &LLRB{name: name, finch: make(chan struct{})}\n\tllrb.logprefix = fmt.Sprintf(\"LLRB [%s]\", name)\n\tllrb.inittxns()\n\n\tsetts = make(s.Settings).Mixin(Defaultsettings(), setts)\n\tllrb.readsettings(setts)\n\tllrb.setts = setts\n\n\tllrb.nodearena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\tllrb.valarena = malloc.NewArena(llrb.memcapacity, llrb.allocator)\n\n\t// statistics\n\tllrb.h_upsertdepth = lib.NewhistorgramInt64(10, 100, 10)\n\n\tinfof(\"%v started ...\\n\", llrb.logprefix)\n\tllrb.logarenasettings()\n\treturn llrb\n}", "func (c *Client) NewProposal(np *www.NewProposal) (*www.NewProposalReply, error) {\n\tresponseBody, err := c.makeRequest(http.MethodPost,\n\t\twww.PoliteiaWWWAPIRoute, www.RouteNewProposal, np)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar npr www.NewProposalReply\n\terr = json.Unmarshal(responseBody, &npr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshal NewProposalReply: %v\", err)\n\t}\n\n\tif c.cfg.Verbose {\n\t\terr := prettyPrintJSON(npr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &npr, nil\n}", "func newGame() *guessingGame {\n\treturn &guessingGame{\n\t\tnum: rand.Intn(10) + 1,\n\t}\n}", "func NewRR(s string) (dns.RR, error) {\n\tif len(s) > 0 && s[len(s)-1] != '\\n' { // We need a closing newline\n\t\treturn ReadRR(strings.NewReader(s + \"\\n\"))\n\t}\n\treturn ReadRR(strings.NewReader(s))\n}", "func (c Client) New(params *stripe.TreasuryCreditReversalParams) (*stripe.TreasuryCreditReversal, error) {\n\tcreditreversal := &stripe.TreasuryCreditReversal{}\n\terr := c.B.Call(\n\t\thttp.MethodPost,\n\t\t\"/v1/treasury/credit_reversals\",\n\t\tc.Key,\n\t\tparams,\n\t\tcreditreversal,\n\t)\n\treturn creditreversal, err\n}", "func NewRule(uniqifier int) *RuleBuilder {\n\truleIDBytes := sha256.Sum256([]byte(fmt.Sprintf(\"rule-id%v\", uniqifier)))\n\tvar bugID bugs.BugID\n\tif uniqifier%2 == 0 {\n\t\tbugID = bugs.BugID{System: \"monorail\", ID: fmt.Sprintf(\"chromium/%v\", uniqifier)}\n\t} else {\n\t\tbugID = bugs.BugID{System: \"buganizer\", ID: fmt.Sprintf(\"%v\", uniqifier)}\n\t}\n\n\trule := FailureAssociationRule{\n\t\tProject: testProject,\n\t\tRuleID: hex.EncodeToString(ruleIDBytes[0:16]),\n\t\tRuleDefinition: \"reason LIKE \\\"%exit code 5%\\\" AND test LIKE \\\"tast.arc.%\\\"\",\n\t\tBugID: bugID,\n\t\tIsActive: true,\n\t\tIsManagingBug: true,\n\t\tIsManagingBugPriority: true,\n\t\tIsManagingBugPriorityLastUpdated: time.Date(1900, 1, 2, 3, 4, 8, uniqifier, time.UTC),\n\t\tCreationTime: time.Date(1900, 1, 2, 3, 4, 5, uniqifier, time.UTC),\n\t\tCreationUser: LUCIAnalysisSystem,\n\t\tLastUpdated: time.Date(1900, 1, 2, 3, 4, 7, uniqifier, time.UTC),\n\t\tLastUpdatedUser: \"[email protected]\",\n\t\tPredicateLastUpdated: time.Date(1900, 1, 2, 3, 4, 6, uniqifier, time.UTC),\n\t\tSourceCluster: clustering.ClusterID{\n\t\t\tAlgorithm: fmt.Sprintf(\"clusteralg%v-v9\", uniqifier),\n\t\t\tID: hex.EncodeToString([]byte(fmt.Sprintf(\"id%v\", uniqifier))),\n\t\t},\n\t}\n\treturn &RuleBuilder{\n\t\trule: rule,\n\t\tuniqifier: uniqifier,\n\t}\n}", "func NewPlanner(db DB) *Planner {\n\treturn &Planner{\n\t\tDB: db,\n\t\tNow: time.Now,\n\t}\n}" ]
[ "0.5639432", "0.56050396", "0.5415833", "0.5342135", "0.5241635", "0.5227963", "0.5099866", "0.4905231", "0.4904413", "0.47154996", "0.47037742", "0.46589753", "0.45973787", "0.45820704", "0.4568143", "0.45237657", "0.45206556", "0.4516852", "0.45102775", "0.45020384", "0.44491366", "0.44486582", "0.44427642", "0.44302973", "0.4402574", "0.4398957", "0.43888626", "0.4367999", "0.435992", "0.43493718", "0.4345529", "0.4322659", "0.43216884", "0.4286402", "0.42769197", "0.42704993", "0.42688027", "0.42647925", "0.4263155", "0.4237959", "0.42298985", "0.42253724", "0.42191765", "0.42017803", "0.41895005", "0.41702142", "0.41660327", "0.41594276", "0.41591257", "0.41534835", "0.4142849", "0.4139294", "0.4137872", "0.41293618", "0.41164404", "0.41146833", "0.41011316", "0.40955028", "0.40809664", "0.40622124", "0.4058926", "0.40586028", "0.40473306", "0.4041882", "0.40410116", "0.40342408", "0.40341124", "0.40340343", "0.40301087", "0.40295768", "0.40271488", "0.4019739", "0.401796", "0.4015905", "0.40156472", "0.40149567", "0.40106314", "0.4008066", "0.40049806", "0.40036362", "0.39986962", "0.39941415", "0.3990422", "0.39889157", "0.39765015", "0.39687878", "0.39663333", "0.3963419", "0.39619347", "0.39608902", "0.39576718", "0.39567593", "0.39526817", "0.3952334", "0.39462727", "0.39434254", "0.3940235", "0.39274228", "0.3921512", "0.39180708" ]
0.71885735
0
Load loads model from file or model name. It also updates default configuration parameters if provided. This method implements `PretrainedModel` interface.
func (qa *RobertaForQuestionAnswering) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error { var urlOrFilename string // If modelName, infer to default configuration filename: if modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok { urlOrFilename = modelFile } else { // Otherwise, just take the input urlOrFilename = modelNameOrPath } cachedFile, err := util.CachedPath(urlOrFilename) if err != nil { return err } vs := nn.NewVarStore(device) p := vs.Root() roberta := bert.NewBertModel(p.Sub("roberta"), config.(*bert.BertConfig)) numLabels := int64(2) qaOutputs := nn.NewLinear(p.Sub("qa_outputs"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig()) qa.roberta = roberta qa.qaOutputs = qaOutputs err = vs.Load(cachedFile) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Load(fileName string, src interface{}) error {\n\tfile, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\tif err == nil {\n\t\tdecoder := gob.NewDecoder(file)\n\t\tif err = decoder.Decode(src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t// Restore parameters\n\tswitch src.(type) {\n\tcase Model:\n\t\tmodel := src.(Model)\n\t\tmodel.SetParams(model.GetParams())\n\tdefault:\n\t\treturn errors.New(\"the file is not a model dump\")\n\t}\n\treturn nil\n}", "func (mlm *RobertaForMaskedLM) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmlm.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmlm.lmHead = NewRobertaLMHead(p.Sub(\"lm_head\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (mc *RobertaForMultipleChoice) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tmc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tmc.dropout = util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, 1, nn.DefaultLinearConfig())\n\tmc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (sc *RobertaForSequenceClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\tsc.roberta = bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tsc.classifier = NewRobertaClassificationHead(p.Sub(\"classifier\"), config.(*bert.BertConfig))\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Model) Load(path string) error {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\tif err := json.Unmarshal(data, m); err != nil {\n\t\treturn errors.Wrap(err, \"load model\")\n\t}\n\treturn nil\n}", "func Load(modelArchive string, framework Framework, flags ModelFlags) (*Model, error) {\n\tf, _ := os.Open(modelArchive)\n\tdefer f.Close()\n\tvar outDir string\n\tif fi, err := f.Stat(); err == nil && fi.IsDir() {\n\t\toutDir = modelArchive\n\t} else if err == nil && !fi.IsDir() {\n\t\ttmpDir := os.TempDir()\n\t\toutDir = filepath.Join(tmpDir, utils.PseudoUuid())\n\t\tif err := utils.Unzip(modelArchive, outDir); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to extract model archive: %v\", err)\n\t\t}\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s does not exist\", modelArchive)\n\t}\n\n\tmodelFilename := filepath.Join(outDir, \"saved_model.pb\")\n\tif _, err := os.Stat(modelFilename); err != nil {\n\t\t// This if is here for when we can read pbtxt files\n\t\tif _, err2 := os.Stat(modelFilename + \"txt\"); err2 == nil {\n\t\t\tmodelFilename = modelFilename + \"txt\"\n\t\t\treturn nil, errors.New(\"Currently loading saved_model.pbtxt is not supported\")\n\t\t\t//comment the return when we can read pbtxt\n\t\t} else {\n\t\t\treturn nil, errors.New(\"saved_model.pb does not exist\")\n\t\t}\n\t}\n\n\tflags.ModelPath = outDir\n\tflags.ModelFile = modelFilename\n\tvar model Model\n\terr := framework.Load(&model, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &model, nil\n}", "func (tc *RobertaForTokenClassification) Load(modelNameOrPath string, config interface{ pretrained.Config }, params map[string]interface{}, device gotch.Device) error {\n\tvar urlOrFilename string\n\t// If modelName, infer to default configuration filename:\n\tif modelFile, ok := pretrained.RobertaModels[modelNameOrPath]; ok {\n\t\turlOrFilename = modelFile\n\t} else {\n\t\t// Otherwise, just take the input\n\t\turlOrFilename = modelNameOrPath\n\t}\n\n\tcachedFile, err := util.CachedPath(urlOrFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs := nn.NewVarStore(device)\n\tp := vs.Root()\n\n\troberta := bert.NewBertModel(p.Sub(\"roberta\"), config.(*bert.BertConfig))\n\tdropout := util.NewDropout(config.(*bert.BertConfig).HiddenDropoutProb)\n\tnumLabels := int64(len(config.(*bert.BertConfig).Id2Label))\n\tclassifier := nn.NewLinear(p.Sub(\"classifier\"), config.(*bert.BertConfig).HiddenSize, numLabels, nn.DefaultLinearConfig())\n\n\ttc.roberta = roberta\n\ttc.dropout = dropout\n\ttc.classifier = classifier\n\n\terr = vs.Load(cachedFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (am *AssetManager) LoadModel(name, iname string) {\n\tif strings.Contains(name, \".obj\") {\n\t\tam.Models[iname] = NewWavefrontModelFromFile(am.modelsDir + name)\n\t} else {\n\t\tlog.Fatal(\"cannot find \" + name)\n\t}\n}", "func Load(model interface{}, provider Provider, strict bool) error {\n\treturn load(model, provider, strict)\n}", "func LoadModel(r io.Reader) (Model, error) {\n\tdec := json.NewDecoder(r)\n\tvar m Model\n\tif err := dec.Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\tm.setWeightVec()\n\treturn m, nil\n}", "func Load(modelName string) (r *pb.TextResponse, err error) {\n\tif modelName == \"\" {\n\t\tmodelName = defaultModel\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tr, err = grpcClient.LoadModel(ctx, &pb.TextRequest{Text: modelName})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}", "func (s *DataStore) Load() error {\n\tfile, err := os.Open(s.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ts.Lock()\n\tdefer s.Unlock()\n\n\terr = json.NewDecoder(file).Decode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func LoadModelFile(path string) (Model, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fp.Close()\n\treturn LoadModel(fp)\n}", "func Load(filename string) (*SvmModel, error) {\n\n\tcfn := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(cfn))\n\n\tmdl := C.svm_load_model(cfn)\n\tif mdl == nil {\n\t\treturn nil, SvmError{Message: fmt.Sprintf(\"unable to load model file: %s\", filename)}\n\t}\n\n\treturn &SvmModel{object: mdl}, nil\n}", "func (wrapper *TvmWrapper) LoadModel(modelParam *ModelParam) (*moduleInfo, error) {\n\tdefer runtime.GC()\n\n\t// debug model parameters\n\tfmt.Print(modelParam.DebugStr())\n\n\t// load module library\n\tfmt.Print(\"start to load module library...\\n\")\n\tmodLibP, err := gotvm.LoadModuleFromFile(modelParam.ModelLibPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// read module json file\n\tfmt.Print(\"start to read module json file...\\n\")\n\tbytes, err := ioutil.ReadFile(modelParam.ModelJSONPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tmodJsonStr := string(bytes)\n\n\t// create graph module of tvm\n\tfmt.Print(\"start to create graph module of tvm...\\n\")\n\tfuncp, err := gotvm.GetGlobalFunction(\"tvm.graph_runtime.create\")\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t\treturn nil, err\n\t}\n\t// graph_runtime.create\n\t// arg[0] : model json text\n\t// arg[1] : model library\n\t// arg[2] : device type (ex. KDLCPU, KDLGPU...)\n\t// arg[3] : device id\n\tgraphrt, err := funcp.Invoke(modJsonStr, modLibP, wrapper.config.DeviceType, (int64)(0))\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tgraphmod := graphrt.AsModule()\n\n\t// import params to graph module\n\tfmt.Print(\"start to import params to graph module...\\n\")\n\tbytes, err = ioutil.ReadFile(modelParam.ModelParamsPath)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\tfuncp, err = graphmod.GetFunction(\"load_params\")\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\t_, err = funcp.Invoke(bytes)\n\tif err != nil {\n\t\tfmt.Print(err.Error())\n\t\treturn nil, err\n\t}\n\n\t// create module information\n\tfmt.Print(\"start to create module information...\\n\")\n\tinfo := newModuleInfo(graphmod, modelParam.InputShape, modelParam.OutputShape)\n\treturn info, nil\n}", "func loadModel(modelName string) (multilayer.MultiLayerPerceptron, error) {\n\tf, err := os.Open(\"models/\" + modelName + \".model.gob\")\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, fmt.Errorf(\"failed opening model: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\n\tnn := multilayer.MultiLayerPerceptron{}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn multilayer.MultiLayerPerceptron{}, err\n\t}\n\terr = nn.UnmarshalBinary(data)\n\treturn nn, err\n}", "func (t *TOMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif t.Reader != nil {\n\t\tr = t.Reader\n\t} else if t.Path != \"\" {\n\t\tfile, err := getConfig(t.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tif _, err := toml.DecodeReader(r, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (env *Environment) LoadExistingModel(m string) *text.NaiveBayes {\n\t// get the classifier definition to make sure it is well defined\n\tclf := env.GetClassifierDefinition(m)\n\tclf.panicErrors()\n\n\tstreamChan := make(chan base.TextDatapoint, clf.TextChannelSize)\n\tmodel := clf.getModel(streamChan)\n\terr := model.RestoreFromFile(env.baseModelPath(clf.ModelOut))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn model\n}", "func Load(fileName string) (*openapi3.Swagger, error) {\n\tmodel, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile(fileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = model.Validate(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"Loaded OpenAPI 3 Specification file:\", fileName)\n\treturn model, nil\n}", "func Load(r io.Reader) error {\n\treturn DefaultInstance.Load(r)\n}", "func (l *OptionalTOMLLoader) Load(s interface{}) error {\n\tif _, err := os.Stat(l.Path); err == nil {\n\t\treturn l.TOMLLoader.Load(s)\n\t}\n\treturn nil\n}", "func (e *CachedEnforcer) LoadModel() error {\n\tif e.autoClear {\n\t\tdefer e.InvalidateCache()\n\t}\n\treturn e.base.LoadModel()\n}", "func (c *IntentClassifier) Load(filePath string) error {\n\tlog.Printf(\"Loading Classifier from %s...\", filePath)\n\tmeta := persist.Load(filePath)\n\t//get the classifier current meta data\n\tname, version := c.getMeta()\n\tif meta.Name != name {\n\t\treturn fmt.Errorf(\"This file doesn't contain a KNearestNeighbors classifier\")\n\t}\n\tif meta.Version != version {\n\t\treturn fmt.Errorf(\"Can't understand this file format\")\n\t}\n\n\tdecoder := gob.NewDecoder(bytes.NewBuffer(meta.Data))\n\terr := decoder.Decode(&c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error decoding RNN checkpoint file: %s\", err)\n\t}\n\n\tcheckpointFile = filePath\n\treturn nil\n}", "func (k *KMP) Load(filepath, format string) error {\n\tvar err error\n\tswitch format {\n\tcase \"json\":\n\t\tf, err := os.Open(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tb, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = json.Unmarshal(b, k)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid load format, %s\", format)\n\t}\n\treturn err\n}", "func Load(config interface{}, filename string) error {\n\tv := reflect.ValueOf(config).Elem()\n\tif err := applyDefaults(reflect.StructField{}, v); err != nil {\n\t\treturn fmt.Errorf(\"init config with default values: %s\", err)\n\t}\n\n\tif err := mergeJSONConfig(config, filename); err != nil {\n\t\treturn err\n\t}\n\n\tif err := applyEnv(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn validate(config)\n}", "func Load(filename string) (*Params, error) {\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar params Params\n\tif err := json.Unmarshal(file, &params); err != nil {\n\t\tlog.Printf(\"failed to parse %s: %s\", file, string(file))\n\t\treturn nil, err\n\t}\n\treturn &params, nil\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func Load(path string, v interface{}) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn Unmarshal(f, v)\n}", "func (lm *LocalMeta) Load() error {\n\t// initialize gset\n\tvar err error\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, \"\")\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfile, err := os.Open(lm.filename)\n\tif err != nil && !os.IsNotExist(errors.Cause(err)) {\n\t\treturn errors.Trace(err)\n\t}\n\n\tif os.IsNotExist(errors.Cause(err)) {\n\t\treturn nil\n\t}\n\tdefer file.Close()\n\n\t_, err = toml.DecodeReader(file, lm)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tlm.gset, err = gtid.ParserGTID(lm.flavor, lm.BinlogGTID)\n\treturn errors.Trace(err)\n}", "func InitModel(modelDir string, modelFile string) *TfModel {\n\tmodelpath := filepath.Join(modelDir, modelFile)\n\tmodel, err := ioutil.ReadFile(modelpath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Construct an in-memory graph from the serialized form.\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\toperations := graph.Operations()\n\tfor _, op := range operations {\n\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t}\n\t// Create a session for inference over graph.\n\tsession, err := tf.NewSession(graph, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &TfModel{Model: &tf.SavedModel{Graph: graph, Session: session}}\n}", "func (e *Definition) Load(path, entity string) error {\n\n\tfullPath := filepath.Join(path, entity)\n\n\tb, err := ioutil.ReadFile(fullPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontent := string(b)\n\te.json = jsonutil.NewFromString(content)\n\te.byteRead = 0\n\n\ts, err := schema.Read(e)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read schema: %s\", err)\n\t\treturn err\n\t}\n\n\te.schema = s\n\tv := validator.New(s)\n\te.validator = v\n\treturn nil\n}", "func Load(reader io.Reader, configuration interface{}) error {\n\tif err := FromYAML(reader, configuration); err != nil {\n\t\treturn err\n\t}\n\treturn FromEnv(configuration)\n}", "func Init(path string, tags []string) *TfModel {\n\tmodel, err := tf.LoadSavedModel(path, tags, nil)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading Saved Model:%v\\n\", err.Error())\n\t\treturn nil\n\t}\n\toperations := model.Graph.Operations()\n\tfor _, op := range operations {\n\t\tname := op.Name()\n\t\tif strings.HasPrefix(name, \"sentence\") || strings.HasPrefix(name, \"dropout\") || strings.HasPrefix(name, \"inference\") {\n\t\t\tlog.Println(\"op name:\", op.Name(), \"NumOutputs:\", op.NumOutputs())\n\t\t}\n\t}\n\tlog.Println(\"op loading finished\")\n\treturn &TfModel{Model: model}\n}", "func Load(filename string, v interface{}) {\n\tParse(read(filename), v)\n}", "func (trm *TrmConfig) Load(pathTrm, pathVoice string) {\n\tfmt.Println(\"trm config load\")\n\ttrm.OpenJSON(pathTrm)\n\ttrm.OpenJSON(pathVoice)\n}", "func Load() error {\n\treturn def.Load()\n}", "func LoadModel(args ...interface{}) (*WordModel, error) {\n\tvar arg interface{}\n\tif len(args) == 0 {\n\t\targ = \"https://raw.githubusercontent.com/go-ego/gse/master/data/dict/dictionary.txt\"\n\t} else {\n\t\targ = args[0]\n\t}\n\n\tr, err := readerFromAnything(arg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmodel := NewWordModel()\n\n\tscanner := bufio.NewScanner(r)\n\tvar words []WordFreq\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, errors.New(\"Error: not enough fields\")\n\t\t}\n\t\tword := fields[0]\n\t\tfreq, _ := strconv.ParseFloat(fields[1], 32)\n\t\tif len([]rune(word)) < 2 {\n\t\t\t//freq = 2\n\t\t}\n\t\twords = append(words, WordFreq{\n\t\t\tWord: word,\n\t\t\tLogProbability: float32((freq)),\n\t\t})\n\t}\n\n\tsort.Slice(words, func(a, b int) bool {\n\t\treturn words[a].Word < words[b].Word\n\t})\n\n\tprev := \"\"\n\tfor _, word := range words {\n\t\tif word.Word == prev {\n\t\t\tcontinue\n\t\t}\n\t\tprev = word.Word\n\t\tmodel.AddWord(word.Word, word.LogProbability)\n\t}\n\n\tmodel.Finish()\n\n\treturn model, nil\n}", "func (self *LSHforest) Load(path string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn msgpack.Unmarshal(b, self)\n}", "func Load() models.Language {\n\tif models.ConfigFile != \"\" {\n\t\tlangFile = models.ConfigFile\n\t} else {\n\t\tmodels.ConfigFile = langFile\n\t}\n\n\tlang := language.LoadLanguages(langFile)\n\treturn lang\n}", "func (g *Gonf) Load() error {\n\tb, err := ioutil.ReadFile(g.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcfg := map[string]interface{}{}\n\tif err := json.Unmarshal(b, &cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// forbids access to Get/Set local and HTTP while reloading\n\tg.confLock.Lock()\n\tdefer g.confLock.Unlock()\n\tg.conf = cfg\n\n\treturn g.load(cfg, []string{}, []otoFlag{})\n}", "func Load(config interface{}, configPath string) error {\n\tswitch fileExtension(configPath) {\n\tcase \"yaml\":\n\t\treturn loadYaml(config, configPath)\n\tcase \"json\":\n\t\treturn loadJson(config, configPath)\n\tdefault:\n\t\treturn ero.Newf(\"Can not support load file %s\", configPath)\n\t}\n}", "func (lf LoaderFunc) Load(serverType string) (Input, error) {\n\treturn lf(serverType)\n}", "func Load(v interface{}, loadFrom string) error {\n\tcfg, err := ini.Load(loadFrom)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.NameMapper = ini.TitleUnderscore\n\n\treturn cfg.MapTo(v)\n}", "func Load(filePath string, t Tomler) error {\n\ttomlValue := t.TOMLValue()\n\tvar err error\n\tif _, err = toml.DecodeFile(filePath, tomlValue); err != nil {\n\t\treturn err\n\t}\n\treturn t.FromTOML(tomlValue)\n}", "func (p *BaseProvider) Load() error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (env *Environment) Load(source, code string) error {\n\treturn nil\n}", "func (b *baseLoader) Load(ctx context.Context, src *url.URL) (*Schema, error) {\n\t// open IO\n\tvar r io.ReadCloser\n\tswitch src.Scheme {\n\tcase \"file\":\n\t\tvar err error\n\t\tif r, err = os.Open(src.Path); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q from %q: %w\", src.Path, src, err)\n\t\t}\n\tcase \"http\", \"https\":\n\t\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, src.String(), nil)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create request for %q: %w\", src, err)\n\t\t}\n\t\tresp, err := b.client.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed requesting %q: %w\", src, err)\n\t\t}\n\t\tr = resp.Body\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported scheme: %v\", src.Scheme)\n\t}\n\tdefer func() {\n\t\t_ = r.Close()\n\t}()\n\n\t// read and init schema\n\tvar s Schema\n\tif err := json.NewDecoder(r).Decode(&s); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding %q failed: %w\", src, err)\n\t}\n\tif s.ID == nil {\n\t\treturn nil, fmt.Errorf(\"no ID set on %q\", src)\n\t}\n\ts.calculateID()\n\ts.setSrc(src)\n\n\treturn &s, nil\n}", "func Load(path string) (*OBJFile, error) {\n\tin, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer in.Close()\n\treturn Decode(in)\n}", "func (dto *GetAdapterModelResponse) Load(data base.ModelInterface) error {\n\tm, ok := data.(*model.AdapterModel)\n\tif !ok {\n\t\tlog.Error(\"GetAdapterModelResponse.Load() failed, convert interface failed.\")\n\t\treturn base.ErrorDataConvert\n\t}\n\tdto.GetResponse.Load(&m.Model)\n\tdto.Name = m.Name\n\tdto.Type = m.Type\n\tdto.Capability.Load(m.Capability)\n\treturn nil\n}", "func (l *Loader) LoadObjModel(file string) models.RawModel {\n\tdat, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvertices := make([]mgl32.Vec3, 0)\n\ttextures := make([]mgl32.Vec2, 0)\n\tnormals := make([]mgl32.Vec3, 0)\n\tvar verticesArray []float32\n\tvar texturesArray []float32\n\tvar normalsArray []float32\n\tindicesArray := make([]uint32, 0)\n\tlines := strings.Split(string(dat), \"\\n\")\n\tvar fStart int\n\tfor i, line := range lines {\n\t\tsplited := strings.Split(line, \" \")\n\t\tif len(splited) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tt := splited[0]\n\t\tif t == \"v\" {\n\t\t\tvertices = append(vertices, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vn\" {\n\t\t\tnormals = append(normals, mgl32.Vec3{toFloat(splited[1]), toFloat(splited[2]), toFloat(splited[3])})\n\t\t}\n\t\tif t == \"vt\" {\n\t\t\ttextures = append(textures, mgl32.Vec2{toFloat(splited[1]), toFloat(splited[2])})\n\t\t}\n\t\tif t == \"f\" {\n\t\t\tfStart = i\n\t\t\ttexturesArray = make([]float32, len(vertices)*2)\n\t\t\tnormalsArray = make([]float32, len(vertices)*3)\n\t\t\tverticesArray = make([]float32, len(vertices)*3)\n\t\t\tbreak\n\t\t}\n\t}\n\tfor i := fStart; i < len(lines); i++ {\n\t\tsplited := strings.Split(lines[i], \" \")\n\t\tif len(splited) == 0 || splited[0] != \"f\" {\n\t\t\tbreak\n\t\t}\n\t\tvertex1 := strings.Split(splited[1], \"/\")\n\t\tvertex2 := strings.Split(splited[2], \"/\")\n\t\tvertex3 := strings.Split(splited[3], \"/\")\n\t\tindicesArray = processVertex(vertex1, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex2, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t\tindicesArray = processVertex(vertex3, indicesArray, textures, normals, vertices, texturesArray, normalsArray, verticesArray)\n\t}\n\tcolors := make([]float32, len(normalsArray))\n\tfor i := range colors {\n\t\tcolors[i] = 1\n\t}\n\treturn l.LoadToVAO(verticesArray, texturesArray, indicesArray, normalsArray, colors)\n}", "func (f *Flow) Load(cacheDir string) (err error) {\n\tif f.FlowFile == \"\" {\n\t\treturn nil\n\t}\n\tvar content []byte\n\tswitch getURLType(f.FlowFile) {\n\tcase \"local\":\n\t\tcontent, err = ioutil.ReadFile(f.FlowFile)\n\tcase \"web\":\n\t\tcontent, err = get(cacheDir, f.FlowFile)\n\t// TODO git - including the branch\n\tdefault:\n\t\treturn fmt.Errorf(\"unrecognised floe file type: <%s>\", f.FlowFile)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// unmarshal into a flow\n\tnewFlow := &Flow{}\n\terr = yaml.Unmarshal(content, &newFlow)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set up the flow, and copy bits into this flow\n\terr = newFlow.zero()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(newFlow.Name) != 0 {\n\t\tf.Name = newFlow.Name\n\t}\n\tf.ReuseSpace = newFlow.ReuseSpace\n\tif len(newFlow.HostTags) != 0 {\n\t\tf.HostTags = newFlow.HostTags\n\t}\n\tif len(newFlow.ResourceTags) != 0 {\n\t\tf.ResourceTags = newFlow.ResourceTags\n\t}\n\tif len(newFlow.Env) != 0 {\n\t\tf.Env = newFlow.Env\n\t}\n\tif len(newFlow.Tasks) != 0 {\n\t\tf.Tasks = newFlow.Tasks\n\t}\n\t// Pointless overriding triggers - as they are what caused this load\n\treturn nil\n}", "func (s *CommandLineSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.callback != nil {\n\t\treturn s.koanf.Load(posflag.ProviderWithFlag(s.flags, \".\", s.koanf, s.callback), nil)\n\t}\n\n\treturn s.koanf.Load(posflag.Provider(s.flags, \".\", s.koanf), nil)\n}", "func (s *YAMLFileSource) Load(_ *schema.StructValidator) (err error) {\n\tif s.path == \"\" {\n\t\treturn errors.New(\"invalid yaml path source configuration\")\n\t}\n\n\treturn s.koanf.Load(file.Provider(s.path), yaml.Parser())\n}", "func Load(p string) (Spec, error) {\n\tvar spec Spec\n\n\tbuf, err := os.ReadFile(p)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to read file: %s - %w\", p, err)\n\t}\n\n\terr = yaml.Unmarshal(buf, &spec)\n\tif err != nil {\n\t\treturn spec, fmt.Errorf(\"failed to parse spec: %s - %w\", p, err)\n\t}\n\n\tspec.Path = p\n\n\treturn spec, nil\n}", "func Load(config *Config) error {\n\treturn NewLoader(config).Load()\n}", "func Load(path string, target interface{}) error {\n\tformatter, err := parsePath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn load(formatter, data, target)\n}", "func Load(filepath string, config interface{}) error {\n\tmagazine := make(map[string]interface{})\n\tfileBytes, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := yaml.Unmarshal(fileBytes, &magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagazine = flatten(magazine)\n\tif err := applyEnv(magazine); err != nil {\n\t\treturn err\n\t}\n\n\tmagBytes, err := yaml.Marshal(bellows.Expand(magazine))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(magBytes, config)\n}", "func (m *SynapsesPersist) Load() {\n\tdataPath, err := filepath.Abs(m.relativePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teFile, err := os.Open(dataPath + m.file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer eFile.Close()\n\n\tbytes, err := ioutil.ReadAll(eFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(bytes, &m.Synapses)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.Error(\"Was not able to open file\", \"path\", path, \"error\", err)\n\t\treturn err\n\t}\n\tdecoder := gob.NewDecoder(file)\n\terr = decoder.Decode(object)\n\tif err != nil {\n\t\tlog.Error(\"Was not able to decode file.\", \"path\", path, \"error\", err)\n\t}\n\treturn err\n}", "func (s *JsonSource) Load() error {\n\n\tfile, err := ioutil.ReadFile(s.Path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal([]byte(file), s.TargetStruct)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (defaultStorage) Load() error {\n\tpanic(noConfigStorage)\n}", "func (function *Function) Load() (err error) {\n\tdefinition, err := ioutil.ReadFile(function.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfunction.Definition = string(definition)\n\n\treturn\n}", "func Load(state *state.State, driverName string, name string, config map[string]string, logger logger.Logger, volIDFunc func(volType VolumeType, volName string) (int64, error), commonRulesFunc func() map[string]func(string) error) (Driver, error) {\n\t// Locate the driver loader.\n\tdriverFunc, ok := drivers[driverName]\n\tif !ok {\n\t\treturn nil, ErrUnknownDriver\n\t}\n\n\td := driverFunc()\n\terr := d.init(state, name, config, logger, volIDFunc, commonRulesFunc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d, nil\n}", "func (vm *BFVM) LoadFromString(source string) error {\n\treturn vm.LoadFromStream(strings.NewReader(source))\n}", "func (appConf *AppConf) Load(filename string, forceReload bool) (*AppConf, error){\n\t// appConf is load and force reload is false return direction\n\tif isLoad && !forceReload{\n\t\treturn appConf, nil\n\t}\n\tfilename, err := appConf.getEnvConfigPath(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = toml.DecodeFile(filename, appConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"使用配置文件: %s\", filename)\n\t// mark appConf as loaded\n\tisLoad = true\n\treturn appConf, nil\n}", "func (d *Datastore) Load() (Object, error) {\n\td.localLock.Lock()\n\tdefer d.localLock.Unlock()\n\n\t// clear Object first, as mapstructure's decoder doesn't have ZeroFields set to true for merging purposes\n\td.meta.Object = d.meta.Object[:0]\n\n\terr := d.kv.LoadConfig(d.meta)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = d.meta.unmarshall()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d.meta.object, nil\n}", "func (ctx *AppContext) Load(env string) {\n\tlog.Println(\"Load app context\")\n\n\t// Load env specific config\n\tenvConfig := viper.Sub(env)\n\tctx.Env = env\n\tctx.ProjectID = envConfig.GetString(\"project_id\")\n\tctx.SuffixOfKind = envConfig.GetString(\"datastore.kind_suffix\")\n\tctx.EtcdServers = envConfig.GetStringSlice(\"etcd\")\n\n\t// Load common config\n\tctx.CommonConfig = viper.Sub(\"common\")\n}", "func Load(path string, object interface{}) error {\n\tfile, err := os.Open(path)\n\tif err == nil {\n\t\tdecoder := json.NewDecoder(file)\n\t\terr = decoder.Decode(object)\n\t}\n\tfile.Close()\n\treturn err\n}", "func Load() {\n\tvar err error\n\n\tconfLen := len(FilePath)\n\tif confLen != 0 {\n\t\terr = readFromJSON(FilePath)\n\t}\n\tif err == nil {\n\t\terr = readFromENV()\n\t}\n\tif err != nil {\n\t\tpanic(`Configuration not found. Please specify configuration`)\n\t}\n}", "func Load(r io.Reader) (*Config, error) {\n\tvar c Config\n\tif err := defaults.Set(&c); err != nil {\n\t\treturn nil, err\n\t}\n\tc.init()\n\tvar raw map[string]any\n\tif _, err := toml.NewDecoder(r).Decode(&raw); err != nil {\n\t\treturn nil, errors.Wrap(err, \"config: error decoding toml data\")\n\t}\n\tif err := c.parse(raw); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func TestDnn_LoadModel(t *testing.T) {\n\t//MODEL_PARAM=tmodel.pb,input_1,reshape_3/Reshape\n\tparam := os.Getenv(\"MODEL_PARAM\")\n\tif param == \"\" {\n\t\tt.Skip(\"Skipping model loading test; no MODEL_PARAM set\")\n\t\t//t.Error(\"no MODEL_PARAM set\")\n\t}\n\tstr2dnnfilter := func(inp string) VideoProfile {\n\t\tdnnfilter := VideoProfile{}\n\t\tstrs := strings.Split(inp, \",\")\n\t\tif len(strs) != 3 {\n\t\t\treturn dnnfilter\n\t\t}\n\t\tdnnfilter.Detector.ModelPath = strs[0]\n\t\tdnnfilter.Detector.Input = strs[1]\n\t\tdnnfilter.Detector.Output = strs[2]\n\t\treturn dnnfilter\n\t}\n\n\t_, dir := setupTest(t)\n\tdefer os.RemoveAll(dir)\n\n\tdnncfg := str2dnnfilter(param)\n\n\tif len(dnncfg.Detector.ModelPath) <= 0 || len(dnncfg.Detector.Input) <= 0 || len(dnncfg.Detector.Output) <= 0 {\n\t\tt.Errorf(\"invalid MODEL_PARAM set %v\", param)\n\t}\n\n\tdnnfilter := NewDnnFilter()\n\tdnnfilter.dnncfg = dnncfg\n\tif dnnfilter.InitDnnFilter(dnncfg) != true {\n\t\tt.Errorf(\"Can not load model file %v\", dnncfg.Detector.ModelPath)\n\t}\n\tdnnfilter.StopDnnFilter()\n}", "func (p *Puck) Load(name ...string) error {\n\tcmd := []byte(\"load();\\n\")\n\terr := p.command(name, cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (l *tomlLoader) Load(out interface{}) error {\n\tif _, err := toml.DecodeReader(l.r, out); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Load(key string, data []byte) Entity {\n\tvar (\n\t\tbuffer bytes.Buffer\n\t\tentity Entity\n\t)\n\n\tbuffer.Write(data)\n\tdecoder := gob.NewDecoder(&buffer)\n\tentityType := strings.Split(key, \".\")[0]\n\n\tswitch entityType {\n\tcase \"player\":\n\t\tentity = new(Player)\n\tcase \"planet\":\n\t\tentity = new(Planet)\n\tcase \"mission\":\n\t\tentity = new(Mission)\n\tcase \"sun\":\n\t\tentity = new(Sun)\n\tcase \"ss\":\n\t\tentity = new(SolarSlot)\n\tcase \"spy_report\":\n\t\tentity = new(SpyReport)\n\tdefault:\n\t\treturn nil\n\t}\n\tdecoder.Decode(entity)\n\treturn entity\n}", "func Load(r io.Reader, v interface{}) error {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, v)\n}", "func (j *JSONLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\tif j.Reader != nil {\n\t\tr = j.Reader\n\t} else if j.Path != \"\" {\n\t\tfile, err := getConfig(j.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\treturn json.NewDecoder(r).Decode(s)\n}", "func (y *YAMLLoader) Load(s interface{}) error {\n\tvar r io.Reader\n\n\tif y.Reader != nil {\n\t\tr = y.Reader\n\t} else if y.Path != \"\" {\n\t\tfile, err := getConfig(y.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tr = file\n\t} else {\n\t\treturn ErrSourceNotSet\n\t}\n\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn yaml.Unmarshal(data, s)\n}", "func LoadConfig(path string) *Config {\n\tdefaultConfig := defaultConfig()\n\tfmt.Println(path)\n\tfmt.Println(defaultConfig)\n\tif _, err := toml.DecodeFile(path, defaultConfig); err != nil {\n\t\tlog.Fatal(\"error\", err.Error())\n\t}\n\tfmt.Println(defaultConfig)\n\treturn defaultConfig\n}", "func (m *Method) TrainModel(c *gin.Context) {\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(c.Request.Body)\n\tJSONStr := buf.String()\n\tm.GoPython(`ml.py`, JSONStr)\n\n\tvar response Response = Response{Status: `model training started`}\n\tc.JSON(http.StatusOK, response)\n}", "func (tfl tiltfileLoader) Load(ctx context.Context, tf *corev1alpha1.Tiltfile, prevResult *TiltfileLoadResult) TiltfileLoadResult {\n\tstart := time.Now()\n\tfilename := tf.Spec.Path\n\tabsFilename, err := ospath.RealAbs(tf.Spec.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn TiltfileLoadResult{\n\t\t\t\tConfigFiles: []string{filename},\n\t\t\t\tError: fmt.Errorf(\"No Tiltfile found at paths '%s'. Check out https://docs.tilt.dev/tutorial.html\", filename),\n\t\t\t}\n\t\t}\n\t\tabsFilename, _ = filepath.Abs(filename)\n\t\treturn TiltfileLoadResult{\n\t\t\tConfigFiles: []string{absFilename},\n\t\t\tError: err,\n\t\t}\n\t}\n\n\ttiltignorePath := watch.TiltignorePath(absFilename)\n\ttlr := TiltfileLoadResult{\n\t\tConfigFiles: []string{absFilename, tiltignorePath},\n\t}\n\n\ttiltignore, err := watch.ReadTiltignore(tiltignorePath)\n\n\t// missing tiltignore is fine, but a filesystem error is not\n\tif err != nil {\n\t\ttlr.Error = err\n\t\treturn tlr\n\t}\n\n\ttlr.Tiltignore = tiltignore\n\n\ts := newTiltfileState(ctx, tfl.dcCli, tfl.webHost, tfl.execer, tfl.k8sContextPlugin, tfl.versionPlugin,\n\t\ttfl.configPlugin, tfl.extensionPlugin, tfl.ciSettingsPlugin, feature.FromDefaults(tfl.fDefaults))\n\n\tmanifests, result, err := s.loadManifests(tf)\n\n\ttlr.BuiltinCalls = result.BuiltinCalls\n\ttlr.DefaultRegistry = s.defaultReg\n\n\t// All data models are loaded with GetState. We ignore the error if the state\n\t// isn't properly loaded. This is necessary for handling partial Tiltfile\n\t// execution correctly, where some state is correctly assembled but other\n\t// state is not (and should be assumed empty).\n\tws, _ := watch.GetState(result)\n\ttlr.WatchSettings = ws\n\n\t// NOTE(maia): if/when add secret settings that affect the engine, add them to tlr here\n\tss, _ := secretsettings.GetState(result)\n\ts.secretSettings = ss\n\n\tioState, _ := io.GetState(result)\n\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, ioState.Paths...)\n\ttlr.ConfigFiles = append(tlr.ConfigFiles, s.postExecReadFiles...)\n\ttlr.ConfigFiles = sliceutils.DedupedAndSorted(tlr.ConfigFiles)\n\n\tdps, _ := dockerprune.GetState(result)\n\ttlr.DockerPruneSettings = dps\n\n\taSettings, _ := tiltfileanalytics.GetState(result)\n\ttlr.AnalyticsOpt = aSettings.Opt\n\n\ttlr.Secrets = s.extractSecrets()\n\ttlr.FeatureFlags = s.features.ToEnabled()\n\ttlr.Error = err\n\ttlr.Manifests = manifests\n\ttlr.TeamID = s.teamID\n\n\tobjectSet, _ := v1alpha1.GetState(result)\n\ttlr.ObjectSet = objectSet\n\n\tvs, _ := version.GetState(result)\n\ttlr.VersionSettings = vs\n\n\ttelemetrySettings, _ := telemetry.GetState(result)\n\ttlr.TelemetrySettings = telemetrySettings\n\n\tus, _ := updatesettings.GetState(result)\n\ttlr.UpdateSettings = us\n\n\tci, _ := cisettings.GetState(result)\n\ttlr.CISettings = ci\n\n\tconfigSettings, _ := config.GetState(result)\n\tif tlr.Error == nil {\n\t\ttlr.EnabledManifests, tlr.Error = configSettings.EnabledResources(tf, manifests)\n\t}\n\n\tduration := time.Since(start)\n\tif tlr.Error == nil {\n\t\ts.logger.Infof(\"Successfully loaded Tiltfile (%s)\", duration)\n\t}\n\textState, _ := tiltextension.GetState(result)\n\thashState, _ := hasher.GetState(result)\n\n\tvar prevHashes hasher.Hashes\n\tif prevResult != nil {\n\t\tprevHashes = prevResult.Hashes\n\t}\n\ttlr.Hashes = hashState.GetHashes()\n\n\ttfl.reportTiltfileLoaded(s.builtinCallCounts, s.builtinArgCounts, duration,\n\t\textState.ExtsLoaded, prevHashes, tlr.Hashes)\n\n\tif len(aSettings.CustomTagsToReport) > 0 {\n\t\treportCustomTags(tfl.analytics, aSettings.CustomTagsToReport)\n\t}\n\n\treturn tlr\n}", "func (k *Kluster) Load() error {\n\tif err := k.LoadSummary(); err != nil {\n\t\treturn err\n\t}\n\n\t// DEBUG:\n\t// fmt.Printf(\"DEBUG: cluster %s config version: %s\\tMin: %s\\tMax: %s\\n\", k.Name, k.Version, MinSemVersion, SemVersion)\n\n\tver, err := version.NewSemVer(k.Version)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"the cluster version (%s) is not well formed or not SemVer compliance. %s\", k.Version, err)\n\t}\n\tif ver.LT(MinSemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is not supported by this KubeKit, the minimun version supported is %s\", k.Version, MinVersion)\n\t}\n\tif ver.GT(SemVersion) {\n\t\treturn fmt.Errorf(\"the cluster version %s is greater than the cluster version supported by this KubeKit (%s)\", k.Version, Version)\n\t}\n\n\tk.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tname := k.Platform()\n\tconfig := k.Platforms[name]\n\n\tcred, err := k.GetCredentials()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tplatform, err := provisioner.NewPlatform(name, k.Name, config, cred, k.ui, k.Version)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.provisioner[name] = platform\n\n\treturn nil\n}", "func (c *Info) Load() error {\n\tb, err := ioutil.ReadFile(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Lock()\n\terr = json.Unmarshal(b, c)\n\tc.Unlock()\n\n\treturn err\n}", "func Load(filename string) (*Beam, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treader := bufio.NewReader(f)\n\tdecoder := json.NewDecoder(reader)\n\tdecoder.DisallowUnknownFields()\n\tcfg := new(Beam)\n\t// This **Beam double-pointer appears to be required to detect an invalid\n\t// input of \"null\". See Test_Load/file_contains_null test.\n\terr = decoder.Decode(&cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error decoding JSON value in %v: %v\", filename, err)\n\t}\n\tif cfg == nil {\n\t\treturn nil, fmt.Errorf(\"loading %v resulted in nil config\", filename)\n\t}\n\tif decoder.More() {\n\t\treturn nil, fmt.Errorf(\"found unexpected data after config in %v\", filename)\n\t}\n\treturn cfg, nil\n}", "func (fb *FlowBuilder) Load(rawData []byte) *FlowBuilder {\n\tfb.flow = flow.New()\n\tfb.flow.UseRegistry(fb.registry)\n\n\tdoc := &FlowDocument{[]Node{}, []Link{}, []Trigger{}}\n\tlog.Println(\"Loading document from:\", string(rawData))\n\terr := json.Unmarshal(rawData, doc)\n\tif err != nil {\n\t\tfb.Err = err\n\t\treturn fb\n\t}\n\n\tfb.Doc = doc\n\n\treturn fb\n}", "func (s *Startup) Load() error {\n\n\t// TODO: parameterize startup config file name\n\tjsonFile, err := ioutil.ReadFile(\"startup.json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(jsonFile, s); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil // no error\n}", "func (component *Component) Load(filename string) error {\n\treturn util.LoadYAML(filename, component)\n}", "func (l *Loader) Load() (*Config, error) {\n\tif l.ConfigPath == \"\" {\n\t\treturn nil, errors.Reason(\"-qscheduler-config is required\").Err()\n\t}\n\n\tblob, err := ioutil.ReadFile(l.ConfigPath)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to open the config file\").Err()\n\t}\n\n\tcfg := &Config{}\n\tif err := proto.UnmarshalText(string(blob), cfg); err != nil {\n\t\treturn nil, errors.Annotate(err, \"not a valid Config proto message\").Err()\n\t}\n\n\tl.lastGood.Store(cfg)\n\treturn cfg, nil\n}", "func (s *EnvironmentSource) Load(_ *schema.StructValidator) (err error) {\n\tkeyMap, ignoredKeys := getEnvConfigMap(schema.Keys, s.prefix, s.delimiter)\n\n\treturn s.koanf.Load(env.ProviderWithValue(s.prefix, constDelimiter, koanfEnvironmentCallback(keyMap, ignoredKeys, s.prefix, s.delimiter)), nil)\n}", "func Load(filename string, data any, validation bool) error {\n\tisJSON := strings.HasSuffix(filename, \".json\")\n\n\tbs, err := os.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif validation {\n\t\terr := validate(bs, data, isJSON)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn unmarshal(bs, data, isJSON)\n}", "func Load(env string) *Configuration {\n\t_, filePath, _, _ := runtime.Caller(0)\n\tconfigName := \"config.\" + env + \".yaml\"\n\tconfigPath := filePath[:len(filePath)-9] + \"files\" + string(filepath.Separator)\n\n\tviper.SetConfigName(configName)\n\tviper.AddConfigPath(configPath)\n\tviper.SetConfigType(\"yaml\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar config Configuration\n\tviper.Unmarshal(&config)\n\tsetGinMode(config.Server.Mode)\n\n\treturn &config\n}", "func Load(path string) (*LevelDB, error) {\n\treturn LoadWithOptions(path, DefaultOptions)\n}", "func Load(name string, data interface{}) error {\n\tp := jsonPath(name)\n\t// Don't load anything if the file doesn't exist\n\t_, err := os.Stat(p)\n\tif os.IsNotExist(err) {\n\t\tlog.Printf(\"File %s didn't exist, loading with fresh data\\n\", p)\n\t\treturn nil\n\t}\n\n\t// Read and unmarshal the json\n\tif b, err := ioutil.ReadFile(p); err != nil {\n\t\treturn err\n\t} else if len(b) == 0 {\n\t\tlog.Printf(\"File %s was empty, loading with fresh data\\n\", p)\n\t\treturn nil\n\t} else if err := json.Unmarshal(b, data); err != nil {\n\t\treturn fmt.Errorf(\"failed to load file %s error: %s\", p, err)\n\t}\n\n\tlog.Printf(\"Loaded %s\\n\", p)\n\treturn nil\n}", "func (rs *Restake) LoadProto(pbAct *iotextypes.StakeRestake) error {\n\tif pbAct == nil {\n\t\treturn ErrNilProto\n\t}\n\n\trs.bucketIndex = pbAct.GetBucketIndex()\n\trs.payload = pbAct.GetPayload()\n\trs.duration = pbAct.GetStakedDuration()\n\trs.autoStake = pbAct.GetAutoStake()\n\n\treturn nil\n}", "func (config *Config) Load() error {\n\tvar env string\n\tflag.StringVar(&env, \"env\", \"dev\", \"environment\")\n\n\tflag.Parse()\n\n\tviperRegistry := viper.New()\n\tviperRegistry.AddConfigPath(\"./config\")\n\tviperRegistry.SetConfigName(env)\n\tviperRegistry.SetConfigType(\"json\")\n\tviperRegistry.SetEnvPrefix(\"todo\")\n\tviperRegistry.AutomaticEnv()\n\n\tconfig.Env = env\n\n\tif err := viperRegistry.ReadInConfig(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureApplication(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureDB(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\tif err := config.configureAuth(viperRegistry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (wlt *Wallet) Load(dir string) error {\n\tr := &ReadableWallet{}\n\tif err := r.Load(filepath.Join(dir, wlt.GetFilename())); err != nil {\n\t\treturn err\n\t}\n\tr.Meta[\"filename\"] = wlt.GetFilename()\n\t*wlt = NewWalletFromReadable(r)\n\treturn nil\n}", "func Load(filepath string, startTag, endTag string, vars map[string]string) (result string, err error) {\n\tvar data []byte\n\tif data, err = ioutil.ReadFile(filepath); err == nil {\n\t\tvar tpl *Engine\n\t\tif tpl, err = New(string(data), startTag, endTag); err == nil {\n\t\t\tif result, err = tpl.Process(vars); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if err == errs.TmplVarsNotFoundError {\n\t\t\terr = nil\n\t\t\tresult = string(data)\n\t\t}\n\t}\n\treturn\n}", "func (l *Loader) Load(cfg *config.Config) {\n\tcfg.Address = os.Getenv(\"BRCEP_ADDRESS\")\n\tcfg.LogLevel = os.Getenv(\"BRCEP_LOG_LEVEL\")\n\tcfg.PreferredAPI = os.Getenv(\"BRCEP_PREFERRED_API\")\n\tcfg.ViaCepURL = os.Getenv(\"BRCEP_VIACEP_URL\")\n\tcfg.CepAbertoURL = os.Getenv(\"BRCEP_CEPABERTO_URL\")\n\tcfg.CepAbertoToken = os.Getenv(\"BRCEP_CEPABERTO_TOKEN\")\n\tcfg.CorreiosURL = os.Getenv(\"BRCEP_CORREIOS_URL\")\n}", "func Load(cfg interface{}, configPath string) error {\n\tif err := readConfigFile(configPath, cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Load(p string) (cfg *Config, err error) {\n\tvar d []byte\n\td, err = ioutil.ReadFile(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcfg = new(Config)\n\tif err = yaml.Unmarshal(d, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif cfg.ClusterState == nil {\n\t\tcfg.ClusterState = &ClusterState{}\n\t}\n\tif cfg.ALBIngressController == nil {\n\t\tcfg.ALBIngressController = &ALBIngressController{}\n\t}\n\n\tcfg.ConfigPath, err = filepath.Abs(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.ClusterState.UpTook != \"\" {\n\t\tcfg.ClusterState.upTook, err = time.ParseDuration(cfg.ClusterState.UpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif cfg.ALBIngressController.IngressUpTook != \"\" {\n\t\tcfg.ALBIngressController.ingressUpTook, err = time.ParseDuration(cfg.ALBIngressController.IngressUpTook)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn cfg, nil\n}" ]
[ "0.70864344", "0.6942464", "0.69314396", "0.69175935", "0.6770165", "0.6715859", "0.6647983", "0.66319776", "0.64276546", "0.6366989", "0.63446957", "0.6211604", "0.620865", "0.6141415", "0.6127916", "0.59314406", "0.5909854", "0.58246374", "0.5804325", "0.57926095", "0.56939393", "0.5684256", "0.56761587", "0.5629053", "0.5624951", "0.551845", "0.54964244", "0.54948115", "0.5485581", "0.54699135", "0.5465822", "0.5462308", "0.5448593", "0.5435977", "0.5431546", "0.54205436", "0.53927976", "0.5384202", "0.53778386", "0.5366092", "0.5361847", "0.5339832", "0.5310002", "0.5309079", "0.5252111", "0.5243783", "0.5243783", "0.5209713", "0.5200675", "0.51913345", "0.51870203", "0.5179164", "0.51774514", "0.5174737", "0.5173414", "0.5159533", "0.5153861", "0.51490957", "0.5142908", "0.5137269", "0.5136551", "0.51351047", "0.5117679", "0.5104352", "0.510171", "0.50979114", "0.5096669", "0.50808024", "0.5070745", "0.50225466", "0.5018498", "0.5015809", "0.50139666", "0.50027645", "0.49856207", "0.4971469", "0.4967214", "0.496231", "0.4960345", "0.49553794", "0.49447638", "0.49440604", "0.49325326", "0.49304086", "0.4926125", "0.49201232", "0.4917339", "0.4904832", "0.49040154", "0.48990056", "0.4897339", "0.4882487", "0.48742315", "0.48718324", "0.4870223", "0.48689577", "0.4866218", "0.48580316", "0.48447737", "0.4835707" ]
0.6570828
8
ForwadT forwards pass through the model.
func (qa *RobertaForQuestionAnswering) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (startScores, endScores *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) { hiddenState, _, hiddenStates, attentions, err := qa.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train) if err != nil { return ts.None, ts.None, nil, nil, err } sequenceOutput := hiddenState.Apply(qa.qaOutputs) logits := sequenceOutput.MustSplit(1, -1, true) startScores = logits[0].MustSqueeze1(-1, false) endScores = logits[1].MustSqueeze1(-1, false) for _, x := range logits { x.MustDrop() } return startScores, endScores, hiddenStates, attentions, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Model) Forward(qkv attention.QKV) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: m.Key.Forward(qkv.Keys...),\n\t\tValues: m.Value.Forward(qkv.Values...),\n\t}\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (mod *backendModule) Forward(f *gatepb.Forward) error {\n\treturn mod.send(proto.Type(f.Typ), f)\n}", "func (f *Forwarder) Forward(data *call.CallData) {\n\tf.transferAgents.Range(func(key interface{}, value interface{}) bool {\n\t\tstreamId := key.(userid.ID)\n\t\tstream := value.(TransferAgent)\n\t\tif streamId == userid.ID(data.UserId) { // Don't need to forward data back to sender\n\t\t\treturn true\n\t\t}\n\n\t\tif err := stream.Send(data); err != nil {\n\t\t\tf.logger.Error(err)\n\t\t}\n\n\t\treturn true\n\t})\n}", "func (obj *Doc) Forward(ctx context.Context) error {\n\terr := obj.RPC(ctx, \"Forward\", nil)\n\treturn err\n}", "func (a *insertApp) forward(app *App, args ...interface{}) error {\n\tapp.State = \"pending\"\n\treturn db.Session.Apps().Insert(app)\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\th := nn.Affine(g, m.B, m.W, x)\n\tif yPrev != nil {\n\t\th = g.Add(h, g.Prod(m.WRec, yPrev))\n\t}\n\ts.Y = g.Invoke(m.Activation, h)\n\treturn\n}", "func (m *Model) Forward(x *Node, states States) (rv *Node, err error) {\n\trv = x\n\tfor _, l := range m.Layers {\n\t\tif rv, err = l.Forward(rv, states); err != nil {\n\t\t\treturn nil, errors.Wrap(err, l.Name())\n\t\t}\n\t}\n\treturn rv, nil\n}", "func (m *EventItemRequestBuilder) Forward()(*i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.ForwardRequestBuilder) {\n return i06b377af3ae66d378617ba4960aa8e040b78e63f3ebfd980bf3a5d47930f6ecc.NewForwardRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func (q *CQPU) forward(predicate []*pbUtils.AttributePredicate, streamRec *pbQPU.ResponseStreamRecord, streamOut pbQPU.QPU_QueryServer, seqID *int64, respond bool) error {\n\tif respond {\n\t\terr := streamOut.Send(\n\t\t\tprotoutils.ResponseStreamRecord(\n\t\t\t\t*seqID,\n\t\t\t\tstreamRec.GetType(),\n\t\t\t\tstreamRec.GetLogOp(),\n\t\t\t))\n\t\t(*seqID)++\n\t\treturn err\n\t}\n\treturn nil\n}", "func forward(c *cli.Context, name string) error {\n\tdb, err := pomegranate.Connect(c.String(\"dburl\"))\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tdir := c.String(\"dir\")\n\tallMigrations, err := pomegranate.ReadMigrationFiles(dir)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\terr = pomegranate.MigrateForwardTo(name, db, allMigrations, true)\n\tif err != nil {\n\t\treturn cli.NewExitError(err, 1)\n\t}\n\tfmt.Println(\"Done\")\n\treturn nil\n}", "func (a *provisionApp) forward(app *App, args ...interface{}) error {\n\tvar units uint\n\tif len(args) > 0 {\n\t\tswitch args[0].(type) {\n\t\tcase int:\n\t\t\tunits = uint(args[0].(int))\n\t\tcase int64:\n\t\t\tunits = uint(args[0].(int64))\n\t\tcase uint:\n\t\t\tunits = args[0].(uint)\n\t\tcase uint64:\n\t\t\tunits = uint(args[0].(uint64))\n\t\tdefault:\n\t\t\tunits = 1\n\t\t}\n\t}\n\terr := Provisioner.Provision(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif units > 1 {\n\t\t_, err = Provisioner.AddUnits(app, units-1)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *ItemCalendarsItemCalendarViewEventItemRequestBuilder) Forward()(*ItemCalendarsItemCalendarViewItemForwardRequestBuilder) {\n return NewItemCalendarsItemCalendarViewItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (b *TestDriver) Forward(val int) error {\n\tlog.Printf(\"Forward: %d\", val)\n\n\treturn nil\n}", "func (t *Transaction) forwardTransaction() {\n\tif t.tx == nil {\n\t\tpanic(\"tx is nil while forward was being called\")\n\t}\n\tselect {\n\tcase t.sendTxFound <- t.tx:\n\tcase <-t.shutdown:\n\t\treturn\n\t}\n}", "func (ph *Handler) Forward() {\n\terr := recover()\n\tph.forward(err)\n}", "func (rt *Router) forward() {\n\tfor i, v := range rt.InInterfaceL {\n\t\t//pktS := \"\"\n\n\t\t// TRYE\n\t\t// get packet from interface i\n\t\tif pktS, err := v.Get(); err == nil {\n\t\t\t//fmt.Println(\"in routher forward, packet from Get(): \", pktS)\n\t\t\t// if packet exists make a forwarding decision\n\t\t\tp, err := FromByteS(pktS)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Could not get packet\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// HERE you will need to implement a lookup into the\n\t\t\t// forwarding table to find the appropriate outgoing interface\n\t\t\t// for now we assume the outgoing interface is also i\n\t\t\tfmt.Printf(\"%s: forwarding packet %s from interface %d to %d with mtu %d\\n\", rt.Str(), p.Str(), i, i, rt.OutInterfaceL[i].Mtu)\n\n\t\t\tif err = rt.OutInterfaceL[i].Put(p.ToByteS(), false); err != nil {\n\t\t\t\t//log.Printf(\"Could not put packet %s in router %s, into outInterface %d. Error: %s\", p.str, rt.forward, i, err)\n\t\t\t\tlog.Printf(\"%s: packet '%s' lost on interface %d\\n\", rt.Str(), i)\n\t\t\t}\n\t\t}\n\t\t//log.Println(\"no packet to forard in router\")\n\t}\n}", "func (inst *instance) Forward(port int) (string, error) {\n\tvar reply proxyrpc.ForwardResult\n\terr := inst.ProxyApp.Call(\n\t\t\"ProxyVM.Forward\",\n\t\tproxyrpc.ForwardParams{\n\t\t\tID: inst.ID,\n\t\t\tPort: port,\n\t\t},\n\t\t&reply)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reply.ManagerAddress, nil\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (p *Pipeline) FeedForward(index int, seqNo int, data interface{}) {\n\tif index++; index < len(p.nodes) {\n\t\tp.nodes[index].Feed(p, index, seqNo, data)\n\t}\n}", "func (t *Type) ForwardType() *ForwardType", "func (m *Model) Forward(cache Cache, q, x []mat.Tensor) ([]mat.Tensor, []mat.Tensor, Cache) {\n\tvar pk, pv mat.Tensor\n\n\tpq := m.Query.Forward(q...)\n\n\tif hasCache := cache.HasValues(); hasCache && m.IsCrossAttention {\n\t\tpk = cache[0]\n\t\tpv = cache[1]\n\t} else {\n\t\tk := m.Key.Forward(x...)\n\t\tv := m.Value.Forward(x...)\n\n\t\tif hasCache {\n\t\t\tpk = ag.AppendRows(cache[0], k...)\n\t\t\tpv = ag.AppendRows(cache[1], v...)\n\t\t} else {\n\t\t\tpk = ag.Stack(k...)\n\t\t\tpv = ag.Stack(v...)\n\t\t}\n\t}\n\n\tresult, weights := attention.ScaledDotProductAttention(pq, pk, pv, m.ScaleFactor, m.UseCausalMask)\n\n\treturn result, weights, Cache{pk, pv}\n}", "func (m *Model) forward(x ag.Node) (s *State) {\n\tg := m.Graph()\n\ts = new(State)\n\tyPrev := m.prev()\n\ts.InG = g.Sigmoid(nn.Affine(g, m.BIn, m.WIn, x, m.WInRec, yPrev))\n\ts.ForG = g.Sigmoid(nn.Affine(g, m.BFor, m.WFor, x, m.WForRec, yPrev))\n\ts.Cand = g.Tanh(g.Mul(m.WCand, x))\n\ts.Y = g.Prod(s.InG, s.Cand)\n\tif yPrev != nil {\n\t\ts.Y = g.Add(s.Y, g.Prod(g.Tanh(yPrev), s.ForG))\n\t}\n\treturn\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tg := m.Graph()\n\thalfSize := xs[0].Value().Size() / 2\n\n\tres := make([]ag.Node, len(xs))\n\tgate := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\tres[i] = g.View(x, 0, 0, halfSize, 1)\n\t\tgate[i] = g.View(x, halfSize, 0, halfSize, 1)\n\t}\n\n\tgate = m.Norm.Forward(gate...)\n\tgate = m.Proj.Forward(gate...)\n\n\tif m.Act != nil {\n\t\tgate = m.Act.Forward(gate...)\n\t}\n\n\ty := make([]ag.Node, len(gate))\n\tfor i := range y {\n\t\ty[i] = g.Prod(gate[i], res[i])\n\t}\n\treturn y\n}", "func (m *Mind) Forward(in *mat64.Dense) {\n\tinput := mat64.DenseCopyOf(in)\n\tm.Results.HiddenSum = mat64.NewDense(1, 1, nil)\n\n\tir, ic := input.Dims()\n\tor, oc := m.Weights.InputHidden.Dims()\n\tlog.Println(\"input dims(r,c):\", ir, ic)\n\tlog.Println(\"InputHidden dims(r,c):\", or, oc)\n\n\tinput.Product(m.Weights.InputHidden)\n\tm.Results.HiddenSum = mat64.DenseCopyOf(input)\n\tm.Results.HiddenResult = m.Activate(m.Results.HiddenSum)\n\t//m.Results.OutputSum = mat64.NewDense(1, 1, nil)\n\tm.Results.HiddenResult.Product(m.Weights.HiddenOutput)\n\tm.Results.OutputSum = mat64.DenseCopyOf(m.Results.HiddenResult)\n\tm.Results.OutputResult = m.Activate(m.Results.OutputSum)\n}", "func Forward(bus EventBus) EventHandler {\n\treturn Handler(func(evt Event) error {\n\t\tbus.Publish(evt)\n\t\treturn nil\n\t})\n}", "func (req *RequestData) Forward(client *http.Client, config BasketConfig, basket string) (*http.Response, error) {\n\tforwardURL, err := url.ParseRequestURI(config.ForwardURL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid forward URL: %s - %s\", config.ForwardURL, err)\n\t}\n\n\t// expand path\n\tif config.ExpandPath && len(req.Path) > len(basket)+1 {\n\t\tforwardURL.Path = expandURL(forwardURL.Path, req.Path, basket)\n\t}\n\n\t// append query\n\tif len(req.Query) > 0 {\n\t\tif len(forwardURL.RawQuery) > 0 {\n\t\t\tforwardURL.RawQuery += \"&\" + req.Query\n\t\t} else {\n\t\t\tforwardURL.RawQuery = req.Query\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(req.Method, forwardURL.String(), strings.NewReader(req.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create forward request: %s\", err)\n\t}\n\n\t// copy headers\n\tfor header, vals := range req.Header {\n\t\tfor _, val := range vals {\n\t\t\tforwardReq.Header.Add(header, val)\n\t\t}\n\t}\n\t// headers cleanup\n\tforwardHeadersCleanup(forwardReq)\n\t// set do not forward header\n\tforwardReq.Header.Set(DoNotForwardHeader, \"1\")\n\n\t// forward request\n\tresponse, err := client.Do(forwardReq)\n\tif err != nil {\n\t\t// HTTP issue during forwarding - HTTP 502 Bad Gateway\n\t\tlog.Printf(\"[warn] failed to forward request for basket: %s - %s\", basket, err)\n\t\tbadGatewayResp := &http.Response{\n\t\t\tStatusCode: http.StatusBadGateway,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(fmt.Sprintf(\"Failed to forward request: %s\", err)))}\n\t\tbadGatewayResp.Header.Set(\"Content-Type\", \"text/plain\")\n\n\t\treturn badGatewayResp, nil\n\t}\n\n\treturn response, nil\n}", "func (sm *SoftMax) Forward() {\n\tmax := float32(-math.MaxFloat32)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tnet := float32(0)\n\t\toff := ui * sm.NInputs\n\t\tfor j, in := range sm.Inputs {\n\t\t\tnet += sm.Weights.Values[off+j] * in\n\t\t}\n\t\tu.Net = net\n\t\tif net > max {\n\t\t\tmax = net\n\t\t}\n\t}\n\tsum := float32(0)\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Net -= max\n\t\tu.Exp = mat32.FastExp(u.Net)\n\t\tsum += u.Exp\n\t}\n\tfor ui := range sm.Units {\n\t\tu := &sm.Units[ui]\n\t\tu.Act = u.Exp / sum\n\t}\n}", "func (o *OutboundDispatcher) Forward(msg interface{}, des *service.Destination) error {\n\tfor _, v := range o.outboundTransports {\n\t\tif !v.AcceptRecipient(des.RecipientKeys) {\n\t\t\tif !v.Accept(des.ServiceEndpoint) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\treq, err := json.Marshal(msg)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed marshal to bytes: %w\", err)\n\t\t}\n\n\t\t_, err = v.Send(req, des)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send msg using outbound transport: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"no outbound transport found for serviceEndpoint: %s\", des.ServiceEndpoint)\n}", "func (m *Model) StepForward(ns Nodes) (rv Nodes, err error) {\n\tstates := States{}\n\tvar tmp *Node\n\tfor _, x := range ns {\n\t\tif tmp, err = m.Forward(x, states); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trv = append(rv, tmp)\n\t}\n\treturn rv, nil\n}", "func (b *BaseController) Forward(title, templateName string) {\n\tb.Layout = filepath.Join(prefixNg, \"layout.htm\")\n\tb.TplName = filepath.Join(prefixNg, templateName)\n\tb.Data[\"Title\"] = b.Tr(title)\n\tb.LayoutSections = make(map[string]string)\n\tb.LayoutSections[\"HeaderInclude\"] = filepath.Join(prefixNg, viewPath, \"header-include.htm\")\n\n\tif b.UseCompressedJS {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-min-include.htm\")\n\t} else {\n\t\tb.LayoutSections[\"HeaderScriptInclude\"] = filepath.Join(prefixNg, viewPath, \"script-include.htm\")\n\t}\n\n\tlog.Debugf(\"Loaded HeaderScriptInclude file: %s\", b.LayoutSections[\"HeaderScriptInclude\"])\n\n\tb.LayoutSections[\"FooterInclude\"] = filepath.Join(prefixNg, viewPath, \"footer-include.htm\")\n\tb.LayoutSections[\"HeaderContent\"] = filepath.Join(prefixNg, viewPath, \"header-content.htm\")\n\tb.LayoutSections[\"FooterContent\"] = filepath.Join(prefixNg, viewPath, \"footer-content.htm\")\n\n}", "func (s SubTransaction) ForwardAction() Action {\n\treturn s.forward\n}", "func (l *AffineLayer) Forward(x mat.Matrix) mat.Matrix {\n\t_, c := x.Dims()\n\tif c != l.dimIn {\n\t\tpanic(fmt.Sprintf(\"expect %d but got %d\", l.dimIn, c))\n\t}\n\tl.x = x\n\tvar ret mat.Dense\n\tret.Mul(x, l.Weight)\n\tret.Apply(func(i, j int, val float64) float64 {\n\t\treturn l.Bias.At(j, 0) + val\n\t}, &ret)\n\treturn &ret\n}", "func (g *game) forward() {\n\tg.player.Parse(g.input)\n\n\tif g.player.IsQuitting() {\n\t\tg.next = g.newMenu()\n\t}\n}", "func (s *Server) Forward(id int64, event api.Event) {\n\tif event.Type == \"logging\" {\n\t\t// Parse the message\n\t\tlogEntry := api.EventLogging{}\n\t\terr := json.Unmarshal(event.Metadata, &logEntry)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && logEntry.Level == \"dbug\" {\n\t\t\treturn\n\t\t}\n\n\t\tif !s.debug && !s.verbose && logEntry.Level == \"info\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := s.broadcast(event, true)\n\tif err != nil {\n\t\tlogger.Warnf(\"Failed to forward event from member %d: %v\", id, err)\n\t}\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tif p.RequiresFullSeq() {\n\t\treturn p.fullSeqForward(xs)\n\t}\n\treturn p.incrementalForward(xs)\n}", "func (b *RequiredArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) ArgumentNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (a *createBucketIam) forward(app *App, args ...interface{}) error {\n\tenv, err := createBucket(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _ := config.GetString(\"host\")\n\tenvVars := []bind.EnvVar{\n\t\t{Name: \"APPNAME\", Value: app.Name},\n\t\t{Name: \"TSURU_HOST\", Value: host},\n\t}\n\tvariables := map[string]string{\n\t\t\"ENDPOINT\": env.endpoint,\n\t\t\"LOCATIONCONSTRAINT\": strconv.FormatBool(env.locationConstraint),\n\t\t\"ACCESS_KEY_ID\": env.AccessKey,\n\t\t\"SECRET_KEY\": env.SecretKey,\n\t\t\"BUCKET\": env.bucket,\n\t}\n\tfor name, value := range variables {\n\t\tenvVars = append(envVars, bind.EnvVar{\n\t\t\tName: fmt.Sprintf(\"TSURU_S3_%s\", name),\n\t\t\tValue: value,\n\t\t\tInstanceName: s3InstanceName,\n\t\t})\n\t}\n\tapp.SetEnvsToApp(envVars, false, true)\n\treturn nil\n}", "func (s *Service) Forward(topicID, msgID, targetAddr, text string) error {\n\tpayload := map[string]interface{}{\n\t\t\"id\": msgID,\n\t\t\"address\": targetAddr,\n\t\t\"text\": text,\n\t}\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpf, err := s.client.Publish(topicID, b, 2, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn pf.Wait(5 * time.Second)\n}", "func (c *chrono) Forward(skew time.Duration) {\n\tc.skew = skew\n}", "func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t// Ensure our request client does not follow redirects\n\thttpClient := http.Client{\n\t\tCheckRedirect: func(r *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\n\tif config.TLS != nil {\n\t\ttlsConfig, err := config.TLS.CreateTLSConfig()\n\t\tif err != nil {\n\t\t\ttracing.SetErrorAndDebugLog(r, \"Unable to configure TLS to call %s. Cause %s\", config.Address, err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\thttpClient.Transport = &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}\n\t}\n\n\tforwardReq, err := http.NewRequest(http.MethodGet, config.Address, http.NoBody)\n\ttracing.LogRequest(tracing.GetSpan(r), forwardReq)\n\tif err != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause %s\", config.Address, err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twriteHeader(r, forwardReq, config.TrustForwardHeader)\n\n\ttracing.InjectRequestHeaders(forwardReq)\n\n\tforwardResponse, forwardErr := httpClient.Do(forwardReq)\n\tif forwardErr != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error calling %s. Cause: %s\", config.Address, forwardErr)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbody, readError := ioutil.ReadAll(forwardResponse.Body)\n\tif readError != nil {\n\t\ttracing.SetErrorAndDebugLog(r, \"Error reading body %s. Cause: %s\", config.Address, readError)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer forwardResponse.Body.Close()\n\n\t// Pass the forward response's body and selected headers if it\n\t// didn't return a response within the range of [200, 300).\n\tif forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {\n\t\tlog.Debugf(\"Remote error %s. StatusCode: %d\", config.Address, forwardResponse.StatusCode)\n\n\t\tutils.CopyHeaders(w.Header(), forwardResponse.Header)\n\t\tutils.RemoveHeaders(w.Header(), forward.HopHeaders...)\n\n\t\t// Grab the location header, if any.\n\t\tredirectURL, err := forwardResponse.Location()\n\n\t\tif err != nil {\n\t\t\tif err != http.ErrNoLocation {\n\t\t\t\ttracing.SetErrorAndDebugLog(r, \"Error reading response location header %s. Cause: %s\", config.Address, err)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if redirectURL.String() != \"\" {\n\t\t\t// Set the location in our response if one was sent back.\n\t\t\tw.Header().Set(\"Location\", redirectURL.String())\n\t\t}\n\n\t\ttracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)\n\t\tw.WriteHeader(forwardResponse.StatusCode)\n\t\tw.Write(body)\n\t\treturn\n\t}\n\n\tfor _, headerName := range config.AuthResponseHeaders {\n\t\theaderKey := http.CanonicalHeaderKey(headerName)\n\t\tr.Header.Del(headerKey)\n\t\tif len(forwardResponse.Header[headerKey]) > 0 {\n\t\t\tr.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)\n\t\t}\n\t}\n\n\tr.RequestURI = r.URL.RequestURI()\n\tnext(w, r)\n}", "func (rh *RobertaLMHead) Forward(hiddenStates *ts.Tensor) *ts.Tensor {\n\tgelu := util.NewGelu()\n\tappliedDense := hiddenStates.Apply(rh.dense)\n\tgeluFwd := gelu.Fwd(appliedDense)\n\tappliedLN := geluFwd.Apply(rh.layerNorm)\n\tappliedDecoder := appliedLN.Apply(rh.decoder)\n\tappliedBias := appliedDecoder.MustAdd(rh.bias, true)\n\n\tgeluFwd.MustDrop()\n\tappliedDense.MustDrop()\n\tappliedLN.MustDrop()\n\n\treturn appliedBias\n}", "func (n *Network) Forward() {\n\tif !n.constructed() {\n\t\tlog.Panic(\"Cannot run an emtpy Network\")\n\t}\n\n\tfor l := range n.layers {\n\t\tcandy.Must(parallel.For(0, len(n.layers[l]), 1, func(g int) {\n\t\t\tgate := n.layers[l][g]\n\t\t\tgate.forward(gate)\n\t\t}))\n\t}\n}", "func (wh *WholeNet) FeedForward(t *t.Tensor) {\n\t(*wh).Layers[0].FeedForward(t)\n\tfor l := 1; l < len((*wh).Layers); l++ {\n\t\tout := (*wh).Layers[l-1].GetOutput()\n\t\t(*wh).Layers[l].FeedForward(&out)\n\t}\n}", "func (t *Tor) Forward(ctx context.Context, conf *ForwardConf) (*OnionForward, error) {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\t// Create the forward up here and make sure we close it no matter the error within\n\tfwd := &OnionForward{Tor: t}\n\tvar err error\n\n\t// Henceforth, any error requires we close the svc\n\n\t// Build the onion request\n\treq := &control.AddOnionRequest{MaxStreams: conf.MaxStreams, ClientAuths: conf.ClientAuths}\n\t// Set flags\n\tif conf.DiscardKey {\n\t\treq.Flags = append(req.Flags, \"DiscardPK\")\n\t}\n\tif conf.Detach {\n\t\treq.Flags = append(req.Flags, \"Detach\")\n\t}\n\tif len(conf.ClientAuths) > 0 {\n\t\treq.Flags = append(req.Flags, \"V3Auth\")\n\t}\n\tif conf.NonAnonymous {\n\t\treq.Flags = append(req.Flags, \"NonAnonymous\")\n\t}\n\tif conf.MaxStreamsCloseCircuit {\n\t\treq.Flags = append(req.Flags, \"MaxStreamsCloseCircuit\")\n\t}\n\t// Set the key\n\tswitch key := conf.Key.(type) {\n\tcase nil:\n\t\treq.Key = control.GenKey(control.KeyAlgoED25519V3)\n\tcase control.GenKey:\n\t\treq.Key = key\n\tcase ed25519.KeyPair:\n\t\tfwd.Key = key\n\t\treq.Key = &control.ED25519Key{key}\n\tcase othered25519.PrivateKey:\n\t\tproperKey := ed25519.FromCryptoPrivateKey(key)\n\t\tfwd.Key = properKey\n\t\treq.Key = &control.ED25519Key{properKey}\n\tcase *control.ED25519Key:\n\t\tfwd.Key = key.KeyPair\n\t\treq.Key = key\n\tdefault:\n\t\terr = fmt.Errorf(\"Unrecognized key type: %T\", key)\n\t}\n\n\t// Apply the remote ports\n\tfwd.PortForwards = conf.PortForwards\n\tfor localPort, remotePorts := range fwd.PortForwards {\n\t\tif len(remotePorts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, remotePort := range remotePorts {\n\t\t\treq.Ports = append(req.Ports, &control.KeyVal{\n\t\t\t\tKey: strconv.Itoa(remotePort),\n\t\t\t\tVal: localPort,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Create the onion service\n\tvar resp *control.AddOnionResponse\n\tif err == nil {\n\t\tresp, err = t.Control.AddOnion(req)\n\t}\n\n\t// Apply the response to the service\n\tif err == nil {\n\t\tfwd.ID = resp.ServiceID\n\t\tswitch key := resp.Key.(type) {\n\t\tcase nil:\n\t\t\t// Do nothing\n\t\tcase *control.ED25519Key:\n\t\t\tfwd.Key = key.KeyPair\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"Unrecognized result key type: %T\", key)\n\t\t}\n\t}\n\n\t// Wait if necessary\n\tif err == nil && !conf.NoWait {\n\t\tt.Debugf(\"Enabling network before waiting for publication\")\n\t\t// First make sure network is enabled\n\t\tif err = t.EnableNetwork(ctx, true); err == nil {\n\t\t\tt.Debugf(\"Waiting for publication\")\n\t\t\t// Now we'll take a similar approach to Stem. Several UPLOADs are sent out, so we count em. If we see\n\t\t\t// UPLOADED, we succeeded. If we see failed, we count those. If there are as many failures as uploads, they\n\t\t\t// all failed and it's a failure. NOTE: unlike Stem's comments that say they don't, we are actually seeing\n\t\t\t// the service IDs for UPLOADED so we don't keep a map.\n\t\t\tuploadsAttempted := 0\n\t\t\tfailures := []string{}\n\t\t\t_, err = t.Control.EventWait(ctx, []control.EventCode{control.EventCodeHSDesc},\n\t\t\t\tfunc(evt control.Event) (bool, error) {\n\t\t\t\t\ths, _ := evt.(*control.HSDescEvent)\n\t\t\t\t\tif hs != nil && hs.Address == fwd.ID {\n\t\t\t\t\t\tswitch hs.Action {\n\t\t\t\t\t\tcase \"UPLOAD\":\n\t\t\t\t\t\t\tuploadsAttempted++\n\t\t\t\t\t\tcase \"FAILED\":\n\t\t\t\t\t\t\tfailures = append(failures,\n\t\t\t\t\t\t\t\tfmt.Sprintf(\"Failed uploading to dir %v - reason: %v\", hs.HSDir, hs.Reason))\n\t\t\t\t\t\t\tif len(failures) == uploadsAttempted {\n\t\t\t\t\t\t\t\treturn false, fmt.Errorf(\"Failed all uploads, reasons: %v\", failures)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"UPLOADED\":\n\t\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn false, nil\n\t\t\t\t})\n\t\t}\n\t}\n\n\t// Give back err and close if there is an err\n\tif err != nil {\n\t\tif closeErr := fwd.Close(); closeErr != nil {\n\t\t\terr = fmt.Errorf(\"Error on listen: %v (also got error trying to close: %v)\", err, closeErr)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn fwd, nil\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (m *Model) Forward(xs ...ag.Node) []ag.Node {\n\tys := make([]ag.Node, len(xs))\n\tfor i, x := range xs {\n\t\ts := m.forward(x)\n\t\tm.States = append(m.States, s)\n\t\tys[i] = s.Y\n\t}\n\treturn ys\n}", "func (c *ManetConnection) forward(bytes []byte) {\n\tincomingHeader := data.PacketHeaderFromBytes(bytes)\n\n\tcached := c.inCache(incomingHeader.SequenceNumber, incomingHeader.SendKey)\n\tfmt.Println(\"CACHE: \", incomingHeader.SequenceNumber, incomingHeader.SendKey, cached)\n\n\tif cached || incomingHeader.TTL <= 1 {\n\t\tfmt.Println(\"DROP!\")\n\t\treturn\n\t}\n\n\tc.cache[incomingHeader.SequenceNumber] = incomingHeader.SendKey\n\tdelete(c.cache, incomingHeader.SequenceNumber-cacheDepth)\n\n\toutgoingHeader := &data.PacketHeader{\n\t\tSourceAddress: incomingHeader.SourceAddress,\n\t\tDestinationAddress: incomingHeader.DestinationAddress,\n\t\tPreviousHop: GetMyAddress(),\n\t\tTTL: incomingHeader.TTL - 1,\n\t\tPacketType: incomingHeader.PacketType,\n\t\tSequenceNumber: incomingHeader.SequenceNumber,\n\t\tNumBytes: incomingHeader.NumBytes,\n\t\tSendKey: incomingHeader.SendKey,\n\t}\n\n\tfor i, b := range outgoingHeader.ToBytes() {\n\t\tbytes[i] = b\n\t}\n\n\tfor neighbor := range myNeighbors {\n\t\tif neighbor == incomingHeader.PreviousHop {\n\t\t\tcontinue\n\t\t}\n\t\traddr := ToUDPAddr(neighbor)\n\t\tfmt.Println(\"FORWARD to\", neighbor, \"DEST: \", incomingHeader.DestinationAddress, \"aka\", raddr)\n\t\tif _, err := c.conn.WriteToUDP(bytes, raddr); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func (ms *MVCCStats) Forward(nowNanos int64) {\n\tif ms.LastUpdateNanos >= nowNanos {\n\t\treturn\n\t}\n\tms.AgeTo(nowNanos)\n}", "func (m *ItemMailFoldersItemMessagesMessageItemRequestBuilder) Forward()(*ItemMailFoldersItemMessagesItemForwardRequestBuilder) {\n return NewItemMailFoldersItemMessagesItemForwardRequestBuilderInternal(m.BaseRequestBuilder.PathParameters, m.BaseRequestBuilder.RequestAdapter)\n}", "func (mlm *RobertaForMaskedLM) Forward(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, allHiddenStates, allAttentions, err := mlm.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, encoderHiddenStates, encoderMask, train)\n\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tpredictionScores := mlm.lmHead.Forward(hiddenState)\n\n\treturn predictionScores, allHiddenStates, allAttentions, nil\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tys := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tys[i] = m.forward(x)\n\t}\n\treturn ys\n}", "func (tr *Peer) FastForward(ctx context.Context, target string,\n\treq *FastForwardRequest, resp *FastForwardResponse) error {\n\n\tif tr.isShutdown() {\n\t\treturn ErrTransportStopped\n\t}\n\n\ttr.wg.Add(1)\n\tdefer tr.wg.Done()\n\n\treturn tr.fastForward(ctx, target, req, resp)\n}", "func (fl *follow) forward(r io.Reader) (cont bool) {\n\tfl.Decoder.Reset(r)\n\treturn fl.Forwarder.Do(fl.Watcher, fl.Decoder)\n}", "func (m *Linear) Forward(x mat.Tensor) mat.Tensor {\n\treturn ag.Add(ag.Mul(m.W, x), m.B)\n}", "func (lay *Layer) Forward(x *mat.Dense) (a *mat.Dense) {\n\t// x is (n x in )\n\trow, _ := x.Dims()\n\n\txx := new(mat.Dense)\n\txx.Augment(x, NewConstantMat(row, 1, 1.0)) // ( n x in+1 )\n\tz := new(mat.Dense)\n\tz.Mul(xx, lay.w) // (n x in + 1 ).(in +1 x out) = (n x out)\n\n\tz.Apply(func(i, j int, v float64) float64 { return lay.act.f(v) }, z)\n\treturn z\n}", "func (r *Lachesis) FastForward(\n\treq *net.FastForwardRequest, resp *net.FastForwardResponse) error {\n\tresult, err := r.process(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titem, ok := result.(*net.FastForwardResponse)\n\tif !ok {\n\t\treturn ErrBadResult\n\t}\n\t*resp = *item\n\treturn nil\n}", "func (ch *RobertaClassificationHead) ForwardT(hiddenStates *ts.Tensor, train bool) *ts.Tensor {\n\tappliedDO1 := hiddenStates.MustSelect(1, 0, false).ApplyT(ch.dropout, train)\n\tappliedDense := appliedDO1.Apply(ch.dense)\n\ttanhTs := appliedDense.MustTanh(false)\n\tappliedDO2 := tanhTs.ApplyT(ch.dropout, train)\n\tretVal := appliedDO2.Apply(ch.outProj)\n\n\tappliedDO1.MustDrop()\n\tappliedDense.MustDrop()\n\ttanhTs.MustDrop()\n\tappliedDO2.MustDrop()\n\n\treturn retVal\n}", "func (m *Model) Forward(xs ...mat.Tensor) []mat.Tensor {\n\tif len(xs) == 0 {\n\t\treturn nil\n\t}\n\tout := make([]mat.Tensor, len(xs))\n\tfor i, x := range xs {\n\t\tmean := ag.ReduceMean(x)\n\t\tdev := ag.SubScalar(x, mean)\n\t\tstdDev := ag.Sqrt(ag.Add(ag.ReduceMean(ag.Square(dev)), m.Eps))\n\t\tout[i] = ag.Add(ag.Prod(ag.DivScalar(dev, stdDev), m.W), m.B)\n\t}\n\treturn out\n}", "func (n Neuron) FeedForward(previous_layer Layer) {\n sum := 0.0\n\n // Sum outputs from the previous layer.\n for _, neuron := range previous_layer {\n // TODO: there may be duplication issues here\n sum += neuron.output * neuron.output_weights[n.index].weight\n }\n\n n.output = n.Activation(sum)\n}", "func (ti *TimeIndex) iterForward(t time.Time) index.Iter {\n i := ti.IndexNear(t)\n return &forwardIter{\n at: i,\n ti: ti,\n }\n}", "func (v *SourceSearchContext) Forward(iter *gtk.TextIter) (*gtk.TextIter, *gtk.TextIter, bool, bool) {\n\n\tstart, end := new(gtk.TextIter), new(gtk.TextIter)\n\tvar hasWrappedAround C.gboolean\n\n\tc := C.gtk_source_search_context_forward(\n\t\tv.native(),\n\t\tnativeTextIter(iter),\n\t\tnativeTextIter(start),\n\t\tnativeTextIter(end),\n\t\t&hasWrappedAround)\n\n\treturn start, end, gobool(hasWrappedAround), gobool(c)\n}", "func (r *RotateModule) Forward(x *ts.Tensor) *ts.Tensor {\n\tfx := Byte2FloatImage(x)\n\n\tout, err := Rotate(fx, r.angle)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbx := Float2ByteImage(out)\n\tfx.MustDrop()\n\tout.MustDrop()\n\n\treturn bx\n}", "func Forward(in, out Link) rules.Rule {\n\treturn rules.Rule(fmt.Sprintf(\n\t\t\"-t filter -A fw-interfaces -j ACCEPT -i %v -o %v\",\n\t\tin.Name(), out.Name()))\n}", "func (la *Lattice) Forward(m TokenizeMode) {\n\tfor i, size := 1, len(la.list); i < size; i++ {\n\t\tcurrentList := la.list[i]\n\t\tfor index, target := range currentList {\n\t\t\tprevList := la.list[target.Start]\n\t\t\tif len(prevList) == 0 {\n\t\t\t\tla.list[i][index].Cost = maximumCost\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor j, n := range prevList {\n\t\t\t\tvar c int16\n\t\t\t\tif n.Class != USER && target.Class != USER {\n\t\t\t\t\tc = la.dic.Connection.At(int(n.Right), int(target.Left))\n\t\t\t\t}\n\t\t\t\ttotalCost := int64(c) + int64(target.Weight) + int64(n.Cost)\n\t\t\t\tif m != Normal {\n\t\t\t\t\ttotalCost += int64(additionalCost(n))\n\t\t\t\t}\n\t\t\t\tif totalCost > maximumCost {\n\t\t\t\t\ttotalCost = maximumCost\n\t\t\t\t}\n\t\t\t\tif j == 0 || int32(totalCost) < la.list[i][index].Cost {\n\t\t\t\t\tla.list[i][index].Cost = int32(totalCost)\n\t\t\t\t\tla.list[i][index].prev = la.list[target.Start][j]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (r *LeakyReLU[O]) Forward() (mat.Tensor, error) {\n\treturn r.x.Value().(mat.Matrix).ApplyWithAlpha(leakyReLU, r.alpha.Value().Item().F64()), nil\n}", "func (f *Forward) Forward(state request.Request) (*dns.Msg, error) {\n\tif f == nil {\n\t\treturn nil, ErrNoForward\n\t}\n\n\tfails := 0\n\tvar upstreamErr error\n\tfor _, proxy := range f.List() {\n\t\tif proxy.Down(f.maxfails) {\n\t\t\tfails++\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// All upstream proxies are dead, assume healtcheck is complete broken and randomly\n\t\t\t// select an upstream to connect to.\n\t\t\tproxy = f.List()[0]\n\t\t}\n\n\t\tret, err := proxy.Connect(context.Background(), state, f.opts)\n\n\t\tret, err = truncated(state, ret, err)\n\t\tupstreamErr = err\n\n\t\tif err != nil {\n\t\t\tif fails < len(f.proxies) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Check if the reply is correct; if not return FormErr.\n\t\tif !state.Match(ret) {\n\t\t\treturn state.ErrorMessage(dns.RcodeFormatError), nil\n\t\t}\n\n\t\treturn ret, err\n\t}\n\n\tif upstreamErr != nil {\n\t\treturn nil, upstreamErr\n\t}\n\n\treturn nil, ErrNoHealthy\n}", "func (p *CloudAuditLogsSourceProbe) Forward(ctx context.Context, event cloudevents.Event) error {\n\t// Create the receiver channel\n\tchannelID := channelID(fmt.Sprint(event.Extensions()[utils.ProbeEventTargetPathExtension]), event.ID())\n\tcleanupFunc, err := p.receivedEvents.CreateReceiverChannel(channelID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create receiver channel: %v\", err)\n\t}\n\tdefer cleanupFunc()\n\n\t// The probe creates a Pub/Sub topic.\n\ttopic := event.ID()\n\tlogging.FromContext(ctx).Infow(\"Creating pubsub topic\", zap.String(\"topic\", topic))\n\tif _, err := p.pubsubClient.CreateTopic(ctx, topic); err != nil {\n\t\treturn fmt.Errorf(\"Failed to create pubsub topic '%s': %v\", topic, err)\n\t}\n\n\treturn p.receivedEvents.WaitOnReceiverChannel(ctx, channelID)\n}", "func forwardRequest(originatorAddr *net.UDPAddr, msgID []byte, reqPay pb.KVRequest, rawMsg []byte, toNode Node) {\n\tif self.Addr.String() == toNode.Addr.String() {\n\t\tfmt.Println(\"Stop. Can't forward to self - \", toNode.Addr.String())\n\t\treturn\n\t}\n\n\tsendRequestToNode(msgID, reqPay, &toNode)\n}", "func (c *MiningClient) Forwarder() {\n\tfLog := log.WithField(\"func\", \"MiningClient.Forwarder()\")\n\tfor {\n\t\tselect {\n\t\tcase ent := <-c.entryChannel:\n\t\t\terr := c.encoder.Encode(NewNetworkMessage(FactomEntry, GobbedEntry{\n\t\t\t\tExtIDs: ent.ExtIDs,\n\t\t\t\tChainID: ent.ChainID,\n\t\t\t\tContent: ent.Content,\n\t\t\t}))\n\t\t\tif err != nil {\n\t\t\t\tfLog.WithField(\"evt\", \"entry\").WithError(err).Error(\"failed to send entry\")\n\t\t\t} else {\n\t\t\t\tfLog.WithField(\"evt\", \"entry\").WithField(\"entry\", fmt.Sprintf(\"%x\", ent.Hash())).Debugf(\"sent entry\")\n\t\t\t}\n\t\tcase s := <-c.UpstreamStats:\n\t\t\terr := c.encoder.Encode(NewNetworkMessage(MiningStatistics, *s))\n\t\t\tif err != nil {\n\t\t\t\tfLog.WithField(\"evt\", \"entry\").WithError(err).Error(\"failed to send stats\")\n\t\t\t} else {\n\t\t\t\tfLog.WithField(\"evt\", \"entry\").Debugf(\"sent entry\")\n\t\t\t}\n\t\t}\n\t}\n}", "func forwardBox(ctx *Context, t *Tuple, w Writer) error {\n\tw.Write(ctx, t)\n\treturn nil\n}", "func (b *Brain) Forward(inputArray []float64) int {\r\n\tb.ForwardPasses++\r\n\tb.LastInputArray = inputArray // back this up\r\n\r\n\t// create network input\r\n\tvar (\r\n\t\tnetInput []float64\r\n\t\taction int\r\n\t)\r\n\tif b.ForwardPasses > b.TemporalWindow {\r\n\t\t// we have enough to actually do something reasonable\r\n\t\tnetInput = b.NetInput(inputArray)\r\n\r\n\t\tif b.Learning {\r\n\t\t\t// compute epsilon for the epsilon-greedy policy\r\n\t\t\tb.Epsilon = math.Min(1.0, math.Max(b.EpsilonMin, 1.0-float64(b.Age-b.LearningStepsBurnin)/float64(b.LearningStepsTotal-b.LearningStepsBurnin)))\r\n\t\t} else {\r\n\t\t\tb.Epsilon = b.EpsilonTestTime // use test-time value\r\n\t\t}\r\n\r\n\t\trf := b.Rand.Float64()\r\n\t\tif rf < b.Epsilon {\r\n\t\t\t// choose a random action with epsilon probability\r\n\t\t\taction = b.RandomAction()\r\n\t\t} else {\r\n\t\t\t// otherwise use our policy to make decision\r\n\t\t\taction, _ = b.Policy(netInput)\r\n\t\t}\r\n\t} else {\r\n\t\t// pathological case that happens first few iterations\r\n\t\t// before we accumulate window_size inputs\r\n\t\tnetInput = nil\r\n\t\taction = b.RandomAction()\r\n\t}\r\n\r\n\t// remember the state and action we took for backward pass\r\n\tcopy(b.NetWindow, b.NetWindow[1:])\r\n\tb.NetWindow[len(b.NetWindow)-1] = netInput\r\n\tcopy(b.StateWindow, b.StateWindow[1:])\r\n\tb.StateWindow[len(b.StateWindow)-1] = inputArray\r\n\tcopy(b.ActionWindow, b.ActionWindow[1:])\r\n\tb.ActionWindow[len(b.ActionWindow)-1] = action\r\n\r\n\treturn action\r\n}", "func Forward(ctx context.Context, destination chan<- packet.Buf, source <-chan packet.Buf) {\n\tdefer contextack.Ack(ctx, ForwardDoneAck)\n\n\tvar p packet.Buf\n\n\tfor {\n\t\tvar (\n\t\t\tinput <-chan packet.Buf\n\t\t\toutput chan<- packet.Buf\n\t\t\tok bool\n\t\t)\n\n\t\tif p == nil {\n\t\t\tinput = source\n\t\t} else {\n\t\t\toutput = destination\n\t\t}\n\n\t\tselect {\n\t\tcase p, ok = <-input:\n\t\t\tif !ok {\n\t\t\t\t// EOF\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase output <- p:\n\t\t\t// ok\n\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (device *SilentStepperBrick) DriveForward() (err error) {\n\tvar buf bytes.Buffer\n\n\tresultBytes, err := device.device.Set(uint8(FunctionDriveForward), buf.Bytes())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resultBytes) > 0 {\n\t\tvar header PacketHeader\n\n\t\theader.FillFromBytes(resultBytes)\n\n\t\tif header.Length != 8 {\n\t\t\treturn fmt.Errorf(\"Received packet of unexpected size %d, instead of %d\", header.Length, 8)\n\t\t}\n\n\t\tif header.ErrorCode != 0 {\n\t\t\treturn DeviceError(header.ErrorCode)\n\t\t}\n\n\t\tbytes.NewBuffer(resultBytes[8:])\n\n\t}\n\n\treturn nil\n}", "func Forward() {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\terr := recover() // Have to do recover directly in deferred function\n\tinternalPanicHandler.forward(err)\n}", "func (p *Player) Forward() mgl32.Vec3 {\n\treturn p.Speed\n}", "func (f *Forwarder) ForwardRequest(request []byte, destination, service, endpoint string,\n\tkeys []string, format tchannel.Format, opts *Options) ([]byte, error) {\n\n\tf.EmitEvent(RequestForwardedEvent{})\n\n\tf.incrementInflight()\n\topts = f.mergeDefaultOptions(opts)\n\trs := newRequestSender(f.sender, f, f.channel, request, keys, destination, service, endpoint, format, opts)\n\tb, err := rs.Send()\n\tf.decrementInflight()\n\n\tif err != nil {\n\t\tf.EmitEvent(FailedEvent{})\n\t} else {\n\t\tf.EmitEvent(SuccessEvent{})\n\t}\n\n\treturn b, err\n}", "func (r *Redirect) Forward(conn net.Conn) {\n\tif conn == nil {\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tvar (\n\t\trequest = []byte{}\n\t\trequestTmp = make([]byte, 1024)\n\t)\n\n\tfor {\n\t\tn, err := conn.Read(requestTmp)\n\t\tif err != nil {\n\t\t\tr.reply(conn, nil, \"\", err)\n\t\t\treturn\n\t\t}\n\t\trequest = append(request, requestTmp[:n]...)\n\t\tif n < 1024 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(request)))\n\n\tif err != nil {\n\t\tr.reply(conn, nil, \"\", err)\n\t\treturn\n\t}\n\n\tu, err := url.Parse(string(req.RequestURI[1:]))\n\tif err != nil {\n\t\tr.reply(conn, req, \"\", err)\n\t\treturn\n\t}\n\treq.URL = u\n\treq.Host = u.Host\n\n\treq.RequestURI = \"\"\n\trequestObj := r.requestPool.Get().(*RequestWrapper)\n\trequestObj.CreatedTime = time.Now()\n\trequestObj.request = req\n\trequestObj.TryCount = 0\n\trequestObj.ID = r.makeID()\n\n\tif !r.putTask(requestObj, false) {\n\t\tr.reply(conn, req, \"\", errors.New(\"request put into buffer timeout\"))\n\t\treturn\n\t}\n\n\tr.reply(conn, req, requestObj.ID, nil)\n}", "func Forward(b Branch, distance float64) Branch {\n\tvar b_new Branch\n\tb_new.phase = b.phase\n\tb_new.xy = b.xy + cmplx.Rect(distance, b.phase)\n\treturn b_new\n}", "func forward(statusch <-chan engine.SearchStatus, responsech chan<- uci.Response) {\n\tfor info := range statusch {\n\t\tresponsech <- uci.ResponseSearchInformation{Depth: info.Depth}\n\t}\n}", "func processForward(forward *chproto.ChangeForward) {\n\n\t// If we are already trying to forward a change forward message with\n\t// the same requesting node and request ID, discard this message.\n\tif _, exists := getForwardTimeout(uint16(*forward.Request.RequestNode),\n\t\t*forward.Request.RequestId); exists {\n\t\treturn\n\t}\n\n\t// Everything else in this function runs in a transaction.\n\t// We are read-only.\n\tstore.StartTransaction()\n\tdefer store.EndTransaction()\n\n\t// If this is a core node and this node stopped being leader less than\n\t// a Change Timeout Period ago, always add us to the ignore list.\n\tif config.IsCore() && !isIgnored(forward, config.Id()) {\n\t\tdiff := time.Now().Sub(store.StoppedLeading())\n\t\tif diff < config.CHANGE_TIMEOUT_PERIOD {\n\t\t\tforward.Ignores = append(forward.Ignores,\n\t\t\t\tuint32(config.Id()))\n\t\t}\n\t}\n\n\t// If all core node IDs are in the forward's ignore list, discard it.\n\tif len(forward.Ignores) == len(config.CoreNodes()) {\n\t\tlog.Print(\"shared/chrequest: dropped msg due to full ignores\")\n\t\treturn\n\t}\n\n\t// Otherwise, choose a potential leader node.\n\t// This is O(n^2) in the number of core nodes,\n\t// but we don't expect to have many.\n\tchosenNode := uint16(0)\n\t_, leader := store.Proposal()\n\tif leader != 0 && !isIgnored(forward, leader) {\n\t\tchosenNode = leader\n\t} else {\n\t\tfor _, node := range config.CoreNodes() {\n\t\t\tif !isIgnored(forward, node) {\n\t\t\t\tchosenNode = node\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif chosenNode == 0 {\n\t\t// Shouldn't happen.\n\t\tlog.Print(\"shared/chrequest: bug, \" +\n\t\t\t\"couldn't find candidate leader node\")\n\t\treturn\n\t}\n\n\t// If we are the selected leader, construct an external change request,\n\t// and send it on our change request channel.\n\tif chosenNode == config.Id() {\n\t\tintRequest := forward.Request\n\t\tchrequest := new(store.ChangeRequest)\n\t\tchrequest.RequestEntity = *intRequest.RequestEntity\n\t\tchrequest.RequestNode = uint16(*intRequest.RequestNode)\n\t\tchrequest.RequestId = *intRequest.RequestId\n\t\tchrequest.Changeset = make([]store.Change,\n\t\t\tlen(intRequest.Changeset))\n\n\t\tfor i, ch := range intRequest.Changeset {\n\t\t\tchrequest.Changeset[i].TargetEntity = *ch.TargetEntity\n\t\t\tchrequest.Changeset[i].Key = *ch.Key\n\t\t\tchrequest.Changeset[i].Value = *ch.Value\n\t\t}\n\n\t\tfor _, cb := range changeCallbacks {\n\t\t\tcb(chrequest)\n\t\t}\n\n\t\treturn\n\t}\n\n\t// Otherwise, we send it on to the selected leader,\n\t// add the selected leader to the ignore list,\n\t// and set a timeout to retry.\n\tsendForward(chosenNode, forward)\n\tforward.Ignores = append(forward.Ignores, uint32(chosenNode))\n\taddForwardTimeout(forward)\n}", "func (fbo *folderBranchOps) ForceFastForward(ctx context.Context) {\n\tlState := makeFBOLockState()\n\tfbo.headLock.RLock(lState)\n\tdefer fbo.headLock.RUnlock(lState)\n\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t// We're already up to date.\n\t\treturn\n\t}\n\tif !fbo.hasBeenCleared {\n\t\t// No reason to fast-forward here if it hasn't ever been\n\t\t// cleared.\n\t\treturn\n\t}\n\n\tfbo.forcedFastForwards.Add(1)\n\tfbo.goTracked(func() {\n\t\tdefer fbo.forcedFastForwards.Done()\n\t\tctx, cancelFunc := fbo.newCtxWithFBOID()\n\t\tdefer cancelFunc()\n\n\t\tfbo.log.CDebugf(ctx, \"Forcing a fast-forward\")\n\t\tvar currHead ImmutableRootMetadata\n\t\tvar err error\n\tgetMD:\n\t\tfor i := 0; ; i++ {\n\t\t\tcurrHead, err = fbo.config.MDOps().GetForTLF(ctx, fbo.id(), nil)\n\t\t\tswitch errors.Cause(err).(type) {\n\t\t\tcase nil:\n\t\t\t\tbreak getMD\n\t\t\tcase kbfsmd.ServerErrorUnauthorized:\n\t\t\t\t// The MD server connection might not be authorized\n\t\t\t\t// yet, so give it a few chances to go through.\n\t\t\t\tif i > 5 {\n\t\t\t\t\tfbo.log.CDebugf(ctx,\n\t\t\t\t\t\t\"Still unauthorized for TLF %s; giving up fast-forward\",\n\t\t\t\t\t\tfbo.id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif i == 0 {\n\t\t\t\t\tfbo.log.CDebugf(\n\t\t\t\t\t\tctx, \"Got unauthorized error when fast-forwarding %s; \"+\n\t\t\t\t\t\t\t\"trying again after a delay\", fbo.id())\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tdefault:\n\t\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %+v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif currHead == (ImmutableRootMetadata{}) {\n\t\t\tfbo.log.CDebugf(ctx, \"No MD yet\")\n\t\t\treturn\n\t\t}\n\t\tfbo.log.CDebugf(ctx, \"Current head is revision %d\", currHead.Revision())\n\n\t\tlState := makeFBOLockState()\n\t\t// Kick off partial prefetching once the latest merged\n\t\t// revision is set.\n\t\tdefer func() {\n\t\t\tif err == nil {\n\t\t\t\tfbo.kickOffPartialSyncIfNeeded(ctx, lState, currHead)\n\t\t\t}\n\t\t}()\n\n\t\tfbo.mdWriterLock.Lock(lState)\n\t\tdefer fbo.mdWriterLock.Unlock(lState)\n\t\tfbo.headLock.Lock(lState)\n\t\tdefer fbo.headLock.Unlock(lState)\n\n\t\tif !fbo.hasBeenCleared {\n\t\t\treturn\n\t\t}\n\n\t\tdefer func() {\n\t\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t\tfbo.hasBeenCleared = false\n\t\t\t}\n\t\t}()\n\n\t\tif fbo.head != (ImmutableRootMetadata{}) {\n\t\t\t// We're already up to date.\n\t\t\tfbo.log.CDebugf(ctx, \"Already up-to-date: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\terr = fbo.doFastForwardLocked(ctx, lState, currHead)\n\t\tif err != nil {\n\t\t\tfbo.log.CDebugf(ctx, \"Fast-forward failed: %v\", err)\n\t\t}\n\t})\n}", "func (n *Node) Forward() FloatXX {\n\tif n.myoutCached {\n\t\treturn n.myout\n\t}\n\n\tif n.myType == InputNode {\n\t\tn.myout = n.inputValue\n\t} else {\n\t\tn.myout = FloatXX(0.0)\n\t\tfor index, otherNode := range n.inputNodes {\n\t\t\toutput := otherNode.Forward()\n\t\t\tn.inputs = append(n.inputs, output)\n\t\t\tn.myout += n.weights[index] * output\n\t\t}\n\t\tn.myout += n.biasValue * n.biasWeight\n\t\tmyoutActivated := n.activation(n.myout)\n\t\tn.myout = myoutActivated\n\t}\n\n\tn.myoutCached = true\n\treturn n.myout\n}", "func (t *TimeLine) forward(num, denom uint32, runCallbacks bool) {\n\tend := t.cursor + t.Ticks(num, denom)\n\tif runCallbacks {\n\t\tt.lastDelta = t.runCallbacks(t.cursor, end)\n\t}\n\tt.cursor = end\n}", "func (sc *RobertaForSequenceClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (labels *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\n\thiddenState, _, hiddenStates, attentions, err := sc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tlabels = sc.classifier.ForwardT(hiddenState, train)\n\thiddenState.MustDrop()\n\n\treturn labels, hiddenStates, attentions, nil\n}", "func (b *MessagesSendBuilder) ForwardMessages(v []int) *MessagesSendBuilder {\n\tb.Params[\"forward_messages\"] = v\n\treturn b\n}", "func (m *Model) ForwardWithPastKeysValues(qkv attention.QKV, past attention.KeysValuesPair) attention.Output {\n\tprojAtt := attention.QKV{\n\t\tQueries: m.Query.Forward(qkv.Queries...),\n\t\tKeys: append([]ag.Node{}, past.Keys...), // this append is important\n\t\tValues: append([]ag.Node{}, past.Values...), // this append is important\n\t}\n\n\tif qkv.Keys != nil { // the qkv.Values shall not be null as well\n\t\tprojAtt.Keys = append(projAtt.Keys, m.Key.Forward(qkv.Keys...)...)\n\t\tprojAtt.Values = append(projAtt.Values, m.Value.Forward(qkv.Values...)...)\n\t}\n\n\tattOutput, attWeights := attention.ScaledDotProductAttention(m.Graph(), projAtt, m.ScaleFactor, m.UseCausalMask)\n\n\treturn attention.Output{\n\t\tAttOutput: attOutput,\n\t\tAttWeights: attWeights,\n\t\tProjKeysValues: attention.KeysValuesPair{\n\t\t\tKeys: projAtt.Keys,\n\t\t\tValues: projAtt.Values,\n\t\t},\n\t}\n}", "func (rbm *RBM) Forward(v []float64) []float64 {\n\thidden := make([]float64, rbm.NumHiddenUnits)\n\tfor i := 0; i < rbm.NumHiddenUnits; i++ {\n\t\thidden[i] = rbm.P_H_Given_V(i, v)\n\t}\n\treturn hidden\n}", "func (p *Processor) Forward(xs ...ag.Node) []ag.Node {\n\tlength := len(xs)\n\tqs := p.query.Forward(xs...)\n\tks := make([]ag.Node, length)\n\tvs := p.value.Forward(xs...)\n\tmapk := make(map[int]*IndexedNodes)\n\tmapv := make(map[int]*IndexedNodes)\n\n\t// TODO: can it be implemented in a concurrent fashion?\n\tfor i, q := range qs {\n\t\tnorm := p.Graph.Sqrt(p.Graph.ReduceSum(p.Graph.Pow(q, 2.0)))\n\t\tks[i] = p.Graph.DivScalar(q, norm) // Euclidean norm\n\t\th := p.getHash(ks[i].Value().(*mat.Dense))\n\t\tinsertNode(mapk, ks[i], i, h)\n\t\tinsertNode(mapv, vs[i], i, h)\n\t}\n\n\tcontext := make([]ag.Node, length)\n\tprob := make([]mat.Matrix, length)\n\tfor i, q := range qs {\n\t\tj := p.getHash(q.Value().(*mat.Dense))\n\t\tc, p := p.lshScaledDotProductAttention(p.Graph, q, mapk[j], mapv[j], length, p.scaleFactor)\n\t\tcontext[i], prob[i] = c, p\n\t}\n\n\tp.Attention = &ContextProb{\n\t\tcontext: context,\n\t\tprob: prob,\n\t}\n\treturn context\n}", "func (a *createRepository) forward(app *App, args ...interface{}) error {\n\tgUrl := repository.GitServerUri()\n\tvar users []string\n\tfor _, t := range app.GetTeams() {\n\t\tusers = append(users, t.Users...)\n\t}\n\tc := gandalf.Client{Endpoint: gUrl}\n\t_, err := c.NewRepository(app.Name, users, false)\n\treturn err\n}", "func (b *LiteralArgumentBuilder) Forward(target CommandNode, modifier RedirectModifier, fork bool) LiteralNodeBuilder {\n\tb.ArgumentBuilder.Forward(target, modifier, fork)\n\treturn b\n}", "func (q Quat) Forward() Vec3f {\n\treturn q.RotateVec(Vec3f{0, 0, -1})\n}", "func (matrix Matrix4) Forward() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[2][0],\n\t\tmatrix[2][1],\n\t\tmatrix[2][2],\n\t}.Unit()\n}", "func forwardRequest(client *http.Client, request *utils.ForwardedRequest) error {\n\thttpRequest := request.Contents\n\tif *forwardUserID {\n\t\thttpRequest.Header.Add(utils.HeaderUserID, request.User)\n\t}\n\treverseProxy := httputil.NewSingleHostReverseProxy(&url.URL{\n\t\tScheme: \"http\",\n\t\tHost: *host,\n\t})\n\treverseProxy.FlushInterval = 100 * time.Millisecond\n\tresponseForwarder, err := utils.NewResponseForwarder(client, *proxy, request.BackendID, request.RequestID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treverseProxy.ServeHTTP(responseForwarder, httpRequest)\n\tif *debug {\n\t\tlog.Printf(\"Backend latency for request %s: %s\\n\", request.RequestID, time.Since(request.StartTime).String())\n\t}\n\treturn responseForwarder.Close()\n}", "func (s *Service) forwardToLeader(w http.ResponseWriter, req *http.Request) {\n\turl, err := url.Parse(s.RaftConfig.RaftNodeConfig.NodeProtocol + req.RequestURI)\n\tif err != nil {\n\t\tpanic(\"parse leader host url failed: \" + err.Error())\n\t}\n\turl.Host = s.raftNode.GetLeaderHost()\n\n\t// without leader, then return special error\n\tif url.Host == \"\" {\n\t\trpc.ReplyErr(w, apierrors.CodeNoLeader, apierrors.ErrNoLeader.Error())\n\t\treturn\n\t}\n\n\tlog.Infof(\"forward url: %v\", url)\n\n\tproxy := httpproxy.ReverseProxy{\n\t\tDirector: func(request *http.Request) {\n\t\t\trequest.URL = url\n\t\t},\n\t}\n\n\tproxy.ServeHTTP(w, req)\n}", "func (r *Threshold[O]) Forward() (mat.Tensor, error) {\n\ty := r.x.Value().(mat.Matrix).ApplyWithAlpha(\n\t\tthreshold,\n\t\tr.threshold.Value().Item().F64(),\n\t\tr.k.Value().Item().F64(),\n\t)\n\treturn y, nil\n}", "func (p *SignalChannel) forward(req Request, customer *models.Customer) (res Response, err error) {\n\tlog.Debug(\"[forward] SignalChannel\")\t\n\tlog.Debugf(\"req.Uri=%+v, req.Type=%+v\", req.Uri, req.Type)\n\tvar controller ControllerInterface\n\n\t// Select controller based on prefix\n\tfor i := range req.Uri {\n\t\tif strings.HasPrefix(req.Uri[i], \"mitigate\") {\n\t\t\tlog.Debug(\"Call MitigationRequest controller\")\n\t\t\tcontroller = &MitigationRequest{}\n\t\t\tbreak;\n\t\n\t\t} else if strings.HasPrefix(req.Uri[i], \"config\") {\n\t\t\tlog.Debug(\"Call SessionConfig controller\")\n\t\t\tcontroller = &SessionConfiguration{}\n\t\t\tbreak;\t\n\t\t} else if strings.HasPrefix(req.Uri[i], \"tm-setup\") {\n\t\t\tlog.Debug(\"Call TelemetrySetupRequest controller\")\n\t\t\tcontroller = &TelemetrySetupRequest{}\n\t\t\tbreak;\n\t\t} else if strings.HasPrefix(req.Uri[i], \"tm\") {\n\t\t\tlog.Debug(\"Call TelemetryPreMitigationRequest controller\")\n\t\t\tcontroller = &TelemetryPreMitigationRequest{}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (controller == nil) {\n\t\tlog.Debug (\"No controller supports this kind of request\")\n\t\treturn Response{\n Code: dots_common.NotFound,\n Type: dots_common.NonConfirmable,\n }, nil\n\t}\n\n\t// Invoke controller service method to process request\n\tswitch req.Code {\n\tcase libcoap.RequestGet:\n\t\treturn controller.HandleGet(req, customer)\n\tcase libcoap.RequestPost:\n\t\treturn controller.HandlePost(req, customer)\n\tcase libcoap.RequestPut:\n\t\treturn controller.HandlePut(req, customer)\n\tcase libcoap.RequestDelete:\n\t\treturn controller.HandleDelete(req, customer)\n\tdefault:\n\t\tlog.Debug (\"No controller supports this type of request\")\n\t\treturn Response{\n Code: dots_common.NotFound,\n Type: dots_common.NonConfirmable,\n }, nil\n\t}\t\n}", "func (tc *RobertaForTokenClassification) ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds *ts.Tensor, train bool) (output *ts.Tensor, hiddenStates, attentions []*ts.Tensor, err error) {\n\thiddenState, _, hiddenStates, attentions, err := tc.roberta.ForwardT(inputIds, mask, tokenTypeIds, positionIds, inputEmbeds, ts.None, ts.None, train)\n\tif err != nil {\n\t\treturn ts.None, nil, nil, err\n\t}\n\n\tappliedDO := hiddenState.ApplyT(tc.dropout, train)\n\toutput = appliedDO.Apply(tc.classifier)\n\n\tappliedDO.MustDrop()\n\n\treturn output, hiddenStates, attentions, nil\n}", "func (vm *VM) Perform(target, locals Interface, msg *Message) Interface {\n\tif v, proto := GetSlot(target, msg.Name()); proto != nil {\n\t\tx := v.Activate(vm, target, locals, proto, msg)\n\t\tif x != nil {\n\t\t\treturn x\n\t\t}\n\t\treturn vm.Nil\n\t}\n\tif forward, fp := GetSlot(target, \"forward\"); fp != nil {\n\t\tx := forward.Activate(vm, target, locals, fp, msg)\n\t\tif x != nil {\n\t\t\treturn x\n\t\t}\n\t\treturn vm.Nil\n\t}\n\treturn vm.RaiseExceptionf(\"%s does not respond to %s\", vm.TypeName(target), msg.Name())\n}", "func (c *compiler) patchForward(mark int) {\n\toffset := len(c.code) - mark\n\tc.code[mark-1] = opcodeInt(offset)\n}", "func (m *NN) Forward(x *gorgonia.Node) (err error) {\n\tl := make([]*gorgonia.Node, len(m.W)+1)\n\tldot := make([]*gorgonia.Node, len(m.W))\n\tp := make([]*gorgonia.Node, len(m.W))\n\n\t// initial the first layer\n\tl[0] = x\n\n\t// W X + B\n\tfor i := 0; i < len(m.W); i++ {\n\t\tif len(m.B) != 0 && i < len(m.W) {\n\t\t\tL1, err := gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(l[i].Shape(), m.W[i].Shape())\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tldot[i], err = gorgonia.BroadcastAdd(L1, m.B[i], nil, []byte{0})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tldot[i], err = gorgonia.Mul(l[i], m.W[i])\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(\"mul wrong \", err)\n\t\t\t}\n\t\t}\n\n\t\t// Dropout\n\t\tp[i], err = gorgonia.Dropout(ldot[i], m.D[i])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Can't drop!\")\n\t\t}\n\n\t\t//activation function\n\t\tl[i+1] = gorgonia.Must(m.A[i](p[i]))\n\t}\n\n\tm.Pred = gorgonia.Must(m.A[len(m.A)-1](l[len(l)-1]))\n\tgorgonia.Read(m.Pred, &m.PredVal)\n\treturn\n}", "func (c *Cursor) Forward(n int) {\n\t(*c).Index += n\n}" ]
[ "0.6578177", "0.65311825", "0.60598856", "0.60520715", "0.59716046", "0.5958758", "0.59383243", "0.5921928", "0.5888444", "0.58074296", "0.57394636", "0.5717503", "0.5681384", "0.56571454", "0.5655735", "0.56228024", "0.5592294", "0.5528087", "0.5528087", "0.5523619", "0.55222744", "0.5512257", "0.5494828", "0.54749924", "0.54101", "0.54065764", "0.54032075", "0.5398537", "0.5397681", "0.53887117", "0.5378935", "0.5358342", "0.53275377", "0.53182375", "0.53122926", "0.5305775", "0.5286407", "0.52730876", "0.52641207", "0.52469265", "0.52280223", "0.5209902", "0.52034897", "0.5189926", "0.5173603", "0.5173603", "0.5165368", "0.5160966", "0.515784", "0.51500714", "0.51467013", "0.5124667", "0.5092642", "0.5091897", "0.50892776", "0.5070595", "0.506049", "0.50482076", "0.5044606", "0.50236046", "0.5017781", "0.49936208", "0.49914533", "0.49729666", "0.49639404", "0.49587506", "0.49553677", "0.4947405", "0.4935706", "0.49143076", "0.4905641", "0.49041647", "0.4895514", "0.48840648", "0.48818105", "0.48719975", "0.4863032", "0.48578268", "0.4853591", "0.48424932", "0.4840057", "0.48393983", "0.48375615", "0.48322257", "0.4821309", "0.48185062", "0.4815611", "0.48138782", "0.4811868", "0.48088896", "0.48047492", "0.47988072", "0.47896042", "0.47696084", "0.47560486", "0.4744879", "0.4742967", "0.47387883", "0.4733322", "0.47320768", "0.47279996" ]
0.0
-1
NotifyWithHipchat notify with hipchat
func (a *App) NotifyWithHipchat(body string, statusCode int) { if a.HipchatRoom == "" || a.HipchatToken == "" { return } url := "https://api.hipchat.com/v2/room/" + a.HipchatRoom + "/notification?auth_token=" + a.HipchatToken color := "red" if statusCode == 200 { color = "green" } input, err := json.Marshal(&hipchatRequest{Notify: true, MessageFormat: "text", Color: color, Message: "@all\n" + body}) if err != nil { log.Print(err) return } resp, err := a.HealthcheckNotifier.HipChatClient.Post(url, "application/json", bytes.NewBuffer(input)) if err != nil { log.Print(err) return } log.Printf("%s HipChat: %d", a.Name, resp.StatusCode) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Notify(client *hipchat.Client, cfg *config.Config) error {\n\treq := &hipchat.NotificationRequest{\n\t\tMessage: cfg.FormattedMessage(),\n\t\tNotify: config.ToBool(cfg.Notify),\n\t\tColor: cfg.Color,\n\t}\n\n\tfmt.Printf(\"%+v\\n\", req)\n\n\t_, err := client.Room.Notification(cfg.Room, req)\n\tfmt.Printf(\"%+v\\n\", err)\n\n\treturn err\n}", "func Notify(to tb.Recipient, b *tb.Bot, action tb.ChatAction) {\n\terr := b.Notify(to, action)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n}", "func appNotifyChatNotifyMessage(appID string, chatID uint64, chatType, user, msg string, ts time.Time, domain string) {\n\tnotifyMessage(appID, types.MsgKindChatNotify, chatID, chatType, user, msg, 0, ts, domain)\n}", "func (notifier *Notifier) Notify(notification Notification) {\n\n}", "func (n *Notifier) Notify(chatId int64, text string, opts ...Option) error {\n\toptions := NewOptions()\n\tfor _, o := range opts {\n\t\tif err := o(options); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(n.Token) == 0 {\n\t\treturn errors.New(\"bot token not set\")\n\t} else if len(text) == 0 {\n\t\treturn errors.New(\"empty text\")\n\t}\n\n\turi := fmt.Sprintf(\"https://api.telegram.org/bot%s/sendMessage\", n.Token)\n\tdata := url.Values{}\n\tdata.Set(\"chat_id\", fmt.Sprintf(\"%d\", chatId))\n\tdata.Set(\"text\", text)\n\tdata.Set(\"parse_mode\", options.ParseMode)\n\tdata.Set(\"disable_web_page_preview\", fmt.Sprintf(\"%v\", options.DisableWebPreview))\n\n\tclient := n.Client\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\n\tr, _ := http.NewRequest(\"POST\", uri, strings.NewReader(data.Encode()))\n\tr.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(data.Encode())))\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"unexpected status: %s: %s\", res.Status, string(body))\n\t}\n\treturn nil\n}", "func (n *IFTTTNotifier) Notify(msg string) error {\n\n\treq := &utility.HTTPRequest{\n\t\tURL: fmt.Sprintf(\"https://maker.ifttt.com/trigger/%s/with/key/%s\", EventName, n.Key),\n\t}\n\n\tresp, _, err := n.httpClient.DoRequest(utility.HTTPMethodGET, req, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn errors.New(fmt.Sprintf(\"Unexpected status code %d in IFTTTNotifier\", resp.StatusCode))\n\t}\n\n\treturn nil\n}", "func Notify(id int) {\n\tresp := \".\\n\"\n\tresp += \"**\" + Config.Feeds[id].Feed.Title + \": **\" + \"\\n\"\n\tresp += Config.Feeds[id].Feed.Items[0].Date.String() + \"\\n\\n\"\n\t// If a 9front feed, extract the user ☺\n\tif strings.Contains(Config.Feeds[id].Feed.Items[0].Link, \"http://code.9front.org/hg/\") {\n\t\tlines := strings.Split(Config.Feeds[id].Feed.Items[0].Summary, \"\\n\")\n\t\tfor i, v := range lines {\n\t\t\tif strings.Contains(v, \"<th style=\\\"text-align:left;vertical-align:top;\\\">user</th>\") {\n\t\t\t\tline := html.UnescapeString((lines[i+1])[6:len(lines[i+1])-5])\n\t\t\t\tresp += line + \"\\n\\n\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tresp += \"`\" + Config.Feeds[id].Feed.Items[0].Title + \"`\" + \"\\n\"\n\tresp += \"\\n\" + Config.Feeds[id].Feed.Items[0].Link + \"\\n\"\n\tConfig.Feeds[id].Feed.Items[0].Read = true\n\tresp += \"\\n\"\n\t\n\t// Loop through subbed chans and post notification message\n\tfmt.Println(\"Looping through subs to notify...\")\n\tfor _, v := range Config.Subs {\n\t\tif v.SubID == id {\n\t\t\tSession.ChannelMessageSend(v.ChanID, resp)\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\tfmt.Println(\"No new notifys for \", Config.Feeds[id].Feed.UpdateURL)\n\t\n\t/* Enable for logging if subs break\n\tfmt.Println(Config.Feeds[id].Feed.Items[0])\n\tfmt.Println(Config.Feeds[id].Feed.Items[len(Config.Feeds[id].Feed.Items)-1])\n\t*/\n}", "func (r NopReporter) Notify(ctx context.Context, err error) {}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlevel.Debug(n.logger).Log(\"incident\", key)\n\tdata := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\ttmpl := notify.TmplText(n.tmpl, data, &err)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcontent := tmpl(n.conf.Message)\n\n\t// If the dingtalk chatbot required keywords security authenticate. add the keywords to the content.\n\tif n.conf.Keywords != nil && len(n.conf.Keywords) > 0 {\n\t\tkeywords := \"\\n\\n[Keywords] \"\n\t\tfor _, k := range n.conf.Keywords {\n\t\t\tkeywords = fmt.Sprintf(\"%s%s, \", keywords, k)\n\t\t}\n\n\t\tkeywords = strings.TrimSuffix(keywords, \", \")\n\t\tcontent = fmt.Sprintf(\"%s%s\", content, keywords)\n\t}\n\n\tmsg := &dingtalkMessage{\n\t\tType: \"text\",\n\t\tText: dingtalkMessageContent{\n\t\t\tContent: content,\n\t\t},\n\t}\n\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"templating error: %s\", err)\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(msg); err != nil {\n\t\treturn false, err\n\t}\n\n\twebhook, err := url.Parse(n.conf.Webhook.String())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpostMessageURL := config.URL{\n\t\tURL: webhook,\n\t}\n\n\t// If the dingtalk chatbot required signature security authenticate,\n\t// add signature and timestamp to the url.\n\tif len(n.conf.Secret) > 0 {\n\t\ttimestamp, sign, err := calcSign(string(n.conf.Secret))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tq := postMessageURL.Query()\n\t\tq.Set(\"timestamp\", timestamp)\n\t\tq.Set(\"sign\", sign)\n\t\tpostMessageURL.RawQuery = q.Encode()\n\t}\n\n\tresp, err := notify.PostJSON(ctx, n.client, postMessageURL.String(), &buf)\n\tif err != nil {\n\t\treturn true, notify.RedactURL(err)\n\t}\n\tdefer notify.Drain(resp)\n\n\tif resp.StatusCode != 200 {\n\t\treturn true, fmt.Errorf(\"unexpected status code %v\", resp.StatusCode)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tlevel.Debug(n.logger).Log(\"response\", string(body), \"incident\", key)\n\n\tvar dingResp response\n\tif err := json.Unmarshal(body, &dingResp); err != nil {\n\t\treturn true, err\n\t}\n\n\tif dingResp.Code == 0 {\n\t\treturn false, nil\n\t}\n\n\t// Exceed the active call frequency limit.\n\tif dingResp.Status != 0 {\n\t\treturn false, errors.New(dingResp.Punish)\n\t}\n\n\treturn false, errors.New(dingResp.Message)\n}", "func (sn *SlackMessage) Notify(slackURL string) error {\n\tbp, err := json.Marshal(sn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = http.Post(slackURL, \"application/json\", bytes.NewBuffer(bp))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func notify(ctx context.Context, report string) error {\n\t_, err := sendRequest(ctx, \"POST\", notifyAddr, report)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (f *Sender) Notify(msg BotMessageInterface, callbackNotification string, showAlert bool) {\n\tf.bot.AnswerCallbackQuery(tgbotapi.CallbackConfig{\n\t\tCallbackQueryID: msg.CallbackID(),\n\t\tShowAlert: showAlert,\n\t\tText: callbackNotification,\n\t})\n}", "func Notify(client *ircutil.Client, command *ircutil.Command,\n\tmessage *ircutil.Message) {\n\tircutil.SendNotice(client, message.Args[0], strings.Join(message.Args[1:],\n\t\t\" \"))\n}", "func (en Notification) PushNotification() {}", "func (n Notifier) Notify(status int) error {\n\tif n.webHook == \"\" {\n\t\treturn nil\n\t}\n\tstatusStr := \"\"\n\tif status == PROCESS_STARTED {\n\t\tstatusStr = \"\\\"starting\\\"\"\n\t} else if status == PROCESS_RUNNING {\n\t\tstatusStr = \"\\\"up\\\"\"\n\t} else {\n\t\tstatusStr = \"\\\"crashed\\\"\"\n\t}\n\tbody := `{\n\t\t\t\t\t\t\t\"ps\":\n\t\t\t\t\t\t\t\t{ \"status\":` + statusStr + `}\n\t\t\t\t\t\t}`\n\n\treq, err := http.NewRequest(\"PUT\", n.webHook, bytes.NewBufferString(body))\n\tif err != nil {\n\t\treturn errors.New(\"Error in Notify : Failed to construct the HTTP request\" + err.Error())\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tclient := &http.Client{}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"Error in Notify : Was not able to trigger the hook!\\n\" + err.Error())\n\t}\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func (u user) notify() {\n fmt.Printf(\"User: Sending User Email To %s<%s>\\n\", u.name, u.email)\n}", "func notify(conn *websocket.Conn, name, event string) error {\n\tdata := [2]string{name, event}\n\treturn conn.WriteJSON(data)\n}", "func Chat(chub *connections.ConnectionHub) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tgo chub.WriteMessage()\n\t\tlog.Println(\"wrote message\")\n\t})\n}", "func (p *Printer) Notify(ctx context.Context, to string, msg Message) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = p.writer.Write(b)\n\treturn err\n}", "func appNotifyChatMessage(appID string, msg *db.Message) {\n\tnotifyMessage(appID, types.MsgKindChat, msg.ChatID, msg.ChatType, msg.User, msg.Msg, msg.ID, msg.Ts, msg.Domain)\n}", "func (r *Raft) sendHeartbeat(to uint64) {\n\t//r.Prs[to].Next = r.RaftLog.LastIndex() + 1\n\tmsg := r.buildMsgWithoutData(pb.MessageType_MsgHeartbeat, to, false)\n\t//msg.Entries = entryValuesToPoints(r.RaftLog.entries[len(r.RaftLog.entries)-1:])\n\n\tr.appendMsg(msg)\n\t// Your Code Here (2A).\n}", "func (u user) notify() {\n fmt.Printf(\"Sending user email to %s<%s>\\n\",\n u.name,\n u.email)\n}", "func (s *slackNotifier) Notify(msg Message) error {\n\tmsgText := msg.Format()\n\thexRed := \"#FF0000\"\n\tattachment := slack.Attachment{\n\t\tFallback: &msgText,\n\t\tText: &msgText,\n\t\tColor: &hexRed,\n\t}\n\tif len(msg.Meta) != 0 {\n\t\tfor key, value := range msg.Meta {\n\t\t\tattachment.AddField(slack.Field{Title: key, Value: value})\n\t\t}\n\t}\n\tpayload := slack.Payload{\n\t\tUsername: \"Nanny\",\n\t\tIconEmoji: \":baby_chick:\",\n\t\tAttachments: []slack.Attachment{attachment},\n\t}\n\terrs := slack.Send(s.webhookURL, \"\", payload)\n\tif len(errs) > 0 {\n\t\terrStr := \"\"\n\t\tfor _, err := range errs {\n\t\t\terrStr = fmt.Sprintf(\"%s, \", err)\n\t\t}\n\t\treturn errors.New(errStr)\n\t}\n\treturn nil\n}", "func (h *Hipchat) send(client HipchatClient, color, format, message string, notify bool) error {\n\treq := hipchat.MessageRequest{\n\t\tRoomId: h.Room,\n\t\tFrom: \"Drone\",\n\t\tMessage: message,\n\t\tColor: color,\n\t\tMessageFormat: format,\n\t\tNotify: notify,\n\t}\n\n\treturn client.PostMessage(req)\n}", "func (c *Connector) Notify(route string, v interface{} ) error {\n\n\tdata, err := json.Marshal( v )\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg := &message.Message{\n\t\tType: message.Notify,\n\t\tRoute: route,\n\t\tData: data,\n\t}\n\treturn c.sendMessage(msg)\n}", "func (r *room) notify(method string, data interface{}) {\n\tpeers := r.getPeers()\n\tfor _, p := range peers {\n\t\tp.notify(method, data)\n\t}\n}", "func Notify(client *gophercloud.ServiceClient, id string) (r NotifyResult) {\n\tresp, err := client.Post(notifyURL(client, id), nil, nil, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{204},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (n *Notifier) Notify(ctx context.Context, text, language string) error {\n\tu := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"translate.google.com\",\n\t\tPath: \"translate_tts\",\n\t}\n\n\tq := u.Query()\n\tq.Add(\"ie\", \"UTF-8\")\n\tq.Add(\"q\", text)\n\tq.Add(\"tl\", language)\n\tq.Add(\"client\", \"tw-ob\")\n\tu.RawQuery = q.Encode()\n\n\treturn n.Play(ctx, u.String())\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t//n.logger.Info(key)\n\t//data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\t//tmpl := notify.TmplText(n.tmpl, data, &err)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t//n.logger.Info(tmpl(n.conf.Message))\n\n\ttitle := fmt.Sprintf(\"容器告警\")\n\t//text := n.genMarkdown(as)\n\tmsg := n.genMarkdown(title,as)\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(msg); err != nil {\n\t\treturn false, err\n\t}\n\n\tv := n.sign()\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s?%s\", yachURL, v.Encode()), &buf)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tresp, err := n.client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn true, notify.RedactURL(err)\n\t}\n\tdefer notify.Drain(resp)\n\n\tif resp.StatusCode != 200 {\n\t\treturn true, fmt.Errorf(\"unexpected status code %v\", resp.StatusCode)\n\t}\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tn.logger.WithFields(logrus.Fields{\"response\": string(respBody), \"iincident\": key}).WithError(err).Error()\n\t\treturn true, err\n\t}\n\tyachResponse := YachResponse{}\n\terr = json.Unmarshal(respBody, &yachResponse)\n\tif yachResponse.Code != 200 {\n\n\t}\n\tn.logger.WithFields(logrus.Fields{\"response\": string(respBody), \"iincident\": key}).Debug()\n\tdefer notify.Drain(resp)\n\n\treturn true, nil\n}", "func (s *SSHMeta) HubbleObserve(args ...string) *CmdRes {\n\targsCoalesced := \"\"\n\tif len(args) > 0 {\n\t\targsCoalesced = strings.Join(args, \" \")\n\t}\n\thubbleCmd := fmt.Sprintf(\"hubble observe --server=%q --output=jsonpb %s\",\n\t\thubbleSock, argsCoalesced)\n\treturn s.Exec(hubbleCmd)\n}", "func respondToChat(resp *chat.Message, p *MessageProperties) error {\n\tdata, err := json.Marshal(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := fmt.Sprintf(\"https://chat.googleapis.com/v1/%s/messages\", p.Space)\n\n\tbody := bytes.NewBuffer(data)\n\n\treq, err := http.NewRequest(\"POST\", url, body)\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"x-goog-api-key\", apiKey())\n\n\tclient := &http.Client{}\n\n\t_, err = client.Do(req)\n\treturn err\n}", "func HelloPubSub(ctx context.Context, m PubSubMessage) error {\n\tlog.Println(string(m.Data))\n newData := m.Data\n\tresponse, err := http.Post(\"http://13.233.127.38:5000/h\", \"application/json\", bytes.NewBuffer(newData))\n\tif err !=nil{\n\t\tfmt.Println(response)\n }else{\n log.Println(\"log for function\")\n }\n\treturn nil\n}", "func (h *Health) notify() {\n\tfor _, subscriber := range h.subscribers {\n\t\tif subscriber == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tselect {\n\t\tcase subscriber <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n}", "func (c *Client) Notify(text string, language ...string) error {\n\tlang := c.lang\n\tif len(language) != 0 {\n\t\tlang = language[0]\n\t}\n\tif c.accent != \"\" {\n\t\tlang = fmt.Sprintf(\"%s-%s\", lang, c.accent)\n\t}\n\n\turl, err := googletts.GetTTSURL(text, lang)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Play(url)\n}", "func (hc *HipChat2) Post(message string) bool {\n\tif hc.client == nil {\n\t\thc.client = hc.newClient()\n\t\tif hc.client == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tmsg := &hipchat.NotificationRequest{\n\t\tColor: \"purple\",\n\t\tMessage: message,\n\t\tNotify: true,\n\t\tMessageFormat: \"text\",\n\t}\n\n\tif _, err := hc.client.Room.Notification(hc.RoomID, msg); err != nil {\n\t\tlog.Errorf(\"Failed post message...: %s\", msg.Message)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (notifier *SlackNotifier) Notify(msg string) error {\n\t_, _, err := notifier.client.PostMessage(notifier.config.channelID, slack.MsgOptionText(msg, false))\n\tif err != nil {\n\t\tnotifier.logger.Error().Err(err).Msg(\"could not send message to slack\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d delegate) NotifyMsg(data []byte) {}", "func handleResponseNotification(task *task.MessageTask, response *libcoap.Pdu, env *task.Env){\n handleNotification(env, task, response)\n}", "func Notify(groupId string, value *map[string]interface{}) {\n\tlogs.Debug.Printf(\"Notify all client registred to groupid %s , with value %v\", groupId, value)\n\n\tlogs.Debug.Printf(\"clients %v \\n\", appclient.Clients)\n\n\tfor _, client := range appclient.Clients {\n\n\t\tif utils.Contains(client.GroupIds, groupId) {\n\t\t\tdata := map[string]interface{}{\n\t\t\t\t\"groupId\": groupId,\n\t\t\t\t\"value\": value,\n\t\t\t}\n\t\t\tmessage := Message{\n\t\t\t\tCommand: \"connector-value\",\n\t\t\t\tData: data,\n\t\t\t}\n\t\t\tlogs.Debug.Printf(\"Notifying client %p with message %s\", client, message)\n\t\t\tclient.Socket.WriteJSON(message)\n\t\t}\n\t}\n}", "func Notify(cmd string, msg string) error {\n\terr := execCmd(cmd)\n\texecCmd(notifyCmd(msg))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}", "func execNotify(arity int, p *gop.Context) {\n\targs := p.GetArgs(arity)\n\tconv := func(args []interface{}) []os.Signal {\n\t\tret := make([]os.Signal, len(args))\n\t\tfor i, arg := range args {\n\t\t\tret[i] = arg.(os.Signal)\n\t\t}\n\t\treturn ret\n\t}\n\tsignal.Notify(args[0].(chan<- os.Signal), conv(args[1:])...)\n}", "func (w *WebHook) Notify(i interface{}, log *logrus.Entry) error {\n\tvar videoType string\n\tvar video polochon.Video\n\n\tswitch v := i.(type) {\n\tcase *polochon.ShowEpisode:\n\t\tvideoType = \"episode\"\n\t\tvideo = v\n\tcase *polochon.Movie:\n\t\tvideoType = \"movie\"\n\t\tvideo = v\n\tdefault:\n\t\treturn ErrInvalidArgument\n\t}\n\n\tfor _, h := range w.hooks {\n\t\terr := w.notify(h, video, videoType)\n\t\tif err != nil {\n\t\t\tlog.Warnf(err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *HipchatAdapter) Send(res *Response, strings ...string) error {\n\treturn nil\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlevel.Debug(n.logger).Log(\"incident\", key)\n\tdata := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\ttmpl := notify.TmplText(n.tmpl, data, &err)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// if err != nil {\n\t// \treturn false, fmt.Errorf(\"templating error: %s\", err)\n\t// }\n\n\trequest := dysmsapi.CreateSendSmsRequest()\n\trequest.Scheme = \"https\"\n\n\trequest.PhoneNumbers = tmpl(n.conf.ToUsers)\n\trequest.SignName = \"优路教育\"\n\trequest.TemplateCode = \"SMS_192370717\"\n\n\talert01 := data.Alerts[0]\n\n\tvar resultParam bytes.Buffer\n\tresultParam.WriteString(\"微服务 \")\n\tresultParam.WriteString(alert01.Labels[\"serverity\"])\n\tresultParam.WriteString(\" 于 \")\n\tresultParam.WriteString(alert01.StartsAt.Format(\"2006-01-02 15:04:05\"))\n\tresultParam.WriteString(\" 时发生了 \")\n\tresultParam.WriteString(alert01.Labels[\"alertname\"])\n\tresultParam.WriteString(\" 事件,具体错误: \")\n\tresultParam.WriteString(alert01.Annotations.Values()[0])\n\n\tfmt.Println(resultParam.String())\n\n\tresultParamJson := `{\"data\": \"` + resultParam.String() + `\"}`\n\n\trequest.TemplateParam = resultParamJson\n\n\tresp, err := n.client.SendSms(request)\n\n\tfmt.Println(resp)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif resp.Code == \"OK\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, errors.New(resp.Message)\n}", "func sendHeartBeat(members map[string]Entry, selfName string) {\n\tm := createMessage(\"gossip\", members)\n\tb, err := json.Marshal(m)\n\tkMembers := pickAdresses(members, K, selfName)\n\tlogError(err)\n\tfor i := range kMembers {\n\t\trecipientId := kMembers[i]\n\n\t\t//split to timestamp and ip address\n\t\ta := strings.Split(recipientId, \"#\")\n\t\t//memberIp = ip\n\t\trecipientIp := a[1]\n\t\t//retrieve a UDPaddr\n\t\trecipientAddr, err := net.ResolveUDPAddr(\"udp\", recipientIp+\":\"+PORT)\n\t\tlogError(err)\n\t\tconn, err := net.DialUDP(\"udp\", nil, recipientAddr)\n\t\tif !logError(err) {\n\t\t\tconn.Write(b)\n\t\t\tconn.Close()\n\t\t}\n\t}\n}", "func (u user) notify() {\n\tfmt.Printf(\"Sending an email to %s<%s>\\n\", u.name, u.email)\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Sending user email to %s %s\\n\", u.name, u.email)\n}", "func Chatbot(w http.ResponseWriter, r *http.Request) {\n\tp, err := retrieveMessageProperties(r)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tresp, err := generateResponseMessage(p)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tif err := respondToChat(resp, p); err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n}", "func sendNotificationToSlack(payloadJSONEncoded []byte, response chan<- *http.Response) {\n\tfmt.Println(\"Sending notification to Slack...\")\n\n\t// Récupération des paramètres\n\t// ---------------------------\n\thookURL = config.SlackHookURL\n\thookPayload = config.SlackHookPayload\n\n\t// Envoi de la requête\n\t// -------------------\n\tresponse <- sendNotificationToApplication(hookURL, hookPayload, payloadJSONEncoded)\n}", "func notifyUser(msg string) {\n\tcmd := exec.Command(\"notify-send\", \"-u\", \"critical\", msg)\n\tcmd.Run()\n\treturn\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Send email to %s <%s>\\n\", u.name, u.email)\n}", "func (m Messenge) ListenChat(request messengers.ListenChatRequest, output messengers.ListenChatOutput) {\n\tif !m.Available() {\n\t\tlog.Println(\"bot not available\")\n\t\treturn\n\t}\n\tbot := m.bot\n\ttgu := tgbotapi.NewUpdate(0)\n\ttgu.Timeout = 60\n\n\tupdates, err := bot.GetUpdatesChan(tgu)\n\tif err != nil {\n\t\tlog.Panic(\"can't get updates chanel \", err)\n\t}\n\n\tfor update := range updates {\n\t\tchatID := update.Message.Chat.ID\n\t\tmustRegistered := false\n\t\t// is contact?\n\t\tcon := update.Message.Contact\n\t\tif con != nil {\n\t\t\tmustRegistered = true\n\t\t\trequest.Phone = con.PhoneNumber\n\t\t\trequest.Messenger = m.name\n\t\t\trequest.ChatID = int(chatID)\n\t\t\toutput.OnResponse(request)\n\t\t}\n\t\t// is document?\n\t\tdoc := update.Message.Document\n\t\tif doc != nil {\n\t\t\turl, err := m.bot.GetFileDirectURL(doc.FileID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"can't get url for file from chat %e\", err)\n\n\t\t\t} else {\n\t\t\t\trequest.Messenger = m.name\n\t\t\t\trequest.ChatID = int(chatID)\n\t\t\t\trequest.FileURL = url\n\t\t\t\trequest.FileName = doc.FileName\n\t\t\t\trequest.FileSize = doc.FileSize\n\t\t\t\trequest.Description = update.Message.Caption\n\t\t\t\toutput.OnResponse(request)\n\t\t\t}\n\t\t}\n\n\t\tregistered := m.isRegisteredWait(request, mustRegistered, int(chatID), 10)\n\t\tif registered {\n\t\t\tmsg := tgbotapi.NewMessage(chatID, upload)\n\t\t\tmsg.ParseMode = \"HTML\"\n\t\t\tbot.Send(msg)\n\t\t\tmsg = tgbotapi.NewMessage(chatID, m.server)\n\t\t\tbot.Send(msg)\n\t\t} else {\n\t\t\tmsg := tgbotapi.NewMessage(chatID, register)\n\t\t\tvar keyboard = tgbotapi.NewReplyKeyboard(\n\t\t\t\ttgbotapi.NewKeyboardButtonRow(\n\t\t\t\t\ttgbotapi.NewKeyboardButtonContact(\"\\xF0\\x9F\\x93\\x9E Send phone\"),\n\t\t\t\t),\n\t\t\t)\n\t\t\tmsg.ReplyMarkup = keyboard\n\t\t\tbot.Send(msg)\n\t\t}\n\t}\n}", "func listen(ch chan client.Notify) {\n\tfor notify := range ch {\n\t\tif notify.PingRequest != nil {\n\t\t\tfmt.Printf(\"Ping Request %v\\n\", notify.PingRequest)\n\t\t}\n\t}\n}", "func (node *hostNode) Notify(notifee network.Notifiee) {\n\tnode.host.Network().Notify(notifee)\n}", "func PushToHuawei(req *PushNotification, cfg *config.ConfYaml) (resp *ResponsePush, err error) {\n\tlogx.LogAccess.Debug(\"Start push notification for Huawei\")\n\n\tvar (\n\t\tclient *client.HMSClient\n\t\tretryCount = 0\n\t\tmaxRetry = cfg.Huawei.MaxRetry\n\t)\n\n\tif req.Retry > 0 && req.Retry < maxRetry {\n\t\tmaxRetry = req.Retry\n\t}\n\n\t// check message\n\terr = CheckMessage(req)\n\tif err != nil {\n\t\tlogx.LogError.Error(\"request error: \" + err.Error())\n\t\treturn nil, err\n\t}\n\n\tclient, err = InitHMSClient(cfg, cfg.Huawei.AppSecret, cfg.Huawei.AppID)\n\n\tif err != nil {\n\t\t// HMS server error\n\t\tlogx.LogError.Error(\"HMS server error: \" + err.Error())\n\t\treturn nil, err\n\t}\n\n\tresp = &ResponsePush{}\n\nRetry:\n\tisError := false\n\n\tnotification, _ := GetHuaweiNotification(req)\n\n\tres, err := client.SendMessage(context.Background(), notification)\n\tif err != nil {\n\t\t// Send Message error\n\t\terrLog := logPush(cfg, core.FailedPush, req.To, req, err)\n\t\tresp.Logs = append(resp.Logs, errLog)\n\t\tlogx.LogError.Error(\"HMS server send message error: \" + err.Error())\n\t\treturn resp, err\n\t}\n\n\t// Huawei Push Send API does not support exact results for each token\n\tif res.Code == \"80000000\" {\n\t\tstatus.StatStorage.AddHuaweiSuccess(int64(1))\n\t\tlogx.LogAccess.Debug(\"Huwaei Send Notification is completed successfully!\")\n\t} else {\n\t\tisError = true\n\t\tstatus.StatStorage.AddHuaweiError(int64(1))\n\t\tlogx.LogAccess.Debug(\"Huawei Send Notification is failed! Code: \" + res.Code)\n\t}\n\n\tif isError && retryCount < maxRetry {\n\t\tretryCount++\n\n\t\t// resend all tokens\n\t\tgoto Retry\n\t}\n\n\treturn resp, nil\n}", "func doNotify(ctx context.Context, psc *redis.PubSubConn, ch chan struct{}) error {\n\tswitch v := psc.ReceiveWithTimeout(time.Second).(type) {\n\tcase redis.Message:\n\t\tlog.Debug().Str(\"action\", string(v.Data)).Msg(\"got redis message\")\n\t\tif string(v.Data) != watchAction {\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Warn().Err(ctx.Err()).Msg(\"unable to notify channel\")\n\t\t\treturn ctx.Err()\n\t\tcase ch <- struct{}{}:\n\t\t}\n\tcase error:\n\t\tlog.Debug().Err(v).Msg(\"redis subscribe error\")\n\t\treturn v\n\t}\n\treturn nil\n}", "func logNotification(env *task.Env, task *task.MessageTask, pdu *libcoap.Pdu) {\n log.Infof(\"Message Code: %v (%+v)\", pdu.Code, pdu.CoapCode())\n\n\tif pdu.Data == nil {\n\t\treturn\n }\n\n var err error\n var logStr string\n var req *libcoap.Pdu\n if task != nil {\n req = task.GetMessage()\n } else {\n req = nil\n }\n\n observe, err := pdu.GetOptionIntegerValue(libcoap.OptionObserve)\n if err != nil {\n log.WithError(err).Warn(\"Get observe option value failed.\")\n return\n }\n log.WithField(\"Observe Value:\", observe).Info(\"Notification Message\")\n\n\tmaxAgeRes := pdu.GetOptionStringValue(libcoap.OptionMaxage)\n\tif maxAgeRes != \"\" {\n\t\tlog.Infof(\"Max-Age Option: %v\", maxAgeRes)\n\t}\n\n log.Infof(\" Raw payload: %s\", pdu.Data)\n hex := hex.Dump(pdu.Data)\n\tlog.Infof(\" Raw payload hex: \\n%s\", hex)\n\n\t// Check if the response body data is a string message (not an object)\n\tif pdu.IsMessageResponse() {\n\t\tlog.Debugf(\"Server send notification with error message: %+v\", pdu.Data)\n\t\treturn\n\t}\n\n\tdec := codec.NewDecoder(bytes.NewReader(pdu.Data), dots_common.NewCborHandle())\n\n // Identify response is mitigation or session configuration by cbor data in heximal\n if strings.Contains(hex, string(libcoap.IETF_MITIGATION_SCOPE_HEX)) {\n var v messages.MitigationResponse\n err = dec.Decode(&v)\n logStr = v.String()\n env.UpdateCountMitigation(req, v, string(pdu.Token))\n log.Debugf(\"Request query with token as key in map: %+v\", env.GetAllRequestQuery())\n } else if strings.Contains(hex, string(libcoap.IETF_SESSION_CONFIGURATION_HEX)) {\n var v messages.ConfigurationResponse\n err = dec.Decode(&v)\n logStr = v.String()\n log.Debug(\"Receive session notification - Client update new values to system session configuration and restart ping task.\")\n\t\tRestartHeartBeatTask(pdu, env)\n\n\t\t// Not refresh session config in case session config task is nil (server send notification after reset by expired Max-age)\n\t\tsessionTask := env.SessionConfigTask()\n\t\tif sessionTask != nil {\n\t\t\tRefreshSessionConfig(pdu, env, sessionTask.MessageTask())\n\t\t}\n\t} else if strings.Contains(hex, string(libcoap.IETF_TELEMETRY_PRE_MITIGATION)) {\n var v messages.TelemetryPreMitigationResponse\n err = dec.Decode(&v)\n logStr = v.String()\n log.Debug(\"Receive telemetry pre-mitigation notification.\")\n }else {\n log.Warnf(\"Unknown notification is received.\")\n }\n\n if err != nil {\n log.WithError(err).Warn(\"CBOR Decode failed.\")\n return\n }\n log.Infof(\" CBOR decoded: %s\", logStr)\n}", "func Notify(ctx context.Context, subj, msg string) error {\n\tif os.Getenv(\"GOPASS_NO_NOTIFY\") != \"\" || !config.Bool(ctx, \"core.notifications\") {\n\t\tdebug.Log(\"Notifications disabled\")\n\n\t\treturn nil\n\t}\n\tconn, err := dbus.SessionBus()\n\tif err != nil {\n\t\tdebug.Log(\"DBus failure: %s\", err)\n\n\t\treturn err\n\t}\n\n\tobj := conn.Object(\"org.freedesktop.Notifications\", \"/org/freedesktop/Notifications\")\n\tcall := obj.Call(\"org.freedesktop.Notifications.Notify\", 0, \"gopass\", uint32(0), iconURI(), subj, msg, []string{}, map[string]dbus.Variant{\"transient\": dbus.MakeVariant(true)}, int32(3000))\n\tif call.Err != nil {\n\t\tdebug.Log(\"DBus notification failure: %s\", call.Err)\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (notifier *Notifier) Notify(msg Message) {\n\tnotifier.receiveCh <- msg\n}", "func chatroom() {\n\tfor {\n\t\tselect {\n\t\tcase _betRecord := <-betRecordCh:\n\t\t\tcontentTyp := \"下注:\"\n\t\t\t//\"下注:\"/\"派彩:\"\n\t\t\tif _betRecord.Settled {\n\t\t\t\tcontentTyp = \"派彩:\"\n\t\t\t}\n\t\t\t_betRecordStr, err := json.Marshal(_betRecord)\n\t\t\tgoutils.CheckErr(err)\n\t\t\tpublish <- newEvent(models.EVENT_BET, contentTyp, string(_betRecordStr))\n\n\t\tcase _betAccount := <-betAccountCh:\n\t\t\t//更新帳戶\n\t\t\tpublish <- newEvent(models.EVENT_ACCOUNT, \"目前帳戶:\", fmt.Sprint(_betAccount.Balance))\n\n\t\tcase _countingSuggest := <-countingSuggestCh:\n\t\t\t//提供建議\n\t\t\tSuggestionBetStr := models.TransBetTypeToStr(_countingSuggest.SuggestionBet)\n\t\t\tif SuggestionBetStr != \"\" {\n\n\t\t\t\tTrendMethodWinRate := math.Abs(math.Ceil(_countingSuggest.TrendMethodWinRate*10000)) / 100\n\t\t\t\tmsg := \"第 \" + fmt.Sprint(_countingSuggest.TableNo) + \" 桌 \" + _countingSuggest.GameIDDisplay + \" 下一局建議買 \" + SuggestionBetStr + \" (\" + _countingSuggest.TrendName + \") TrendMethodWinRate:\" + fmt.Sprint(TrendMethodWinRate)\n\t\t\t\tgoutils.Logger.Info(\"TableNo:\" + fmt.Sprint(_countingSuggest.TableNo) + \" *真* 提供建議 msg:\" + msg)\n\t\t\t\t_countingSuggestStr, err := json.Marshal(_countingSuggest)\n\t\t\t\tgoutils.CheckErr(err)\n\t\t\t\tpublish <- newEvent(models.EVENT_SUGGESTION, \"建議:\", string(_countingSuggestStr))\n\t\t\t}\n\t\t\t/*\n\t\t\t\tSuggestionBetStr := models.TransBetTypeToStr(_countingSuggest.SuggestionBet)\n\t\t\t\tif SuggestionBetStr != \"\" {\n\t\t\t\t\tmsg := \"第 \" + fmt.Sprint(_countingSuggest.TableNo) + \" 桌 \" + _countingSuggest.GameIDDisplay + \" 下一局建議買 \" + SuggestionBetStr + \" (\" + _countingSuggest.TrendName + \")\"\n\t\t\t\t\tpublish <- newEvent(models.EVENT_SUGGESTION, \"建議:\", msg)\n\t\t\t\t\tgoutils.Logger.Info(\"TableNo:\" + fmt.Sprint(_countingSuggest.TableNo) + \" *真* 提供建議\")\n\t\t\t\t}\n\t\t\t*/\n\n\t\tcase _countingResult := <-countingResultCh:\n\t\t\t//報告預測結果\n\t\t\t//該局有提供建議時才會填這一局的 Result\n\t\t\t_countingResultStr, err := json.Marshal(_countingResult)\n\t\t\tgoutils.CheckErr(err)\n\t\t\tpublish <- newEvent(models.EVENT_RESULT, \"結果:\", string(_countingResultStr))\n\t\t\t/*\n\t\t\t\tvar guessResultStr string\n\t\t\t\tif _countingResult.TieReturn {\n\t\t\t\t\tguessResultStr = \"平\"\n\n\t\t\t\t} else {\n\n\t\t\t\t\tif _countingResult.GuessResult {\n\t\t\t\t\t\tguessResultStr = \"勝\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tguessResultStr = \"負\"\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tif _countingResult.FirstHand {\n\t\t\t\t\tguessResultStr = \"第一局預測不記結果\"\n\t\t\t\t}\n\n\t\t\t\tmsg := \"第 \" + fmt.Sprint(_countingResult.TableNo) + \" 桌 \" + _countingResult.GameIDDisplay + \" 開 \" + models.TransBetTypeToStr(_countingResult.Result) + \" 建議結果:\" + guessResultStr\n\n\t\t\t\tpublish <- newEvent(models.EVENT_RESULT, \"結果:\", msg)\n\t\t\t*/\n\t\t\tgoutils.Logger.Info(\"TableNo:\" + fmt.Sprint(_countingResult.TableNo) + \" *真* 公佈預測結果\")\n\t\tcase sub := <-subscribe:\n\t\t\tif !isUserExist(subscribers, sub.Name) {\n\t\t\t\tsubscribers.PushBack(sub) // Add user to the end of list.\n\t\t\t\t// Publish a JOIN event.\n\t\t\t\tpublish <- newEvent(models.EVENT_JOIN, sub.Name, \"\")\n\t\t\t\tgoutils.Logger.Info(\"New user:\", sub.Name, \";WebSocket:\", sub.Conn != nil)\n\t\t\t} else {\n\t\t\t\tgoutils.Logger.Info(\"Old user:\", sub.Name, \";WebSocket:\", sub.Conn != nil)\n\t\t\t}\n\t\tcase event := <-publish:\n\t\t\t// Notify waiting list.\n\t\t\tfor ch := waitingList.Back(); ch != nil; ch = ch.Prev() {\n\t\t\t\tch.Value.(chan bool) <- true\n\t\t\t\twaitingList.Remove(ch)\n\t\t\t}\n\t\t\t//TODO:實作不同的call 不同機器人權限連線的 WebSocket\n\t\t\t//注冊時就依權限分類不同的 subscribers(定時去檢查清單,到期就踢掉一些人,或是發佈時檢查其條件還在不在去踢一些人)\n\n\t\t\tbroadcastWebSocket(event) //給所有的 人\n\t\t\tmodels.NewArchive(event)\n\n\t\t\tif event.Type == models.EVENT_MESSAGE {\n\t\t\t\tgoutils.Logger.Info(\"Message from\", event.User, \";Content:\", event.Content)\n\t\t\t}\n\t\tcase unsub := <-unsubscribe:\n\t\t\tfor sub := subscribers.Front(); sub != nil; sub = sub.Next() {\n\t\t\t\tif sub.Value.(Subscriber).Name == unsub {\n\t\t\t\t\tsubscribers.Remove(sub)\n\t\t\t\t\t// Clone connection.\n\t\t\t\t\tws := sub.Value.(Subscriber).Conn\n\t\t\t\t\tif ws != nil {\n\t\t\t\t\t\tws.Close()\n\t\t\t\t\t\tgoutils.Logger.Error(\"WebSocket closed:\", unsub)\n\t\t\t\t\t}\n\t\t\t\t\tpublish <- newEvent(models.EVENT_LEAVE, unsub, \"\") // Publish a LEAVE event.\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (mp *MonitorPool) Notify(n *Notification) {\n\tif timeout, ok := mp.timeouts[n.Code]; ok {\n\t\tsession := mp.session(n.Key)\n\t\tmonitor := session.monitor(n.Code, timeout)\n\t\tmonitor.pulse()\n\t} else {\n\t\tlog.Println(fmt.Sprintf(\"presence: no configuration for notification code: %s\", n.Code))\n\t}\n}", "func web(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :https://anex.us/\"\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func notify(job jobConfig, result runResult) error {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\tnotifyPayload := jobNotify{\n\t\tRunID: job.ID,\n\t\tSuccess: result.Success,\n\t\tOutput: result.Output,\n\t\tLogs: result.Logs,\n\t}\n\n\tpayload, err := json.Marshal(notifyPayload)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"Sending payload %s\\n\", payload)\n\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/%s\", os.Getenv(\"ZETTO_HOST\"), \"notify\"), bytes.NewBuffer(payload))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"ApiKey %s\", os.Getenv(\"ZETTO_API_KEY\")))\n\treq.Header.Add(\"X-Runner-Name\", hostname)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treturn fmt.Errorf(\"Notify error %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}", "func (m *UnixManager) Push(notif *Notification) error {\n\tnotif.applyDefault()\n\n\tcall := m.busObj.Call(\n\t\tprefix+\".Notify\",\n\t\t0,\n\t\tm.appName,\n\t\tuint32(0),\n\t\t// notif.id, // replace id\n\t\tnotif.Icon,\n\t\tnotif.Title,\n\t\tnotif.Body,\n\t\tnotif.Actions.dbusFmt(),\n\t\tmap[string]interface{}{},\n\t\tnotif.ExpireTimeout,\n\t)\n\n\t// dbus error\n\tif call.Err != nil {\n\t\treturn call.Err\n\t}\n\n\t// NOTE Replace id\n\t// if len(call.Body) > 0 {\n\t// \tid := call.Body[0].(uint32)\n\n\t// \t// we keep only what we need.\n\t// \tm.actives[id] = notif\n\n\t// \treturn id, nil\n\t// }\n\n\treturn nil\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Sending User Email To %s<%s>\\n\",\n\t\tu.name,\n\t\tu.email)\n}", "func interfaceNotifications(ch *api.Channel) {\n\t// subscribe for specific notification message\n\tnotifChan := make(chan api.Message, 100)\n\tsubs, _ := ch.SubscribeNotification(notifChan, interfaces.NewSwInterfaceSetFlags)\n\n\t// enable interface events in VPP\n\tch.SendRequest(&interfaces.WantInterfaceEvents{\n\t\tPid: uint32(os.Getpid()),\n\t\tEnableDisable: 1,\n\t}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})\n\n\t// generate some events in VPP\n\tch.SendRequest(&interfaces.SwInterfaceSetFlags{\n\t\tSwIfIndex: 0,\n\t\tAdminUpDown: 0,\n\t}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})\n\tch.SendRequest(&interfaces.SwInterfaceSetFlags{\n\t\tSwIfIndex: 0,\n\t\tAdminUpDown: 1,\n\t}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})\n\n\t// receive one notification\n\tnotif := (<-notifChan).(*interfaces.SwInterfaceSetFlags)\n\tfmt.Printf(\"%+v\\n\", notif)\n\n\t// unsubscribe from delivery of the notifications\n\tch.UnsubscribeNotification(subs)\n}", "func interfaceNotifications(ch api.Channel, index interface_types.InterfaceIndex) {\n\tfmt.Printf(\"Subscribing to notificaiton events for interface index %d\\n\", index)\n\n\tnotifChan := make(chan api.Message, 100)\n\n\t// subscribe for specific notification message\n\tsub, err := ch.SubscribeNotification(notifChan, &interfaces.SwInterfaceEvent{})\n\tif err != nil {\n\t\tlogError(err, \"subscribing to interface events\")\n\t\treturn\n\t}\n\n\t// enable interface events in VPP\n\terr = ch.SendRequest(&interfaces.WantInterfaceEvents{\n\t\tPID: uint32(os.Getpid()),\n\t\tEnableDisable: 1,\n\t}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})\n\tif err != nil {\n\t\tlogError(err, \"enabling interface events\")\n\t\treturn\n\t}\n\n\t// receive notifications\n\tgo func() {\n\t\tfor notif := range notifChan {\n\t\t\te := notif.(*interfaces.SwInterfaceEvent)\n\t\t\tfmt.Printf(\"incoming event: %+v\\n\", e)\n\t\t\tmarshal(e)\n\t\t}\n\t}()\n\n\t// generate some events in VPP\n\terr = ch.SendRequest(&interfaces.SwInterfaceSetFlags{\n\t\tSwIfIndex: index,\n\t\tFlags: interface_types.IF_STATUS_API_FLAG_ADMIN_UP,\n\t}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})\n\tif err != nil {\n\t\tlogError(err, \"setting interface flags\")\n\t\treturn\n\t}\n\terr = ch.SendRequest(&interfaces.SwInterfaceSetFlags{\n\t\tSwIfIndex: index,\n\t\tFlags: 0,\n\t}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})\n\tif err != nil {\n\t\tlogError(err, \"setting interface flags\")\n\t\treturn\n\t}\n\n\t// disable interface events in VPP\n\terr = ch.SendRequest(&interfaces.WantInterfaceEvents{\n\t\tPID: uint32(os.Getpid()),\n\t\tEnableDisable: 0,\n\t}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})\n\tif err != nil {\n\t\tlogError(err, \"setting interface flags\")\n\t\treturn\n\t}\n\n\t// unsubscribe from delivery of the notifications\n\terr = sub.Unsubscribe()\n\tif err != nil {\n\t\tlogError(err, \"unsubscribing from interface events\")\n\t\treturn\n\t}\n\n\tfmt.Println(\"OK\")\n\tfmt.Println()\n}", "func SendNotification() {\n\tnotificationResponse := GetUnreadEventCount()\n\tserviceString, _ := json.Marshal(notificationResponse)\n\tsocket.SendNotification(\n\t\t\"success\",\n\t\tstring(serviceString),\n\t)\n\n\tlog.Println(\"send notification on channel\")\n\n}", "func cmdNotice(source interface{}, params [][]byte) {\n\n\t// u is allowed to be nil here; it means a message from a server, which\n\t// will be translated into a message from this server.\n\tu, _ := source.(*core.User)\n\tt := string(params[0])\n\n\t// Get the origin of the message.\n\tvar origin interface{}\n\tif u != nil {\n\t\torigin = u.Owndata()\n\t} else {\n\t\torigin = source\n\t}\n\n\tif target := core.GetUser(t); target != nil {\n\t\ttarget.Message(origin, u, params[1], \"noreply\")\n\t\treturn\n\t}\n\n\tif t[0] == '#' {\n\t\tchanname := t[1:]\n\t\tch := core.FindChannel(\"\", channame)\n\t\tif ch != nil {\n\t\t\tch.Message(origin, u, params[1], \"noreply\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *Room) Notify(msg interface{}) {\n\tfor _, m := range r.mobs.GetAll() {\n\t\tm.Send(msg)\n\t}\n\tr.Send(msg)\n}", "func (u user) notify() {\n\tfmt.Printf(\"Sending User Email to %s<%s>\\n\",\n\t\tu.name,\n\t\tu.email)\n}", "func (u User) Notify() {\n\tfmt.Println(\"Func User Notify() \" + u.Name)\n}", "func sendHelp(slackClient *slack.RTM, slackChannel string) {\n\tslackClient.SendMessage(slackClient.NewOutgoingMessage(helpMessage, slackChannel))\n}", "func sendHelp(slackClient *slack.RTM, slackChannel string) {\n\tslackClient.SendMessage(slackClient.NewOutgoingMessage(helpMessage, slackChannel))\n}", "func (p *hub) ASyncPush(caller ICaller, ds IDataSet) error {\n go p.notify(C_Mode_Push, caller, ds)\n return nil\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Sending user email to %s<%s>\\n\",\n\t\tu.name,\n\t\tu.email)\n}", "func (_m *MockJournal) Notify(_a0 Notifiee, _a1 Index) {\n\t_m.Called(_a0, _a1)\n}", "func (s *Server) broadcastHPMessage(msg *Message) {\n\ts.iteratePeersWithSendMsg(msg, Peer.EnqueueHPPacket, nil)\n}", "func (s *Slack) Notify(ctx context.Context, message string) {\n\tif t := os.Getenv(\"SLACK_TOKEN\"); t != \"\" {\n\t\ts.Token = t\n\t}\n\tif c := os.Getenv(\"SLACK_CHANNEL\"); c != \"\" {\n\t\ts.Channel = c\n\t}\n\tif s.Channel == \"\" {\n\t\ts.Channel = defaultSlackChannel\n\t}\n\tif s.Token == \"\" {\n\t\tlog.Printf(\"[ERROR] Slack token is required\")\n\t\treturn\n\t}\n\n\tcl := slack.New(s.Token)\n\tat := s.buildAttachment(message, ctx.Value(MetaContextKey) != nil)\n\n\t_, err := cl.Chat().PostMessage(s.Channel).Username(SlackUsername).\n\t\tIconURL(SlackIconURL).Attachment(&at).Text(\"\").Do(ctx)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Slack postMessage failure: %#v\", err)\n\t}\n}", "func (n *Notifier) Notify(err interface{}) error {\n\t_, sendErr := n.Client.SendNotice(NewNotice(err, nil))\n\treturn ex.New(sendErr)\n}", "func Notify(title, message string) error {\n\tnotification := toast.Notification{\n\t\tAppID: \"ntify\",\n\t\tTitle: title,\n\t\tMessage: message,\n\t\tIcon: \"\",\n\t\tActions: nil}\n\n\treturn notification.Push()\n}", "func chat(ctx *gin.Context) {\n\tcred := credentials.NewStaticCredentials(os.Getenv(\"ACCESS_KEY_ID\"), os.Getenv(\"SECRET_ACCESS_KEY\"), \"\")\n\tconfig := aws.NewConfig().WithCredentials(cred).WithRegion(os.Getenv(\"AWS_REGION\"))\n\tsess := session.Must(session.NewSession(config))\n\tsvc := lexruntimeservice.New(sess)\n\tinput := &lexruntimeservice.PostTextInput{\n\t\tBotName: aws.String(ctx.Query(\"bot_name\")),\n\t\tBotAlias: aws.String(ctx.Query(\"bot_alias\")),\n\t\tInputText: aws.String(ctx.Query(\"message\")),\n\t\tUserId: aws.String(ctx.Query(\"user_id\")),\n\t}\n\tresult, err := svc.PostText(input)\n\tif err != nil {\n\t\tctx.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error(), \"message\": \"Server Error.\", \"data\": nil})\n\t} else {\n\t\tctx.JSON(http.StatusOK, gin.H{\"error\": nil, \"message\": \"Bot Updated with new intent.\", \"data\": result})\n\t}\n}", "func HCommand(bot *tb.Bot) interface{} {\n\treturn func(m *tb.Message) {\n\t\tbot.Send(m.Chat, \"h\")\n\t}\n}", "func Notify(title, message string) error {\n\treturn errors.New(\"beeep: unsupported operating system: %v\", runtime.GOOS)\n}", "func speechNotify(n notification) error {\n\tvoice := os.Getenv(voiceEnv)\n\tif voice == \"\" {\n\t\tvoice = \"Alex\"\n\t}\n\ttext := fmt.Sprintf(\"%s %s\", n.title, n.message)\n\n\tcmd := exec.Command(\"say\", \"-v\", voice, text)\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn fmt.Errorf(\"Speech: %s\", err)\n\t}\n\n\treturn nil\n}", "func (i *Indicator) Notify(title string, message string, notifyIcon NotifyIcon, indicatorIcon Icon) {\n\tswitch i.config.notifyLevel {\n\tcase NotifyLevelOff:\n\t\treturn\n\tcase NotifyLevelMin:\n\t\ti.SetIcon(indicatorIcon)\n\tcase NotifyLevelMax:\n\t\ti.SetIcon(indicatorIcon)\n\t\tvar icoName string\n\t\tswitch notifyIcon {\n\t\tcase NotifyIconNil:\n\t\t\ticoName = \"\"\n\t\tcase NotifyIconNoConn:\n\t\t\ticoName = \"liqo-no_conn.png\"\n\t\tcase NotifyIconDefault:\n\t\t\ticoName = \"liqo-black.png\"\n\t\tcase NotifyIconGreen:\n\t\t\ticoName = \"liqo-green.png\"\n\t\tcase NotifyIconGray:\n\t\t\ticoName = \"liqo-gray.png\"\n\t\tcase NotifyIconOrange:\n\t\t\ticoName = \"liqo-orange.png\"\n\t\tdefault:\n\t\t\ticoName = \"liqo-black.png\"\n\t\t}\n\t\tif !i.gProvider.Mocked() {\n\t\t\t/*The golang guidelines suggests error messages should not start with a capitalized letter.\n\t\t\tTherefore, since Notify sometimes receives an error as 'message', the Capitalize() function\n\t\t\tovercomes this problem, correctly displaying the string to the user.*/\n\t\t\t_ = bip.Notify(title, stringUtils.Capitalize(message), filepath.Join(i.config.notifyIconPath, icoName))\n\t\t}\n\tdefault:\n\t\treturn\n\t}\n}", "func help(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :\"\n\tif len(args) == 0 {\n\t\tmessage += \"Try help <command>. For a list of commands try 'yaircb: commands'\"\n\t} else if len(args) != 1 {\n\t\tmessage += \"ERROR: Invalid number of arguments\"\n\t} else {\n\t\tif docString, found := helpStrings[args[0]]; found {\n\t\t\tmessage += args[0] + \": \" + docString\n\t\t} else {\n\t\t\tmessage += \"Found no help for '\" + args[0] + \"'\"\n\t\t}\n\t}\n\tlog.Println(message)\n\tsrvChan <- message\n}", "func (c *Command) OnMsg(user string, msg string) {\n}", "func (n *ConfirmChanNotifier) Notify(c *Confirmation) {\n\tn.C <- c\n}", "func Notification_PushToUserPipe(nf x.Notification) {\n\tnv := Notification_notifyToView(&nf, nf.ForUserId)\n\t_ = nv\n\t//call := base.NewCallWithData(\"NotifyAddOne\", nv)\n\tcall := NewPB_CommandToClient_WithData(\"NotifyAddOne\", nil)\n\tAllPipesMap.SendToUser(nf.ForUserId, call)\n}", "func Notify2Dingtalk(strSite string, strTextContent string) {\n\n\tfmt.Println(\"###### site\")\n\tfmt.Println(strSite)\n\tfmt.Println(\"###### text_content\")\n\tfmt.Println(strTextContent)\n\n client := &http.Client{}\n req, err := http.NewRequest(\"POST\", strSite, strings.NewReader(strTextContent))\n if err != nil {\n fmt.Println(\"error 1\")\n return\n }\n\n req.Header.Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tresp, err := client.Do(req)\n defer resp.Body.Close()\n\n body, err := ioutil.ReadAll(resp.Body)\n if err != nil {\n fmt.Println(\"error 2\")\n return\n }\n\n fmt.Println(\"repone:\",body)\n\t/* for compile check */\n\tbody = body\n}", "func sendNotificationToSup(\n\terr error,\n\tchSpec ChildSpec,\n\tchRuntimeName string,\n\tsupNotifyChan chan<- ChildNotification,\n\tterminateCh chan<- ChildNotification,\n) {\n\tchNotification := ChildNotification{\n\t\tname: chSpec.GetName(),\n\t\ttag: chSpec.GetTag(),\n\t\truntimeName: chRuntimeName,\n\t\terr: err,\n\t}\n\n\t// We send the chNotification that got created to our parent supervisor.\n\t//\n\t// There are two ways the supervisor could receive this notification:\n\t//\n\t// 1) If the supervisor is running it's supervision loop (e.g. normal\n\t// execution), the notification will be received over the `supNotifyChan`\n\t// channel; this will execute the restart mechanisms.\n\t//\n\t// 2) If the supervisor is shutting down, it won't be reading the\n\t// `supNotifyChan`, but instead is going to be executing the `stopChildren`\n\t// function, which calls the `child.Terminate` method for each of the supervised\n\t// internally, this function reads the `terminateCh`.\n\t//\n\tselect {\n\t// (1)\n\tcase supNotifyChan <- chNotification:\n\t// (2)\n\tcase terminateCh <- chNotification:\n\t}\n}", "func SendSlackNotification(title string, cobraCmd *cobra.Command, output string, mgr credential.Manager) error {\n\tuserID, err := mgr.GetUserIDByParseToken()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while parsinng oauth2 token\")\n\t}\n\n\tslackhookUrl := GlobalOpts.SlackAPIURL()\n\ttext_msg := \"New \" + title + \" is triggerred on \" + getClusterType() + \" by \" + userID\n\ttriggeredCmd := revertUpgradeOpts(title, cobraCmd)\n\tattachment := Attachment{\n\t\tColor: SLACK_COLOR,\n\t\tText: triggeredCmd + \"\\n\" + output,\n\t}\n\n\tslackBody, _ := json.Marshal(SlackRequestBody{Text: text_msg, Icon_emoji: ICON_EMOJI, Username: SLACK_USER_NAME,\n\t\tAttachments: []Attachment{attachment}})\n\treq, err := http.NewRequest(http.MethodPost, slackhookUrl, bytes.NewBuffer(slackBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tclient := &http.Client{Timeout: 10 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Drain response body and close, return error to context if there isn't any.\n\tdefer func() {\n\t\tderr := drainResponseBody(resp.Body)\n\t\tif err == nil {\n\t\t\terr = derr\n\t\t}\n\t\tcerr := resp.Body.Close()\n\t\tif err == nil {\n\t\t\terr = cerr\n\t\t}\n\t}()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"calling %s returned %s status\", slackhookUrl, resp.Status)\n\t}\n\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"while decoding slack response body\")\n\t}\n\tbodyString := string(bodyBytes)\n\tif bodyString != \"ok\" {\n\t\treturn fmt.Errorf(\"non-ok response returned from Slack\")\n\t}\n\treturn nil\n}", "func (observer Observer) notify(event Event) {\n\tfmt.Printf(\"Observer %s: New event received from channel %s with message %s \\n\", observer.id, event.channelId, event.value)\n}", "func notifySend(notif *Notification) {\n\t// Decide on the correct urgency string for notify-send\n\turgency := \"critical\"\n\tif notif.Priority < NORMAL {\n\t\turgency = \"low\"\n\t} else if notif.Priority < IMPORTANT {\n\t\turgency = \"normal\"\n\t}\n\n\t// Override the notification icon with an urgency-based one if it's not set\n\ticon := notif.Icon\n\tif icon == \"\" {\n\t\ticon = fmt.Sprintf(\"%s.png\", urgency)\n\t}\n\n\t// Patch for a bug in notify-send which causes it to not show messages\n\t// See www.archivum.info/ubuntu-bugs: Bug 1424243\n\tmsg := strings.Replace(notif.Message, \"&\", \"and\", -1)\n\n\tcmd := exec.Command(\n\t\t\"/usr/bin/env\",\n\t\t\"notify-send\",\n\t\t\"-i\", filepath.Join(config.Static.IconPath, icon),\n\t\t\"-t\", fmt.Sprintf(\"%d\", config.Notifications.NotifySend.Duration/time.Millisecond),\n\t\t\"-u\", urgency,\n\t\tnotif.Title,\n\t\tmsg,\n\t)\n\n\tlog.Debug(\"Command: %s %s\", cmd.Path, cmd.Args)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Critical(\"notify-send failed: `%s %s` (%v)\", cmd.Path, cmd.Args, err)\n\t\treturn\n\t}\n\tnotif.MarkComplete()\n}", "func Notification(id string, opt NotificationOpt) error {\n\tin := bytes.NewBuffer([]byte{})\n\tout := bytes.NewBuffer([]byte{})\n\tin.WriteString(opt.Content)\n\n\tparam := map[string]interface{}{\n\t\t\"priority\": opt.Priority,\n\t\t\"title\": opt.Title,\n\t\t\"sound\": opt.Sound,\n\t\t\"id\": id,\n\t}\n\tif opt.LED.On > 0 && opt.LED.Off > 0 {\n\t\tparam[\"led-on\"] = opt.LED.On\n\t\tparam[\"led-off\"] = opt.LED.Off\n\t}\n\tif opt.Viberate != nil {\n\t\tparam[\"viberate\"] = opt.Viberate\n\t}\n\tfor key, val := range map[string]string{\n\t\t\"led-color\": opt.LED.Color,\n\t\t\"action\": opt.Action,\n\t\t\"on_delete_action\": opt.DeleteAction,\n\t\t\"button_text_1\": opt.Btn1.Text,\n\t\t\"button_action_1\": opt.Btn1.Action,\n\t\t\"button_text_2\": opt.Btn2.Text,\n\t\t\"button_action_2\": opt.Btn2.Action,\n\t\t\"button_text_3\": opt.Btn3.Text,\n\t\t\"button_action_3\": opt.Btn3.Action,\n\t} {\n\t\tif val == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparam[key] = val\n\t}\n\n\tif err := exec(in, out, \"Notification\", param, \"\"); err != nil {\n\t\treturn err\n\t}\n\treturn checkErr(out.Bytes())\n}" ]
[ "0.7070116", "0.61992604", "0.60911196", "0.60856074", "0.60541904", "0.58165413", "0.57948136", "0.57418495", "0.5735038", "0.5724112", "0.5648719", "0.56233865", "0.5618996", "0.56145555", "0.5529747", "0.5523478", "0.5523463", "0.5488026", "0.5483475", "0.54820335", "0.5475805", "0.5474451", "0.54700255", "0.54682356", "0.5466986", "0.5425037", "0.5411074", "0.5408486", "0.54038733", "0.54038733", "0.54038733", "0.54038733", "0.53985775", "0.5398227", "0.5396538", "0.53929", "0.5386575", "0.5383223", "0.53824645", "0.5380452", "0.5365877", "0.53650236", "0.5359848", "0.53283226", "0.5290202", "0.5289329", "0.5273009", "0.52619326", "0.5240419", "0.52326113", "0.5229341", "0.52267176", "0.52252406", "0.52228856", "0.5213285", "0.52119553", "0.52046084", "0.520291", "0.51938254", "0.519263", "0.5183991", "0.51807445", "0.51667166", "0.5147006", "0.51426435", "0.5140294", "0.5126739", "0.512155", "0.511818", "0.5117772", "0.5116183", "0.5112481", "0.51104695", "0.51099265", "0.5102948", "0.5102009", "0.51002365", "0.51002365", "0.50972635", "0.5096823", "0.5085211", "0.50783205", "0.5077405", "0.5067137", "0.5066214", "0.50624985", "0.5059004", "0.50520664", "0.5045985", "0.50413674", "0.5034138", "0.50323397", "0.5029166", "0.5028595", "0.50277203", "0.5027678", "0.50244445", "0.5022038", "0.50211644", "0.50144666" ]
0.7933373
0
NotifyWithMail notify with mail
func (a *App) NotifyWithMail(body string, statusCode int) { from := a.HealthcheckNotifier.MailAddressFrom server := a.HealthcheckNotifier.SMTPServer to := a.MailAddressToDown subject := "[DOWN] " + a.Name if statusCode == 200 { to = a.MailAddressToUp subject = "[UP] " + a.Name } if server == "" || from == "" || len(to) == 0 { return } msg := "From: " + from + "\r\n" + "To: " + toLine(to) + "\r\n" + "Subject: " + subject + "\r\n\r\n" + body + "\r\n" err := smtp.SendMail(server, nil, from, to, []byte(msg)) if err != nil { log.Print(err) return } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (n *NotifyMail) Notify(mail M.Mail) {\n\tif err := n.store.Insert(&mail); err != nil {\n\t\tn.errChan.In() <- err\n\t\treturn\n\t}\n\tn.sendChan <- mail\n}", "func (n *SMTPNotifier) Notify(work *model.WorkRequest) error {\n\t// Get email body\n\tpayload := work.GetLogContent(n.PrefixFilter)\n\tif strings.TrimSpace(payload) == \"\" {\n\t\t// Nothing to notify, abort\n\t\treturn nil\n\t}\n\n\t// Buidl subject\n\tvar subject string\n\tif work.Status == model.Success {\n\t\tsubject = fmt.Sprintf(\"Webhook %s#%d SUCCESS.\", work.Name, work.ID)\n\t} else {\n\t\tsubject = fmt.Sprintf(\"Webhook %s#%d FAILED.\", work.Name, work.ID)\n\t}\n\n\t// Connect to the remote SMTP server.\n\tc, err := smtp.Dial(n.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the sender and recipient first\n\tif err := c.Mail(n.From); err != nil {\n\t\treturn err\n\t}\n\tif err := c.Rcpt(n.To); err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\t// Send the email body.\n\twc, err := c.Data()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Fprintf(wc, \"Subject: %s\\r\\n\\r\\n%s\\r\\n\\r\\n\", subject, payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = wc.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info.Printf(\"job %s#%d notification sent to %s\\n\", work.Name, work.ID, n.To)\n\n\t// Send the QUIT command and close the connection.\n\treturn c.Quit()\n}", "func send_email_notification(subj string, body string) {\n eMailConn, eMailErr := smtp.Dial(\"localhost:25\")\n if eMailErr != nil {\n log.Printf(\"SMTP server connection failure sending notification\\n\")\n }\n\n eMailConn.Mail(g_eMailFrom)\n eMailConn.Rcpt(g_eMailTo)\n\n wc, eMailErr := eMailConn.Data()\n if eMailErr != nil {\n log.Printf(\"Failure initiating DATA stage sending notification\\n\")\n }\n\n defer wc.Close()\n\n buf := bytes.NewBufferString(\"From: \" + g_eMailFrom + \"\\r\\n\" + \"To: \" + g_eMailTo + \"\\r\\n\" + subj + \"\\r\\n\\r\\n\" + body + \"\\r\\n\")\n\n _, eMailErr = buf.WriteTo(wc)\n if eMailErr != nil {\n log.Printf(\"Failure writing notification message DATA\\n\")\n }\n}", "func notify(ctx context.Context, report string) error {\n\t_, err := sendRequest(ctx, \"POST\", notifyAddr, report)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (u user) notify() {\n\tfmt.Printf(\"Sending an email to %s<%s>\\n\", u.name, u.email)\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Send email to %s <%s>\\n\", u.name, u.email)\n}", "func (u user) notify() {\n\tfmt.Printf(\"Sending User Email to %s<%s>\\n\",\n\t\tu.name,\n\t\tu.email)\n}", "func (s *OrderService) EmailNotify(order spec.Order) error {\n\t// Call the PRIVATE endpoint of the user service to get the user's email address\n\t// This is not protected so no auth token is required\n\tresp, err := s.client.InvokeMethod(context.Background(), \"users\", \"private/get/\"+order.ForUserID, \"GET\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error calling user service: %s\", err)\n\t}\n\n\tuser := &userspec.User{}\n\n\terr = json.Unmarshal(resp, user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\temailMetadata := map[string]string{\n\t\t\"emailTo\": user.Email,\n\t\t\"subject\": \"Dapr Store, order details: \" + order.Title,\n\t}\n\n\temailData := \"<h1>Thanks for your order!</h1>Order title: \" + order.Title + \"<br>Order ID: \" + order.ID +\n\t\t\"<br>User: \" + order.ForUserID + \"<br>Amount: £\" + fmt.Sprintf(\"%.2f\", order.Amount) + \"<br><br>Enjoy your new dapper threads!\"\n\n\trequest := &dapr.InvokeBindingRequest{}\n\trequest.Metadata = emailMetadata\n\trequest.Data = []byte(emailData)\n\trequest.Name = s.emailOutputName\n\trequest.Operation = \"create\"\n\n\tif err := s.client.InvokeOutputBinding(context.Background(), request); err != nil {\n\t\tlog.Printf(\"### Problem sending to email output: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tlog.Printf(\"### Email was sent to %s\", user.Email)\n\n\treturn nil\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Sending User Email To %s<%s>\\n\",\n\t\tu.name,\n\t\tu.email)\n}", "func (u user) notify() {\n fmt.Printf(\"User: Sending User Email To %s<%s>\\n\", u.name, u.email)\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Sending user email to %s %s\\n\", u.name, u.email)\n}", "func (u *user) notify() {\n\tfmt.Printf(\"Sending user email to %s<%s>\\n\",\n\t\tu.name,\n\t\tu.email)\n}", "func (s *MailStruct) sendNotification(body string) error {\n\n\tfrom := NotificationFrom\n\trecipients := NotificationRecipients\n\tsubject := NotificationSubject\n\tMailBody := s.MailQueue + \" \" + body\n\n\tsendmail := exec.Command(\"/usr/sbin/sendmail\", \"-G\", \"-i\", \"-f\", from, \"--\", recipients)\n\tpipe, err := sendmail.StdinPipe()\n\tif err != nil {\n\t\tlog.Println(\"Problem with sendmail() method: \", err)\n\t}\n\terr = sendmail.Start()\n\tif err != nil {\n\t\tlog.Println(\"Problem with sendmail() method: \", err)\n\t}\n\n\tfmt.Fprintf(pipe, \"Subject: %s\\n\\n\", subject)\n\tfmt.Fprintf(pipe, \"%s\", MailBody)\n\tpipe.Close()\n\treturn err\n}", "func SendRegisterNotifyMail(c *macaron.Context, u *models.User) {\n\tbody, err := c.HTMLString(string(AUTH_REGISTER_NOTIFY), ComposeTplData(u))\n\tif err != nil {\n\t\tlog.Error(4, \"HTMLString: %v\", err)\n\t\treturn\n\t}\n\n\tmsg := NewMessage([]string{u.Email}, c.Tr(\"mail.register_notify\"), body)\n\tmsg.Info = fmt.Sprintf(\"UID: %d, registration notify\", u.Id)\n\n\tSendAsync(msg)\n}", "func (h *State) notifyEmail(ctx *router.Context, cfg *rotang.Configuration, t time.Time) error {\n\tif !cfg.Config.Email.Enabled || !cfg.Config.Enabled || cfg.Config.External {\n\t\tmsg := \"config not Enabled\"\n\t\tif cfg.Config.Enabled {\n\t\t\tmsg = \"e-mail notifications disabled\"\n\t\t}\n\t\tlogging.Infof(ctx.Context, \"notifyEmail: %q not considered due to %s\", cfg.Config.Name, msg)\n\t\treturn nil\n\t}\n\texpTime := t.Add(time.Duration(cfg.Config.Email.DaysBeforeNotify) * fullDay).UTC()\n\tshifts, err := h.shiftStore(ctx.Context).ShiftsFromTo(ctx.Context, cfg.Config.Name, expTime, expTime.Add(fullDay))\n\tif err != nil {\n\t\tif status.Code(err) == codes.NotFound {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tfor _, s := range shifts {\n\t\tlogging.Debugf(ctx.Context, \"notifyEmail: %q considering shift: %v with expTime: %v\", cfg.Config.Name, s, expTime)\n\t\t// startAfterExpiry checks that the shift StartTime is Equal or After the expiry time.\n\t\tstartAfterExpiry := s.StartTime.After(expTime) || s.StartTime.Equal(expTime)\n\t\t// startInsideDay handles sending only one mail per shift.\n\t\tstartInsideDay := s.StartTime.Before(expTime.Add(fullDay))\n\t\t// notifyZero DatesBeforeNotify 0, then just check we're in the same day as ShiftStart.\n\t\tnotifyZero := t.Equal(expTime)\n\t\tif (notifyZero || startAfterExpiry) && startInsideDay {\n\t\t\tlogging.Debugf(ctx.Context, \"notifyEmail: %q matched shift: %v with expTime: %v\", cfg.Config.Name, s, expTime)\n\t\t\tfor _, m := range s.OnCall {\n\t\t\t\tif err := h.sendMail(ctx, cfg, &s, m.Email); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogging.Infof(ctx.Context, \"notifyEmail: mail sent out to: %q, rota: %q\", m.Email, cfg.Config.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (a *admin) notify() {\n\tfmt.Printf(\"Sending admin email to %s %s\\n\", a.name, a.email)\n}", "func SendNotification(message string, recipients []string) error {\n\te := tc.Email\n\tvar auth smtp.Auth\n\tif e.Password != \"\" {\n\t\tauth = smtp.PlainAuth(\"\", e.Username, e.Password, e.Server)\n\t}\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"Unknown host\"\n\t}\n\n\tfor _, recipient := range e.Notify {\n\t\tcontext := &emailData{\n\t\t\tFrom: e.Username,\n\t\t\tTo: recipient,\n\t\t\tSubject: \"DVID panic report\",\n\t\t\tBody: message,\n\t\t\tHost: hostname,\n\t\t}\n\n\t\tt := template.New(\"emailTemplate\")\n\t\tif t, err = t.Parse(emailTemplate); err != nil {\n\t\t\treturn fmt.Errorf(\"error trying to parse mail template: %v\", err)\n\t\t}\n\n\t\t// Apply the values we have initialized in our struct context to the template.\n\t\tvar doc bytes.Buffer\n\t\tif err = t.Execute(&doc, context); err != nil {\n\t\t\treturn fmt.Errorf(\"error trying to execute mail template: %v\", err)\n\t\t}\n\n\t\t// Send notification\n\t\terr = smtp.SendMail(e.Host(), auth, e.Username, []string{recipient}, doc.Bytes())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (u user) notify() {\n fmt.Printf(\"Sending user email to %s<%s>\\n\",\n u.name,\n u.email)\n}", "func (a *admin) notify() {\n\tfmt.Printf(\"Sending admin email to %s<%s>\\n\",\n\t\ta.name,\n\t\ta.email)\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func sendNotification(n notifier) {\n\tn.notify()\n}", "func (s *sesService) Notify(params interface{}) error {\n\tsesParams := params.(*SESNotifyInput)\n\n\tinput := &ses.SendEmailInput{\n\t\tDestination: &ses.Destination{\n\t\t\tToAddresses: aws.StringSlice(sesParams.To),\n\t\t},\n\t\tMessage: &ses.Message{\n\t\t\tBody: &ses.Body{\n\t\t\t\tText: &ses.Content{\n\t\t\t\t\tData: &sesParams.Message,\n\t\t\t\t\tCharset: aws.String(\"utf-8\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tSubject: &ses.Content{\n\t\t\t\tData: &sesParams.Subject,\n\t\t\t\tCharset: aws.String(\"utf-8\"),\n\t\t\t},\n\t\t},\n\t\tSource: aws.String(sesParams.From),\n\t}\n\n\tresp, err := s.client.SendEmail(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif sesParams.Debug {\n\t\tlog.Printf(\"message sent on aws ses: %v\", resp.MessageId)\n\t}\n\n\treturn nil\n}", "func (n *NotifyMail) send(errChan ErrorChannel, mail M.Mail) {\n\n\terr := n.SendMail(mail)\n\n\tif err != nil {\n\t\t//If no internet connection sleep untill waitTime\n\t\tif strings.Contains(fmt.Sprintf(\"%s\", err), \"no such host\") {\n\t\t\ttime.Sleep(time.Duration(n.waitTime) * time.Second)\n\t\t\terrChan.In() <- errors.New(\"No internet connection mail\")\n\t\t}\n\n\t\t//Try to resend mail n times\n\t\tif mail.Try >= n.retry {\n\t\t\tn.notifChan.In() <- fmt.Sprintf(\"Message sending failed after %d times %d\", n.retry, mail.Id)\n\t\t\tmail.Status = false\n\n\t\t\tif err := n.store.Update(&mail); err != nil {\n\t\t\t\tn.errChan.In() <- err\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\t//send to send mail channel again\n\t\tn.sendChan <- mail\n\t\terrChan.In() <- errors.New(fmt.Sprint(\"Resend: \", mail.Id))\n\t\treturn\n\t}\n\n\tmail.Status = true\n\tif err := n.store.Update(&mail); err != nil {\n\t\tn.errChan.In() <- err\n\t}\n\n\t//If no errors send success notification\n\tn.notifChan.In() <- fmt.Sprintf(\"Mail ID: %d Succesfully sended at: %s\", mail.Id)\n}", "func sendMail(recipient string, name string, url string, newStatus string, oldStatus string) {\n\tif GetConfiguration().Notification.Mailer.Host == \"\" || GetConfiguration().Notification.Mailer.Host == \"smtp.mymail.com\" {\n\t\tlogging.MustGetLogger(\"\").Warning(\"Not sending email because of missing configuration.\")\n\t\treturn\n\t}\n\n\tlogging.MustGetLogger(\"\").Debug(\"Sending email about \\\"\" + url + \"\\\"...\")\n\n\tmConf := GetConfiguration().Notification.Mailer\n\n\tm := gomail.NewMessage()\n\tm.SetAddressHeader(\"From\", mConf.From, GetConfiguration().Application.Title)\n\tm.SetHeader(\"To\", recipient)\n\tm.SetHeader(\"Subject\", \"Status Change: \"+name)\n\tm.SetBody(\"text/html\", \"Hello,<br /><br />\"+\n\t\t\"<b>\"+name+\"</b>\"+\" (\"+url+\") went on <b>\"+time.Now().Format(\"02.01.2006\")+\"</b> at <b>\"+time.Now().Format(\"15:04:05\")+\"</b> from \\\"\"+oldStatus+\"\\\" to \\\"<b>\"+newStatus+\"</b>\\\".<br /><br />\"+\n\t\t\"Sincerely,<br />\"+GetConfiguration().Application.Title+\"<br /><br />\"+\n\t\t\"<small>This email was sent automatically, please do not respond to it.</small>\")\n\n\td := gomail.NewPlainDialer(mConf.Host, mConf.Port, mConf.User, mConf.Password)\n\n\tif err := d.DialAndSend(m); err != nil {\n\t\tlogging.MustGetLogger(\"\").Error(\"Unable to send email: \", err)\n\t}\n}", "func (s *EmailNotificationSender) sendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) error {\n\tc, err := smtp.Dial(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tneedToClose := true\n\tdefer func() {\n\t\tif needToClose {\n\t\t\terr := c.Close()\n\t\t\tlog.Warn(\"Failed to close SMTP client connection\", \"err\", err)\n\t\t}\n\t}()\n\terr = c.Hello(s.smtpEhloName)\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok, _ := c.Extension(\"STARTTLS\"); ok {\n\t\tconfig := &tls.Config{ServerName: host}\n\t\tif err = c.StartTLS(config); err != nil {\n\t\t\tlog.Error(\"it's start tls\", \"err\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\tif a != nil {\n\t\tif ok, _ := c.Extension(\"AUTH\"); !ok {\n\t\t\treturn errors.New(\"smtp: server doesn't support AUTH\")\n\t\t}\n\t\tif err = c.Auth(a); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = c.Mail(from)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, recipient := range to {\n\t\terr = c.Rcpt(recipient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\twc, err := c.Data()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = wc.Write(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = wc.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.Quit()\n\tif err != nil {\n\t\treturn err\n\t}\n\tneedToClose = false\n\treturn nil\n}", "func (s *Slack) Notify(ctx context.Context, message string) {\n\tif t := os.Getenv(\"SLACK_TOKEN\"); t != \"\" {\n\t\ts.Token = t\n\t}\n\tif c := os.Getenv(\"SLACK_CHANNEL\"); c != \"\" {\n\t\ts.Channel = c\n\t}\n\tif s.Channel == \"\" {\n\t\ts.Channel = defaultSlackChannel\n\t}\n\tif s.Token == \"\" {\n\t\tlog.Printf(\"[ERROR] Slack token is required\")\n\t\treturn\n\t}\n\n\tcl := slack.New(s.Token)\n\tat := s.buildAttachment(message, ctx.Value(MetaContextKey) != nil)\n\n\t_, err := cl.Chat().PostMessage(s.Channel).Username(SlackUsername).\n\t\tIconURL(SlackIconURL).Attachment(&at).Text(\"\").Do(ctx)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Slack postMessage failure: %#v\", err)\n\t}\n}", "func NotifyUser(user *models.User, name string, msg string, url string, email bool) {\n\tif user.ID > 0 {\n\t\tnotification := models.NewNotification(name, msg, url)\n\t\tnotification.UserID = user.ID\n\t\tmodels.ORM.Create(&notification)\n\t\t// TODO: Email notification\n\t\t/*\t\tif email {\n\n\t\t\t\t}*/\n\t}\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlevel.Debug(n.logger).Log(\"incident\", key)\n\tdata := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\ttmpl := notify.TmplText(n.tmpl, data, &err)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t// if err != nil {\n\t// \treturn false, fmt.Errorf(\"templating error: %s\", err)\n\t// }\n\n\trequest := dysmsapi.CreateSendSmsRequest()\n\trequest.Scheme = \"https\"\n\n\trequest.PhoneNumbers = tmpl(n.conf.ToUsers)\n\trequest.SignName = \"优路教育\"\n\trequest.TemplateCode = \"SMS_192370717\"\n\n\talert01 := data.Alerts[0]\n\n\tvar resultParam bytes.Buffer\n\tresultParam.WriteString(\"微服务 \")\n\tresultParam.WriteString(alert01.Labels[\"serverity\"])\n\tresultParam.WriteString(\" 于 \")\n\tresultParam.WriteString(alert01.StartsAt.Format(\"2006-01-02 15:04:05\"))\n\tresultParam.WriteString(\" 时发生了 \")\n\tresultParam.WriteString(alert01.Labels[\"alertname\"])\n\tresultParam.WriteString(\" 事件,具体错误: \")\n\tresultParam.WriteString(alert01.Annotations.Values()[0])\n\n\tfmt.Println(resultParam.String())\n\n\tresultParamJson := `{\"data\": \"` + resultParam.String() + `\"}`\n\n\trequest.TemplateParam = resultParamJson\n\n\tresp, err := n.client.SendSms(request)\n\n\tfmt.Println(resp)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif resp.Code == \"OK\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, errors.New(resp.Message)\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tlevel.Debug(n.logger).Log(\"incident\", key)\n\tdata := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\ttmpl := notify.TmplText(n.tmpl, data, &err)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcontent := tmpl(n.conf.Message)\n\n\t// If the dingtalk chatbot required keywords security authenticate. add the keywords to the content.\n\tif n.conf.Keywords != nil && len(n.conf.Keywords) > 0 {\n\t\tkeywords := \"\\n\\n[Keywords] \"\n\t\tfor _, k := range n.conf.Keywords {\n\t\t\tkeywords = fmt.Sprintf(\"%s%s, \", keywords, k)\n\t\t}\n\n\t\tkeywords = strings.TrimSuffix(keywords, \", \")\n\t\tcontent = fmt.Sprintf(\"%s%s\", content, keywords)\n\t}\n\n\tmsg := &dingtalkMessage{\n\t\tType: \"text\",\n\t\tText: dingtalkMessageContent{\n\t\t\tContent: content,\n\t\t},\n\t}\n\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"templating error: %s\", err)\n\t}\n\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(msg); err != nil {\n\t\treturn false, err\n\t}\n\n\twebhook, err := url.Parse(n.conf.Webhook.String())\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tpostMessageURL := config.URL{\n\t\tURL: webhook,\n\t}\n\n\t// If the dingtalk chatbot required signature security authenticate,\n\t// add signature and timestamp to the url.\n\tif len(n.conf.Secret) > 0 {\n\t\ttimestamp, sign, err := calcSign(string(n.conf.Secret))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tq := postMessageURL.Query()\n\t\tq.Set(\"timestamp\", timestamp)\n\t\tq.Set(\"sign\", sign)\n\t\tpostMessageURL.RawQuery = q.Encode()\n\t}\n\n\tresp, err := notify.PostJSON(ctx, n.client, postMessageURL.String(), &buf)\n\tif err != nil {\n\t\treturn true, notify.RedactURL(err)\n\t}\n\tdefer notify.Drain(resp)\n\n\tif resp.StatusCode != 200 {\n\t\treturn true, fmt.Errorf(\"unexpected status code %v\", resp.StatusCode)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tlevel.Debug(n.logger).Log(\"response\", string(body), \"incident\", key)\n\n\tvar dingResp response\n\tif err := json.Unmarshal(body, &dingResp); err != nil {\n\t\treturn true, err\n\t}\n\n\tif dingResp.Code == 0 {\n\t\treturn false, nil\n\t}\n\n\t// Exceed the active call frequency limit.\n\tif dingResp.Status != 0 {\n\t\treturn false, errors.New(dingResp.Punish)\n\t}\n\n\treturn false, errors.New(dingResp.Message)\n}", "func (n *Notification) Send(title string, posturl string) error {\n\tcomponents := strings.SplitN(n.SMTPServer, \":\", 2)\n\tauth := smtp.PlainAuth(\"\", n.SMTPUsername, n.SMTPPassword, components[0])\n\ttemplateData := struct {\n\t\tTitle string\n\t\tURL string\n\t\tDomain string\n\t\tRecipient string\n\t}{\n\t\tTitle: title,\n\t\tURL: posturl,\n\t\tRecipient: n.Recipient,\n\t}\n\n\tif parsed, err := url.Parse(posturl); err == nil {\n\t\ttemplateData.Domain = parsed.Host\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tt, err := template.New(\"email\").Parse(TemplateText)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = t.Execute(buf, templateData); err != nil {\n\t\treturn err\n\t}\n\n\tbody := []byte(buf.String())\n\n\tif err := n.MailFunc(n.SMTPServer, auth, n.Sender, []string{n.Recipient}, body); err != nil {\n\t\tlog.Println(\"Send mail failed: \" + err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (notifier *ApprovalStatusNotifier) Notify(p *ProductReview, approved bool, msg string) error {\n\ts := \"Hello, this is \" + notifier.Sender + \" from Foo Incorporated.\\n\"\n\tif approved {\n\t\ts += \"Thank you for your review. It has been approved and will be on our site shortly!\\n\"\n\t} else {\n\t\ts += \"Your review has been denied due to not meeting our corporate policies regarding language.\"\n\t\ts += \"Please see our policies listed here: foo.inc/guidelines/community-practices.html\\n\"\n\t}\n\ts += msg\n\tlog.Println(\"Notifying client:\", s)\n\treturn nil\n}", "func SendIssueNotifyMail(u, owner *models.User, repo *models.Repository, issue *models.Issue) ([]string, error) {\n\tws, err := models.GetWatchers(repo.ID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetWatchers[%d]: %v\", repo.ID, err)\n\t}\n\n\ttos := make([]string, 0, len(ws))\n\tfor i := range ws {\n\t\tuid := ws[i].UserID\n\t\tif u.Id == uid {\n\t\t\tcontinue\n\t\t}\n\t\tto, err := models.GetUserByID(uid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"GetUserByID: %v\", err)\n\t\t}\n\t\tif to.IsOrganization() {\n\t\t\tcontinue\n\t\t}\n\n\t\ttos = append(tos, to.Email)\n\t}\n\n\tif len(tos) == 0 {\n\t\treturn tos, nil\n\t}\n\n\tsubject := fmt.Sprintf(\"[%s] %s (#%d)\", repo.Name, issue.Name, issue.Index)\n\tcontent := fmt.Sprintf(\"%s<br>-<br> <a href=\\\"%s%s/%s/issues/%d\\\">View it on Gogs</a>.\",\n\t\tmarkdown.RenderSpecialLink([]byte(strings.Replace(issue.Content, \"\\n\", \"<br>\", -1)), owner.Name+\"/\"+repo.Name, repo.ComposeMetas()),\n\t\tsetting.AppUrl, owner.Name, repo.Name, issue.Index)\n\tmsg := NewMessage(tos, subject, content)\n\tmsg.Info = fmt.Sprintf(\"Subject: %s, issue notify\", subject)\n\n\tSendAsync(msg)\n\treturn tos, nil\n}", "func (h *State) sendMail(ctx *router.Context, cfg *rotang.Configuration, shift *rotang.ShiftEntry, email string) error {\n\tm, err := h.memberStore(ctx.Context).Member(ctx.Context, email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsubject, body, err := emailFromTemplate(cfg.Config.Email.Subject, cfg.Config.Email.Body, &rotang.Info{\n\t\tRotaName: cfg.Config.Name,\n\t\tShiftConfig: cfg.Config.Shifts,\n\t\tShiftEntry: *shift,\n\t\tMember: *m,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tto, sender := h.setSender(ctx, []string{email})\n\n\treturn h.mailSender.Send(ctx.Context, &mail.Message{\n\t\tSender: sender,\n\t\tTo: to,\n\t\tSubject: subject,\n\t\tBody: body,\n\t})\n}", "func (s *slackNotifier) Notify(msg Message) error {\n\tmsgText := msg.Format()\n\thexRed := \"#FF0000\"\n\tattachment := slack.Attachment{\n\t\tFallback: &msgText,\n\t\tText: &msgText,\n\t\tColor: &hexRed,\n\t}\n\tif len(msg.Meta) != 0 {\n\t\tfor key, value := range msg.Meta {\n\t\t\tattachment.AddField(slack.Field{Title: key, Value: value})\n\t\t}\n\t}\n\tpayload := slack.Payload{\n\t\tUsername: \"Nanny\",\n\t\tIconEmoji: \":baby_chick:\",\n\t\tAttachments: []slack.Attachment{attachment},\n\t}\n\terrs := slack.Send(s.webhookURL, \"\", payload)\n\tif len(errs) > 0 {\n\t\terrStr := \"\"\n\t\tfor _, err := range errs {\n\t\t\terrStr = fmt.Sprintf(\"%s, \", err)\n\t\t}\n\t\treturn errors.New(errStr)\n\t}\n\treturn nil\n}", "func (s *Service) TapdMailNotice(header, body string) {\n\ts.sendMail(s.c.Mail.NoticeOwner, header, body)\n}", "func NewNotifyMail(conf NotifyMailConfig, nChan NotificationChannel, eChan ErrorChannel) *NotifyMail {\n\tc := mandrill.ClientWithKey(conf.Apikey)\n\n\tc.HTTPClient.Timeout = time.Duration(conf.Timeout) * time.Second\n\n\trps := 1\n\n\t//Computing rate Per Millisecond\n\tif conf.RatePerH > 3600000 {\n\t\trps = 36000000 / conf.RatePerH\n\t}\n\n\tmail := NotifyMail{\n\t\tclient: c,\n\t\tstore: MailStore{conf.DB, conf.Retry},\n\t\tnotifChan: nChan,\n\t\tsendChan: make(chan M.Mail, conf.BuffLimit),\n\t\twaitTime: conf.WaitTime,\n\t\tretry: conf.Retry,\n\t\tcloseChan: make(chan bool),\n\t\terrChan: eChan,\n\t\trpms: rps,\n\t\tfrpm: conf.RetryFailedPerMin,\n\t}\n\n\treturn &mail\n}", "func (n *NotifyMail) SendMail(m M.Mail) error {\n\tmessage := &mandrill.Message{}\n\n\tmessage.AddRecipient(m.ToMail, m.ToName.String, m.ToType) // AddRecipient([email protected], \"RecipientName\", \"to\")\n\tmessage.FromEmail = m.FromMail // [email protected]\n\tmessage.FromName = m.FromName.String //My Name\n\tmessage.Subject = m.Subject.String //Subject\n\tmessage.HTML = m.Html.String //<h1>Long interesting HTML content</h1>\n\n\t_, apiErr, err := n.client.MessagesSend(message)\n\n\tif err != nil {\n\t\t//If Api Error ex(invalid API key, invalid Mail, ....)\n\t\tif apiErr != nil {\n\t\t\treturn errors.New(\n\t\t\t\tfmt.Sprintf(\"Mandrill Api Error: Status: %s,\\n Code: %d,\\n Name: %s,\\n Message: %s\\n\",\n\t\t\t\t\tapiErr.Status,\n\t\t\t\t\tapiErr.Code,\n\t\t\t\t\tapiErr.Name,\n\t\t\t\t\tapiErr.Message))\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Notify(to tb.Recipient, b *tb.Bot, action tb.ChatAction) {\n\terr := b.Notify(to, action)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n}", "func (n *Notifier) Notify() {\n\tvar wg sync.WaitGroup\n\tlog.Println(\"Sending Notification of Site Contacts about\", n.Subject+\"...\")\n\tfor _, c := range n.Site.Contacts {\n\t\tif c.SmsActive || c.EmailActive {\n\t\t\t// Notify contact\n\t\t\twg.Add(1)\n\t\t\tgo send(c, n.Message, n.Subject, n.SendEmail, n.SendSms, &wg)\n\t\t} else {\n\t\t\tlog.Println(\"No active contact methods for\", c.Name)\n\t\t}\n\t}\n\twg.Wait()\n}", "func SendMail(to, subject, body string) (err error) {\n\tlog.Debug(\"calling rpc.SendMail\")\n\t_, err = RpcClientF.SendMail(context.Background(), &pb.MailRequest{To: to, Subject: subject, Body: body})\n\tif err != nil {\n\t\tlog.Warn(err)\n\t} else {\n\t\tlog.Debug(\"mail sent\")\n\t}\n\treturn\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tvar (\n\t\talerts = types.Alerts(as...)\n\t\tdata = notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\t\teventType = pagerDutyEventTrigger\n\t)\n\tif alerts.Status() == model.AlertResolved {\n\t\teventType = pagerDutyEventResolve\n\t}\n\n\tlevel.Debug(n.logger).Log(\"incident\", key, \"eventType\", eventType)\n\n\tdetails := make(map[string]string, len(n.conf.Details))\n\tfor k, v := range n.conf.Details {\n\t\tdetail, err := n.tmpl.ExecuteTextString(v, data)\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrapf(err, \"%q: failed to template %q\", k, v)\n\t\t}\n\t\tdetails[k] = detail\n\t}\n\n\tif n.apiV1 != \"\" {\n\t\treturn n.notifyV1(ctx, eventType, key, data, details, as...)\n\t}\n\treturn n.notifyV2(ctx, eventType, key, data, details, as...)\n}", "func NotifyOtherPeople(message string) {\n\n\n\t// Set up authentication information.\n\n\n\tauth := smtp.PlainAuth(\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"smtp.sendgrid.net\",\n\t)\n\t// Connect to the server, authenticate, set the sender and recipient,\n\t// and send the email all in one step.\n\n\tbody := \"To: \" + \"[email protected]\" + \"\\r\\nFrom:\" + \"<[email protected]>\" + \"\\r\\nSubject: \" + \"shit is all broken\" + \"\\r\\n\\r\\n\" + message\n\n\terr := smtp.SendMail(\n\t\t\"smtp.sendgrid.net:25\",\n\t\tauth,\n\t\t\"<[email protected]>\",\n\t\t[]string{\"[email protected]\"},\n\t\t[]byte(body),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (sn *SlackMessage) Notify(slackURL string) error {\n\tbp, err := json.Marshal(sn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = http.Post(slackURL, \"application/json\", bytes.NewBuffer(bp))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *Mailer) mail(keys map[string]interface{}, template []byte, sig <-chan bool, code chan<- uint, errs chan<- error) {\n\t<-sig\n\n\tvar body bytes.Buffer\n\tparser.ParseKeys(\"{{\\x20(.*)\\x20}}\", template, keys, &body)\n\n\thead := \"To: \" + keys[\"to\"].(string) + \"\\r\\n\" +\n\t\t\"Subject: \" + keys[\"subject\"].(string) + \"\\r\\n\" +\n\t\t\"MIME-Version: 1.0\\r\\n\" +\n\t\t\"Content-Type: text/html; charset=\\\"utf-8\\\"\\r\\n\" +\n\t\t\"Content-Transfer-Encoding: 7bit\\r\\n\\r\\n\"\n\tmsg := []byte(head + \"\\n\" + body.String() + \"\\r\\n\")\n\tto := []string{keys[\"to\"].(string)}\n\n\tif err := smtp.SendMail(m.address, m.auth, m.from, to, msg); err != nil {\n\t\terrs <- err\n\t} else {\n\t\tcode <- 400\n\t}\n}", "func (n *IFTTTNotifier) Notify(msg string) error {\n\n\treq := &utility.HTTPRequest{\n\t\tURL: fmt.Sprintf(\"https://maker.ifttt.com/trigger/%s/with/key/%s\", EventName, n.Key),\n\t}\n\n\tresp, _, err := n.httpClient.DoRequest(utility.HTTPMethodGET, req, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn errors.New(fmt.Sprintf(\"Unexpected status code %d in IFTTTNotifier\", resp.StatusCode))\n\t}\n\n\treturn nil\n}", "func NotifyUser(user model.User) error {\n\t// TODO: send them and email\n\treturn errors.New(\"Not implemented\")\n}", "func sendEmail(downErr, site string, emailSetting NotificationEmailSettings) {\n\n\tdefer wg.Done()\n\n\tlog.Print(\"Sending email....\")\n\n\tbody := \"From: \" + emailSetting.Username + \"\\n\" +\n\t\t\"To: \" + emailSetting.Username + \"\\n\" +\n\t\t\"Subject: \" + site + \" down \\n\\n\" + downErr\n\n\tauth := smtp.PlainAuth(\"\", emailSetting.Username, emailSetting.Password, emailSetting.Smtp)\n\terr := smtp.SendMail(\n\t\temailSetting.Smtp + \":\" + strconv.Itoa(emailSetting.Port),\n\t\tauth, emailSetting.Username,\n\t\t[]string{emailSetting.Username},\n\t\t[]byte(body))\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Println(\"Sent!\")\n}", "func (p *Printer) Notify(ctx context.Context, to string, msg Message) error {\n\tb, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = p.writer.Write(b)\n\treturn err\n}", "func (f *Sender) Notify(msg BotMessageInterface, callbackNotification string, showAlert bool) {\n\tf.bot.AnswerCallbackQuery(tgbotapi.CallbackConfig{\n\t\tCallbackQueryID: msg.CallbackID(),\n\t\tShowAlert: showAlert,\n\t\tText: callbackNotification,\n\t})\n}", "func (n *NotificationService) Notify(ctx context.Context, sub corgi.Subscription) error {\n\tmsg, err := n.messageGenerator.CreateNotification(ctx, sub)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn n.messageSender.Send(ctx, sub.User, msg)\n}", "func (c Config) SendNotification(msg string, recipient string) error {\n\trequestData := url.Values{}\n\trequestData.Set(\"To\", recipient)\n\trequestData.Set(\"From\", c.from)\n\trequestData.Set(\"Body\", msg)\n\trequestDataReader := *strings.NewReader(requestData.Encode())\n\tclient := &http.Client{}\n\trequest, _ := http.NewRequest(\"POST\", c.URL, &requestDataReader)\n\trequest.SetBasicAuth(c.accountSID, c.authToken)\n\trequest.Header.Add(\"Accept\", \"application/json\")\n\trequest.Header.Add(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tresp, _ := client.Do(request)\n\tif resp.StatusCode >= 200 && resp.StatusCode < 300 {\n\t\tvar data map[string]interface{}\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\terr := decoder.Decode(&data)\n\t\tif err == nil {\n\t\t\tlog.Println(data[\"sid\"])\n\t\t}\n\t\treturn nil\n\t}\n\treturn errors.New(\"Res: \" + resp.Status)\n}", "func notifySend(notif *Notification) {\n\t// Decide on the correct urgency string for notify-send\n\turgency := \"critical\"\n\tif notif.Priority < NORMAL {\n\t\turgency = \"low\"\n\t} else if notif.Priority < IMPORTANT {\n\t\turgency = \"normal\"\n\t}\n\n\t// Override the notification icon with an urgency-based one if it's not set\n\ticon := notif.Icon\n\tif icon == \"\" {\n\t\ticon = fmt.Sprintf(\"%s.png\", urgency)\n\t}\n\n\t// Patch for a bug in notify-send which causes it to not show messages\n\t// See www.archivum.info/ubuntu-bugs: Bug 1424243\n\tmsg := strings.Replace(notif.Message, \"&\", \"and\", -1)\n\n\tcmd := exec.Command(\n\t\t\"/usr/bin/env\",\n\t\t\"notify-send\",\n\t\t\"-i\", filepath.Join(config.Static.IconPath, icon),\n\t\t\"-t\", fmt.Sprintf(\"%d\", config.Notifications.NotifySend.Duration/time.Millisecond),\n\t\t\"-u\", urgency,\n\t\tnotif.Title,\n\t\tmsg,\n\t)\n\n\tlog.Debug(\"Command: %s %s\", cmd.Path, cmd.Args)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Critical(\"notify-send failed: `%s %s` (%v)\", cmd.Path, cmd.Args, err)\n\t\treturn\n\t}\n\tnotif.MarkComplete()\n}", "func (n *NotifyMail) Start() {\n\n\t//Run separate goroutine for non blocking main program & resend failed messages per n minute.\n\tgo func() {\n\t\tn.notifChan.In() <- fmt.Sprintf(\"Resend failed messages per %d minute\", n.frpm)\n\t\ttick := time.NewTicker(time.Duration(n.frpm) * time.Minute)\n\t\tfor {\n\t\t\tselect {\n\t\t\t//Wait rate per minute tick\n\t\t\tcase <-tick.C:\n\t\t\t\tn.ResendFailed()\n\t\t\tcase <-n.closeChan:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\t//Starting separate goroutine for non blocking main program\n\tgo func() {\n\t\t//Creating tick for rate per second limiting\n\t\ttick := time.NewTicker(time.Duration(n.rpms) * time.Millisecond)\n\n\t\tfor {\n\t\t\t//Waiting for messages\n\t\t\tmail := <-n.sendChan\n\n\t\t\t//Error Channel for listening mail send errors\n\t\t\terrChan := NewErrorChannel(2)\n\n\t\t\tselect {\n\n\t\t\t//Wait rate per second tick\n\t\t\tcase <-tick.C:\n\t\t\t\tgo n.send(errChan, mail)\n\n\t\t\t//If message sending failed send another\n\t\t\tcase err := <-errChan.Out():\n\t\t\t\tn.errChan.In() <- err\n\t\t\t\tgo n.send(errChan, mail)\n\t\t\tcase <-n.closeChan:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (notifier *SlackNotifier) Notify(msg string) error {\n\t_, _, err := notifier.client.PostMessage(notifier.config.channelID, slack.MsgOptionText(msg, false))\n\tif err != nil {\n\t\tnotifier.logger.Error().Err(err).Msg(\"could not send message to slack\")\n\t\treturn err\n\t}\n\treturn nil\n}", "func notify(job jobConfig, result runResult) error {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\tnotifyPayload := jobNotify{\n\t\tRunID: job.ID,\n\t\tSuccess: result.Success,\n\t\tOutput: result.Output,\n\t\tLogs: result.Logs,\n\t}\n\n\tpayload, err := json.Marshal(notifyPayload)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"Sending payload %s\\n\", payload)\n\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/%s\", os.Getenv(\"ZETTO_HOST\"), \"notify\"), bytes.NewBuffer(payload))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"ApiKey %s\", os.Getenv(\"ZETTO_API_KEY\")))\n\treq.Header.Add(\"X-Runner-Name\", hostname)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treturn fmt.Errorf(\"Notify error %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}", "func Notify(client *gophercloud.ServiceClient, id string) (r NotifyResult) {\n\tresp, err := client.Post(notifyURL(client, id), nil, nil, &gophercloud.RequestOpts{\n\t\tOkCodes: []int{204},\n\t})\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func (self *Notifier) SendNotification(notificationName string, body interface{}, _type string) {\n\tself.Facade.SendNotification(notificationName, body, _type)\n}", "func sendMailTrustifi(db *gorm.DB, orderId int) {\r\n\t// Query DB\r\n\tvar order model.PayOrder\r\n\tvar orderDetails []model.PayOrderDetail\r\n\tvar shopHistory model.ShopHistory\r\n\r\n\tdb.Preload(\"User\").First(&order, orderId)\r\n\tdb.Preload(\"Book\").Find(&orderDetails, \"pay_order_id = ?\", orderId)\r\n\tdb.First(&shopHistory, \"pay_order_id = ?\", orderId)\r\n\r\n\tif order.User.Email.Valid {\r\n\t\tvar err error\r\n\r\n\t\tcontent := getMailContent(order, shopHistory, orderDetails)\r\n\r\n\t\t// Compose email\r\n\t\turl := os.Getenv(\"TRUSTIFI_URL\") + \"/api/i/v1/email\"\r\n\r\n\t\ttype u struct {\r\n\t\t\tEmail string `json:\"email\"`\r\n\t\t}\r\n\r\n\t\treqData := struct {\r\n\t\t\tTitle string `json:\"title\"`\r\n\t\t\tHtml string `json:\"html\"`\r\n\t\t\tRecipients []u `json:\"recipients\"`\r\n\t\t\t// From u `json:\"from\"`\r\n\t\t}{\r\n\t\t\tTitle: \"eLibrary Shopping Record\",\r\n\t\t\tHtml: content,\r\n\t\t\tRecipients: []u{u{order.User.Email.String}},\r\n\t\t\t// From: u{\"[email protected]\"},\r\n\t\t}\r\n\r\n\t\tvar reqDataJson []byte\r\n\t\treqDataJson, err = json.Marshal(reqData)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\r\n\t\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(reqDataJson))\r\n\t\treq.Header.Add(\"x-trustifi-key\", os.Getenv(\"TRUSTIFI_KEY\"))\r\n\t\treq.Header.Add(\"x-trustifi-secret\", os.Getenv(\"TRUSTIFI_SECRET\"))\r\n\t\treq.Header.Add(\"Content-Type\", \"application/json\")\r\n\r\n\t\t// Send the email\r\n\t\tclient := &http.Client{}\r\n\r\n\t\tvar resp *http.Response\r\n\t\tresp, err = client.Do(req)\r\n\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\r\n\t\tdefer resp.Body.Close()\r\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\r\n\t\tfmt.Println(string(body))\r\n\t}\r\n}", "func Notify(client *ircutil.Client, command *ircutil.Command,\n\tmessage *ircutil.Message) {\n\tircutil.SendNotice(client, message.Args[0], strings.Join(message.Args[1:],\n\t\t\" \"))\n}", "func (n *emailNotifier) Send(_ context.Context, subject string, msg *Message) error {\n\tif !n.emailer.Valid() {\n\t\tsklog.Warning(\"No gmail API client; cannot send email!\")\n\t\treturn nil\n\t}\n\t// Replace all newlines with <br/> since gmail uses HTML format.\n\tbody := strings.ReplaceAll(msg.Body, \"\\n\", \"<br/>\")\n\trecipients := append(util.CopyStringSlice(n.to), msg.ExtraRecipients...)\n\tsklog.Infof(\"Sending email to %s: %s\", strings.Join(recipients, \",\"), subject)\n\t_, err := n.emailer.SendWithMarkup(\"\", n.from, recipients, subject, body, n.markup, \"\")\n\treturn err\n}", "func (c *Client) Send(entry model.NotifEntry) error {\n\th := hermes.Hermes{\n\t\tTheme: new(Theme),\n\t\tProduct: hermes.Product{\n\t\t\tName: c.meta.Name,\n\t\t\tLink: c.meta.URL,\n\t\t\tLogo: c.meta.Logo,\n\t\t\tCopyright: fmt.Sprintf(\"%s © %d %s %s\",\n\t\t\t\tc.meta.Author,\n\t\t\t\ttime.Now().Year(),\n\t\t\t\tc.meta.Name,\n\t\t\t\tc.meta.Version),\n\t\t},\n\t}\n\n\tmessage, err := msg.New(msg.Options{\n\t\tMeta: c.meta,\n\t\tEntry: entry,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttitle, text, err := message.RenderMarkdownTemplate(customTpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\temail := hermes.Email{\n\t\tBody: hermes.Body{\n\t\t\tTitle: fmt.Sprintf(\"%s 🔔 notification\", c.meta.Name),\n\t\t\tFreeMarkdown: hermes.Markdown(text),\n\t\t\tSignature: \"Thanks for your support!\",\n\t\t},\n\t}\n\n\t// Generate an HTML email with the provided contents (for modern clients)\n\thtmlpart, err := h.GenerateHTML(email)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"hermes: %v\", err)\n\t}\n\n\t// Generate the plaintext version of the e-mail (for clients that do not support xHTML)\n\ttextpart, err := h.GeneratePlainText(email)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"hermes: %v\", err)\n\t}\n\n\tmsg := gomail.NewMessage()\n\tmsg.SetHeader(\"From\", fmt.Sprintf(\"%s <%s>\", c.meta.Name, c.cfg.From))\n\tmsg.SetHeader(\"To\", c.cfg.To)\n\tmsg.SetHeader(\"Subject\", title)\n\tmsg.SetBody(\"text/plain\", textpart)\n\tmsg.AddAlternative(\"text/html\", htmlpart)\n\n\tvar tlsConfig *tls.Config\n\tif *c.cfg.InsecureSkipVerify {\n\t\ttlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: *c.cfg.InsecureSkipVerify,\n\t\t}\n\t}\n\n\tusername, err := utl.GetSecret(c.cfg.Username, c.cfg.UsernameFile)\n\tif err != nil {\n\t\tlog.Warn().Err(err).Msg(\"Cannot retrieve username secret for mail notifier\")\n\t}\n\tpassword, err := utl.GetSecret(c.cfg.Password, c.cfg.PasswordFile)\n\tif err != nil {\n\t\tlog.Warn().Err(err).Msg(\"Cannot retrieve password secret for mail notifier\")\n\t}\n\n\tdialer := &gomail.Dialer{\n\t\tHost: c.cfg.Host,\n\t\tPort: c.cfg.Port,\n\t\tUsername: username,\n\t\tPassword: password,\n\t\tSSL: *c.cfg.SSL,\n\t\tTLSConfig: tlsConfig,\n\t\tLocalName: c.cfg.LocalName,\n\t}\n\n\treturn dialer.DialAndSend(msg)\n}", "func (notifier *Notifier) Notify(notification Notification) {\n\n}", "func (c Client) SendNotification(notifyUser NotifyUser) {\n\trequest, _ := json.Marshal(notifyUser)\n\turi := fmt.Sprintf(\"%s/notify\", c.Host)\n\treq, err := http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(request))\n\n\tif err != nil {\n\t\tlogger.LogError(fmt.Sprintf(\"http.Do %s\", err.Error()))\n\t}\n\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Basic %s\", c.APIKey))\n\tclient := http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlogger.LogError(fmt.Sprintf(\"http.Do %s\", err.Error()))\n\t}\n\t_, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlogger.LogError(fmt.Sprintf(\"ReadAll: %s\", err.Error()))\n\n\t}\n\tdefer resp.Body.Close()\n}", "func (r NopReporter) Notify(ctx context.Context, err error) {}", "func SendMail(recipient string, subject string, fromTemplate string, replace interface{}) error {\n\tt := template.Must(template.New(\"_all\").Parse(fromTemplate))\n\n\tvar body bytes.Buffer\n\tif err := t.Execute(&body, replace); err != nil {\n\t\treturn err\n\t}\n\n\tm, err := getMailer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer m.Quit()\n\n\tmsg := []byte(\"From: \" + MAIL_SENDER +\"\\r\\n\" +\n\t\t\"To: \" + recipient + \"\\r\\n\" +\n\t\t\"Subject: \" + subject + \"\\r\\n\" +\n\t\t\"MIME-version: 1.0;\\nContent-Type: text/html; charset=\\\"UTF-8\\\";\\n\\n\\r\\n\" +\n\t\tbody.String() + \"\\r\\n\")\n\n\tif err := m.Rcpt(recipient); err != nil {\n\t\treturn err\n\t}\n\n\tw, err := m.Data()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_ = w.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SendMail(config Config, missingContainers []string) {\n\tpassword := \"\"\n\tfmt.Println(\"config.Email.PasswordEnv: \"+config.Email.Passwordenv)\n\tif config.Email.Passwordenv != \"\" {\n\t\tpassword = os.Getenv(config.Email.Passwordenv)\n\t\tfmt.Println(\"env: \"+password)\n\t} else {\n\t\tpassword = config.Email.Password\n\t}\n\n\ttext := \"Some of your Docker containers might not be running:\\n\" + strings.Join(missingContainers, \"\\n\")\n\tmsg := []byte(\"To: \" + config.Email.Recipient + \"\\r\\n\" +\n\t\t\"Subject: SimpleDockerMonitoring warning!\\r\\n\" +\n\t\t\"\\r\\n\" + text)\n\n\tauth := smtp.PlainAuth(\"\", config.Email.Username, password, config.Email.Hostname)\n\terr := smtp.SendMail(config.Email.Url, auth, config.Email.Sender, []string{config.Email.Recipient}, msg)\n\tif err != nil {\n\t\tfmt.Println(\"Cloud not send mail. \" + err.Error())\n\t\tos.Exit(7)\n\t} else {\n\t\tos.Exit(0)\n\t}\n}", "func (notifier *JenkinsNotifier) Notify() error {\n\tif notifier.JenkinsProject.Name == \"\" || notifier.JenkinsProject.Token == \"\" {\n\t\treturn errors.New(\"Jenkins Project config is not correct.\")\n\t}\n\n\turl := notifier.notifyUrl()\n\treq, err := http.NewRequest(\"POST\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tusername, apiToken := notifier.UserName, notifier.UserApiToken\n\tif notifier.JenkinsProject.HasJenkinsConfig() {\n\t\tusername, apiToken = notifier.JenkinsProject.Username, notifier.JenkinsProject.UserApiToken\n\t}\n\treq.SetBasicAuth(username, apiToken)\n\tresp, err := http.DefaultClient.Do(req)\n\tif err == nil && resp.StatusCode == http.StatusOK {\n\t\tdefer resp.Body.Close()\n\t\tlogs.Info(\"Notified to project \", notifier.JenkinsProject.Name)\n\t\treturn nil\n\t} else {\n\t\tif err == nil {\n\t\t\treturn errors.New(\"Notify Status is \" + resp.Status)\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n}", "func Notify(client *hipchat.Client, cfg *config.Config) error {\n\treq := &hipchat.NotificationRequest{\n\t\tMessage: cfg.FormattedMessage(),\n\t\tNotify: config.ToBool(cfg.Notify),\n\t\tColor: cfg.Color,\n\t}\n\n\tfmt.Printf(\"%+v\\n\", req)\n\n\t_, err := client.Room.Notification(cfg.Room, req)\n\tfmt.Printf(\"%+v\\n\", err)\n\n\treturn err\n}", "func notifyUser(msg string) {\n\tcmd := exec.Command(\"notify-send\", \"-u\", \"critical\", msg)\n\tcmd.Run()\n\treturn\n}", "func (i *Invoice) Email(id string, params *InvoiceEmailParams, client *Client) {\n\tvar body, _ = json.Marshal(params)\n\tresp, err := client.Post(i.Endpoint()+\"/\"+id+\"/email?send_attachment=true\", string(body))\n\n\tSendResp(resp, err, i)\n}", "func Notify(id int) {\n\tresp := \".\\n\"\n\tresp += \"**\" + Config.Feeds[id].Feed.Title + \": **\" + \"\\n\"\n\tresp += Config.Feeds[id].Feed.Items[0].Date.String() + \"\\n\\n\"\n\t// If a 9front feed, extract the user ☺\n\tif strings.Contains(Config.Feeds[id].Feed.Items[0].Link, \"http://code.9front.org/hg/\") {\n\t\tlines := strings.Split(Config.Feeds[id].Feed.Items[0].Summary, \"\\n\")\n\t\tfor i, v := range lines {\n\t\t\tif strings.Contains(v, \"<th style=\\\"text-align:left;vertical-align:top;\\\">user</th>\") {\n\t\t\t\tline := html.UnescapeString((lines[i+1])[6:len(lines[i+1])-5])\n\t\t\t\tresp += line + \"\\n\\n\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tresp += \"`\" + Config.Feeds[id].Feed.Items[0].Title + \"`\" + \"\\n\"\n\tresp += \"\\n\" + Config.Feeds[id].Feed.Items[0].Link + \"\\n\"\n\tConfig.Feeds[id].Feed.Items[0].Read = true\n\tresp += \"\\n\"\n\t\n\t// Loop through subbed chans and post notification message\n\tfmt.Println(\"Looping through subs to notify...\")\n\tfor _, v := range Config.Subs {\n\t\tif v.SubID == id {\n\t\t\tSession.ChannelMessageSend(v.ChanID, resp)\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\tfmt.Println(\"No new notifys for \", Config.Feeds[id].Feed.UpdateURL)\n\t\n\t/* Enable for logging if subs break\n\tfmt.Println(Config.Feeds[id].Feed.Items[0])\n\tfmt.Println(Config.Feeds[id].Feed.Items[len(Config.Feeds[id].Feed.Items)-1])\n\t*/\n}", "func sendMail(from, recipients string, maildata []byte) error {\n\tsendmail := exec.Command(\"/usr/sbin/sendmail\", \"-G\", \"-i\", \"-f\", from, \"--\", recipients)\n\tpipe, err := sendmail.StdinPipe()\n\tif err != nil {\n\t\tlog.Println(\"Problem with sendmail() method: \", err)\n\t}\n\n\terr = sendmail.Start()\n\tif err != nil {\n\t\tlog.Println(\"Problem with sendmail() method: \", err)\n\t}\n\n\tfmt.Fprintf(pipe, \"%s\", maildata)\n\tpipe.Close()\n\n\treturn err\n}", "func Notify(ctx context.Context, subj, msg string) error {\n\tif os.Getenv(\"GOPASS_NO_NOTIFY\") != \"\" || !config.Bool(ctx, \"core.notifications\") {\n\t\tdebug.Log(\"Notifications disabled\")\n\n\t\treturn nil\n\t}\n\tconn, err := dbus.SessionBus()\n\tif err != nil {\n\t\tdebug.Log(\"DBus failure: %s\", err)\n\n\t\treturn err\n\t}\n\n\tobj := conn.Object(\"org.freedesktop.Notifications\", \"/org/freedesktop/Notifications\")\n\tcall := obj.Call(\"org.freedesktop.Notifications.Notify\", 0, \"gopass\", uint32(0), iconURI(), subj, msg, []string{}, map[string]dbus.Variant{\"transient\": dbus.MakeVariant(true)}, int32(3000))\n\tif call.Err != nil {\n\t\tdebug.Log(\"DBus notification failure: %s\", call.Err)\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SendMail(ctx context.Context, addr string, a NegotiateAuth, from string, to []string, msg []byte, cfg *tls.Config) error {\n\terr := validateAddrs(from, to)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tt, _ := ctx.Deadline()\n\tvar d net.Dialer\n\tconn, err := d.DialContext(ctx, \"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = conn.SetDeadline(t)\n\tdefer conn.Close()\n\n\thost, _, _ := net.SplitHostPort(addr)\n\treturn sendMail(ctx, conn, host, a, from, to, msg, cfg)\n}", "func (o *SMTPOptions) sendMail(m message.Composer) error {\n\to.mutex.Lock()\n\tdefer o.mutex.Unlock()\n\n\tif err := o.client.Create(o); err != nil {\n\t\treturn err\n\t}\n\tdefer o.client.Close()\n\n\tvar subject, body string\n\ttoAddrs := o.toAddrs\n\tfromAddr := o.fromAddr\n\tisPlainText := o.PlainTextContents\n\tvar headers map[string][]string\n\n\tif emailMsg, ok := m.Raw().(*message.Email); ok {\n\t\tvar err error\n\t\tif len(emailMsg.From) != 0 {\n\t\t\tfromAddr, err = mail.ParseAddress(emailMsg.From)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"invalid 'from' address '%s'\", emailMsg.From)\n\t\t\t}\n\t\t}\n\n\t\ttoAddrs = make([]*mail.Address, len(emailMsg.Recipients))\n\n\t\tfor i := range emailMsg.Recipients {\n\t\t\ttoAddrs[i], err = mail.ParseAddress(emailMsg.Recipients[i])\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"invalid recipient '%s'\", emailMsg.Recipients[i])\n\t\t\t}\n\t\t}\n\n\t\tsubject = emailMsg.Subject\n\t\tbody = emailMsg.Body\n\t\tisPlainText = emailMsg.PlainTextContents\n\t\theaders = emailMsg.Headers\n\t}\n\tif fromAddr == nil {\n\t\treturn errors.New(\"no 'from' address specified\")\n\t}\n\tif len(toAddrs) == 0 {\n\t\treturn errors.New(\"no recipients specified\")\n\t}\n\n\tif err := o.client.Mail(fromAddr.Address); err != nil {\n\t\treturn errors.Wrapf(err, \"initiating mail transaction from address '%s'\", fromAddr.Address)\n\t}\n\n\tvar err error\n\tvar errs []string\n\tvar recipients []string\n\n\t// Set the recipients\n\tfor _, target := range toAddrs {\n\t\tif err = o.client.Rcpt(target.Address); err != nil {\n\t\t\terrs = append(errs, errors.Wrapf(err, \"establishing mail recipient '%s'\", target.String()).Error())\n\t\t\tcontinue\n\t\t}\n\t\trecipients = append(recipients, target.String())\n\t}\n\tif len(errs) > 0 {\n\t\treturn errors.New(strings.Join(errs, \"; \"))\n\t}\n\n\t// Send the email body.\n\twc, err := o.client.Data()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer wc.Close()\n\n\tif len(subject) == 0 && len(body) == 0 {\n\t\tsubject, body = o.GetContents(o, m)\n\t}\n\n\tcontents := []string{\n\t\tfmt.Sprintf(\"From: %s\", fromAddr.String()),\n\t\tfmt.Sprintf(\"To: %s\", strings.Join(recipients, \", \")),\n\t\tfmt.Sprintf(\"Subject: %s\", subject),\n\t\t\"MIME-Version: 1.0\",\n\t}\n\n\tskipContentType := false\n\tfor k, v := range headers {\n\t\tif k == \"To\" || k == \"From\" || k == \"Subject\" || k == \"Content-Transfer-Encoding\" {\n\t\t\tcontinue\n\t\t}\n\t\tif k == \"Content-Type\" {\n\t\t\tskipContentType = true\n\t\t}\n\t\tfor i := range v {\n\t\t\tcontents = append(contents, fmt.Sprintf(\"%s: %s\", k, v[i]))\n\t\t}\n\t}\n\n\tif !skipContentType {\n\t\tif isPlainText {\n\t\t\tcontents = append(contents, \"Content-Type: text/plain; charset=\\\"utf-8\\\"\")\n\t\t} else {\n\t\t\tcontents = append(contents, \"Content-Type: text/html; charset=\\\"utf-8\\\"\")\n\t\t}\n\t}\n\n\tcontents = append(contents,\n\t\t\"Content-Transfer-Encoding: base64\",\n\t\tbase64.StdEncoding.EncodeToString([]byte(body)))\n\n\t// write the body\n\t_, err = bytes.NewBufferString(strings.Join(contents, \"\\r\\n\")).WriteTo(wc)\n\treturn err\n}", "func (m *Mail) ListenForMail() {\n\tfor {\n\t\tmsg := <-m.Jobs\n\t\terr := m.Send(msg)\n\t\tif err != nil {\n\t\t\tm.Results <- Result{false, err}\n\t\t} else {\n\t\t\tm.Results <- Result{true, nil}\n\t\t}\n\t}\n}", "func alertEmail(details mailDetails) (string, string) {\r\n\tto := []string{details.UserName + \"@northeastern.edu\"}\r\n\tto = append(to, rc_email)\r\n\tsubject := \"Subject: Discovery - Login Node Use Warning (\" + details.UserName + \")\\n\"\r\n\tmime := \"MIME-version: 1.0;\\nContent-Type: text/html; charset=\\\"UTF-8\\\";\\n\\n\"\r\n\ttemplate, _ := template.ParseFiles(templateFile)\r\n\tvar body bytes.Buffer\r\n\ttemplate.Execute(&body, details)\r\n\tmsg := []byte(subject + mime + body.String())\r\n\terr := smtp.SendMail(\"smtp.discovery.neu.edu:25\", nil, rc_email, to, msg)\r\n\tnotify := \"notified\"\r\n\ttimeNow := timeCheck()\r\n\tif err != nil {\r\n\t\tnotify = \"un-notified\"\r\n\t\tcheck(err)\r\n\t}\r\n\ttimeString := strconv.FormatInt(timeNow, 10)\r\n\treturn notify, timeString\r\n}", "func (mh *MailerHandler) Send(req *restful.Request, rsp *restful.Response) {\n\n\tvar message mailer.Mail\n\treq.ReadEntity(&message)\n\n\tctx := req.Request.Context()\n\tlog.Logger(ctx).Debug(\"Sending Email\", zap.Any(\"to\", message.To), zap.String(\"subject\", message.Subject), zap.Any(\"templateData\", message.TemplateData))\n\n\tcli := mailer.NewMailerServiceClient(registry.GetClient(common.SERVICE_MAILER))\n\n\tclaims, ok := ctx.Value(claim.ContextKey).(claim.Claims)\n\tif !ok {\n\t\tservice.RestError500(req, rsp, fmt.Errorf(\"sending email anonymously is forbidden\"))\n\t\treturn\n\t}\n\tmessage.From = &mailer.User{\n\t\tAddress: claims.Email,\n\t\tName: claims.DisplayName,\n\t}\n\tmessage.From.Uuid, _ = claims.DecodeUserUuid()\n\tmessage.From.Name = claims.Name\n\tmessage.From.Address = claims.Email\n\n\tvar resolvedTos []*mailer.User\n\tfor _, to := range message.To {\n\t\tif resolved, e := mh.ResolveUser(ctx, to); e == nil {\n\t\t\tresolvedTos = append(resolvedTos, resolved)\n\t\t} else {\n\t\t\tlog.Logger(ctx).Error(\"ignoring sendmail for user as no email was found\", zap.Any(\"user\", to))\n\t\t}\n\t}\n\tif len(resolvedTos) == 0 {\n\t\tservice.RestError500(req, rsp, fmt.Errorf(\"could not find any address to send to\"))\n\t\treturn\n\t}\n\tmessage.To = resolvedTos\n\tqueue := true\n\tif message.TemplateId == \"AdminTestMail\" {\n\t\tqueue = false\n\t\tmessage.TemplateData[\"AdminName\"] = claims.Name\n\t}\n\n\t// Now call service to send email\n\tresponse, err := cli.SendMail(ctx, &mailer.SendMailRequest{Mail: &message, InQueue: queue})\n\tif err != nil {\n\t\tlog.Logger(ctx).Error(\"could not send mail\", zap.Error(err))\n\t\tservice.RestError500(req, rsp, err)\n\t\treturn\n\t}\n\tresponse = &mailer.SendMailResponse{Success: true}\n\trsp.WriteEntity(response)\n}", "func (p *Note) Notification(mt, msg, buid string, out interface{}) error {\n\tctx, cancel := context.WithTimeout(context.Background(), p.Timeout)\n\tdefer cancel()\n\treturn p.client.Do(p.note(ctx, mt, msg, buid), out)\n}", "func NotifyOnSlack(dates *invoices.DateRange, dirName string) error {\n\tmsg := &slack.MsgBuilder{\n\t\tTitleLink: \"https://s3.console.aws.amazon.com/s3/buckets/byrd-accounting\" + dirName,\n\t\tText: \"New numbers for media subscriptions available as PDF!\",\n\t\tPretext: \"Click the link below to access it.\",\n\t\tPeriod: dates.From + \"-\" + dates.To,\n\t\tColor: \"#00711D\",\n\t\tFooter: \"This is an auto-msg. Don't message me.\",\n\t}\n\tif err := slack.NotifyPDFCreation(msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Single) AdminMail(obj Object, subj, to string, grps ...string) error {\n\treturn AdminMail(s, obj, subj, to, grps...)\n}", "func Mail(ctx PfCtx, src_name string, src string, dst_name string, dst string, prefix bool, subject string, body string, regards bool, footer string, sysfooter bool) (err error) {\n\terr = mailA(ctx, src_name, src, []string{dst_name}, []string{dst}, prefix, subject, body, regards, footer, sysfooter)\n\tif err != nil {\n\t\tctx.Err(\"Sending email to \" + dst + \" failed: \" + err.Error())\n\t\terr = errors.New(\"Sending email failed\")\n\t}\n\n\treturn\n}", "func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {\n\tkey, err := notify.ExtractGroupKey(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t//n.logger.Info(key)\n\t//data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)\n\n\t//tmpl := notify.TmplText(n.tmpl, data, &err)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t//n.logger.Info(tmpl(n.conf.Message))\n\n\ttitle := fmt.Sprintf(\"容器告警\")\n\t//text := n.genMarkdown(as)\n\tmsg := n.genMarkdown(title,as)\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(msg); err != nil {\n\t\treturn false, err\n\t}\n\n\tv := n.sign()\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"%s?%s\", yachURL, v.Encode()), &buf)\n\tif err != nil {\n\t\treturn true, err\n\t}\n\tresp, err := n.client.Do(req.WithContext(ctx))\n\tif err != nil {\n\t\treturn true, notify.RedactURL(err)\n\t}\n\tdefer notify.Drain(resp)\n\n\tif resp.StatusCode != 200 {\n\t\treturn true, fmt.Errorf(\"unexpected status code %v\", resp.StatusCode)\n\t}\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tn.logger.WithFields(logrus.Fields{\"response\": string(respBody), \"iincident\": key}).WithError(err).Error()\n\t\treturn true, err\n\t}\n\tyachResponse := YachResponse{}\n\terr = json.Unmarshal(respBody, &yachResponse)\n\tif yachResponse.Code != 200 {\n\n\t}\n\tn.logger.WithFields(logrus.Fields{\"response\": string(respBody), \"iincident\": key}).Debug()\n\tdefer notify.Drain(resp)\n\n\treturn true, nil\n}", "func SendConfMail(admn admin.AdminStruct, validator TempValidator) {\n\n\tbody := \"Dear \" + `,\nThank you for joining Inovatian’s InoChain, your request has been processed and your wallet has been created successfully.\nYour confirmation code is: ` + `\nPlease follow the following link to activate your wallet:\n(If this link is not clickable, please copy and paste into a new browser) \n` +\n\t\tglobalPkg.GlobalObj.Downloadfileip + \"/ConfirmedValidatorAPI?confirmationcode=\" + validator.ConfirmationCode +\n\t\t`\n This is a no-reply email; for any enquiries please contact [email protected]\nIf you did not create this wallet, please disregard this email.\nRegards,\nInovatian Team`\n\tfmt.Println(\"---------* Confirmation Code *-------- \", validator.ConfirmationCode)\n\tsendEmail(body, admn.AdminEmail)\n}", "func (g *NotifyService) Notify(body string) (exit int, err error) {\n\tcfg := g.client.Config\n\tparser := g.client.Config.Parser\n\ttemplate := g.client.Config.Template\n\n\tresult := parser.Parse(body)\n\tif result.Error != nil {\n\t\treturn result.ExitCode, result.Error\n\t}\n\tif result.Result == \"\" {\n\t\treturn result.ExitCode, result.Error\n\t}\n\n\ttemplate.SetValue(terraform.CommonTemplate{\n\t\tTitle: cfg.MR.Title,\n\t\tMessage: cfg.MR.Message,\n\t\tResult: result.Result,\n\t\tBody: body,\n\t\tLink: cfg.CI,\n\t})\n\tbody, err = template.Execute()\n\tif err != nil {\n\t\treturn result.ExitCode, err\n\t}\n\n\tvalue := template.GetValue()\n\n\tif cfg.MR.IsNumber() {\n\t\tg.client.Comment.DeleteDuplicates(value.Title)\n\t}\n\n\t_, isApply := parser.(*terraform.ApplyParser)\n\tif !cfg.MR.IsNumber() && isApply {\n\t\tcommits, err := g.client.Commits.List(cfg.MR.Revision)\n\t\tif err != nil {\n\t\t\treturn result.ExitCode, err\n\t\t}\n\t\tlastRevision, _ := g.client.Commits.lastOne(commits, cfg.MR.Revision)\n\t\tcfg.MR.Revision = lastRevision\n\t}\n\n\treturn result.ExitCode, g.client.Comment.Post(body, PostOptions{\n\t\tNumber: cfg.MR.Number,\n\t\tRevision: cfg.MR.Revision,\n\t})\n}", "func SendEmail(subject, body string, to ...string) pool.WorkFunc {\n\treturn func(wu pool.WorkUnit) (interface{}, error) {\n\t\terr := emailer.SendEmail(subject, body, to...)\n\t\tif wu.IsCancelled() {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n}", "func (a *Api) createAndSendNotification(req *http.Request, conf *models.Confirmation, content map[string]string, lang string) bool {\n\tlog.Printf(\"trying notification with template '%s' to %s with language '%s'\", conf.TemplateName, conf.Email, lang)\n\n\t// Get the template name based on the requested communication type\n\ttemplateName := conf.TemplateName\n\tif templateName == models.TemplateNameUndefined {\n\t\tswitch conf.Type {\n\t\tcase models.TypePasswordReset:\n\t\t\ttemplateName = models.TemplateNamePasswordReset\n\t\tcase models.TypePatientPasswordReset:\n\t\t\ttemplateName = models.TemplateNamePatientPasswordReset\n\t\tcase models.TypePatientPasswordInfo:\n\t\t\ttemplateName = models.TemplateNamePatientPasswordInfo\n\t\tcase models.TypeCareteamInvite:\n\t\t\ttemplateName = models.TemplateNameCareteamInvite\n\t\tcase models.TypeMedicalTeamInvite:\n\t\t\ttemplateName = models.TemplateNameMedicalteamInvite\n\t\tcase models.TypeMedicalTeamPatientInvite:\n\t\t\ttemplateName = models.TemplateNameMedicalteamPatientInvite\n\t\tcase models.TypeMedicalTeamMonitoringInvite:\n\t\t\ttemplateName = models.TemplateNameMedicalteamMonitoringInvite\n\t\tcase models.TypeMedicalTeamDoAdmin:\n\t\t\ttemplateName = models.TemplateNameMedicalteamDoAdmin\n\t\tcase models.TypeMedicalTeamRemove:\n\t\t\ttemplateName = models.TemplateNameMedicalteamRemove\n\t\tcase models.TypeSignUp:\n\t\t\ttemplateName = models.TemplateNameSignup\n\t\tcase models.TypeNoAccount:\n\t\t\ttemplateName = models.TemplateNameNoAccount\n\t\tcase models.TypeInformation:\n\t\t\ttemplateName = models.TemplateNamePatientInformation\n\t\tdefault:\n\t\t\tlog.Printf(\"Unknown confirmation type %s\", conf.Type)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Content collection is here to replace placeholders in template body/content\n\tcontent[\"WebURL\"] = a.getWebURL(req)\n\tcontent[\"SupportURL\"] = a.Config.SupportURL\n\tcontent[\"AssetURL\"] = a.Config.AssetURL\n\tcontent[\"PatientPasswordResetURL\"] = a.Config.PatientPasswordResetURL\n\tcontent[\"SupportEmail\"] = a.Config.SupportURL\n\n\tmail, ok := content[\"Email\"]\n\tif ok {\n\t\tcontent[\"EncodedEmail\"] = url.QueryEscape(mail)\n\t}\n\n\t// Retrieve the template from all the preloaded templates\n\ttemplate, ok := a.templates[templateName]\n\tif !ok {\n\t\tlog.Printf(\"Unknown template type %s\", templateName)\n\t\treturn false\n\t}\n\n\t// Email information (subject and body) are retrieved from the \"executed\" email template\n\t// \"Execution\" adds dynamic content using text/template lib\n\tsubject, body, err := template.Execute(content, lang)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error executing email template '%s'\", err)\n\t\treturn false\n\t}\n\n\tvar tags = make(map[string]string)\n\ttags[\"hydrophoneTemplate\"] = templateName.String()\n\tif traceSession := req.Header.Get(TP_TRACE_SESSION); traceSession != \"\" {\n\t\ttags[TP_TRACE_SESSION] = traceSession\n\t}\n\n\t// Finally send the email\n\tif status, details := a.notifier.Send([]string{conf.Email}, subject, body, tags); status != http.StatusOK {\n\t\tlog.Printf(\"Issue sending email: Status [%d] Message [%s]\", status, details)\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *Service) SendEmail(c context.Context, taskID int64) (err error) {\n\ttask, err := s.dao.DetailTask(c, taskID)\n\tif err != nil {\n\t\tlog.Error(\"s.SendEmail() error(%v)\", err)\n\t\treturn\n\t}\n\tcreateAt := task.CTime.Time().Format(ISO8601Date)\n\tvar sourceDesc string\n\tif task.SourceType == 1 {\n\t\tsourceDesc = \"创作姬\"\n\t} else {\n\t\tsourceDesc = \"其他\"\n\t}\n\tvar appStr string\n\tif task.Platform == 1 {\n\t\tappStr = \"IOS\"\n\t} else if task.Platform == 2 {\n\t\tappStr = \"Android\"\n\t}\n\tdate := task.LogDate.Time().Format(ISO8601Date)\n\tsubject := fmt.Sprintf(\" %s 创建的日志上报完成通知\", createAt)\n\tbody := fmt.Sprintf(\"你于%s创建的一条日志上报任务(上报来源:%s,%s App端,采集的日志文件日期:%s,指定MID:%d),现已上报完毕。\", createAt, sourceDesc, appStr, date, task.MID)\n\terr = s.dao.SendEmail(subject, task.ContactEmail, body)\n\treturn\n}", "func sendConfirmationEmail(w http.ResponseWriter, r *http.Request) {\n\tc := appengine.NewContext(r)\n\n\temail := r.FormValue(\"email\")\n\tbody := r.FormValue(\"body\")\n\tif email == \"\" || body == \"\" {\n\t\treturn\n\t}\n\n\tmsg := &mail.Message{\n\t\tSender: fmt.Sprintf(\"noreply@%s.appspotmail.com\", appengine.AppID(c)),\n\t\tTo: []string{email},\n\t\tSubject: \"You created a new Conference!\",\n\t\tBody: \"Hi, you have created the following conference:\\n\" + body,\n\t}\n\n\tif err := mail.Send(c, msg); err != nil {\n\t\tlog.Errorf(c, \"could not send email: %v\", err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t}\n}", "func (n *Notifier) Notify(err interface{}) error {\n\t_, sendErr := n.Client.SendNotice(NewNotice(err, nil))\n\treturn ex.New(sendErr)\n}", "func SendMail(subject, content, to string) {\n\tsendMail(subject, content, to, true)\n}", "func Notify (err error, rawData ...interface{}){\n\tbugsnag.Notify(err, rawData)\n}", "func (i *Integration) SendTxAckNotification(ctx context.Context, vars map[string]string, pl pb.TxAckEvent) error {\n\treturn i.publishEvent(ctx, pl.ApplicationId, pl.DevEui, \"txack\", &pl)\n}", "func (h *State) JobEmail(ctx *router.Context) {\n\tif err := ctx.Context.Err(); err != nil {\n\t\thttp.Error(ctx.Writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tnow := clock.Now(ctx.Context)\n\tconfigs, err := h.configStore(ctx.Context).RotaConfig(ctx.Context, \"\")\n\tif err != nil {\n\t\thttp.Error(ctx.Writer, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tfor _, cfg := range configs {\n\t\tif err := h.notifyEmail(ctx, cfg, now); err != nil {\n\t\t\tlogging.Warningf(ctx.Context, \"notifyEmail(ctx, _,%v) for rota: %q failed: %v\", now, cfg.Config.Name, err)\n\t\t}\n\t}\n}", "func (ctx *EmailCtx) SendEmail() {\n\temailCh <- ctx.MakeEmail()\n}", "func (n Notifier) Notify(status int) error {\n\tif n.webHook == \"\" {\n\t\treturn nil\n\t}\n\tstatusStr := \"\"\n\tif status == PROCESS_STARTED {\n\t\tstatusStr = \"\\\"starting\\\"\"\n\t} else if status == PROCESS_RUNNING {\n\t\tstatusStr = \"\\\"up\\\"\"\n\t} else {\n\t\tstatusStr = \"\\\"crashed\\\"\"\n\t}\n\tbody := `{\n\t\t\t\t\t\t\t\"ps\":\n\t\t\t\t\t\t\t\t{ \"status\":` + statusStr + `}\n\t\t\t\t\t\t}`\n\n\treq, err := http.NewRequest(\"PUT\", n.webHook, bytes.NewBufferString(body))\n\tif err != nil {\n\t\treturn errors.New(\"Error in Notify : Failed to construct the HTTP request\" + err.Error())\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tclient := &http.Client{}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn errors.New(\"Error in Notify : Was not able to trigger the hook!\\n\" + err.Error())\n\t}\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func SendMail(Config map[string]interface{}, subject string, message string, recipients ...string) error {\n\n\t//if test unit running, skip this\n\tif flag.Lookup(\"test.v\") == nil {\n\t\tmailer := gomail.NewMessage()\n\t\tmailer.SetHeader(\"From\", Config[\"email\"].(string))\n\t\tmailer.SetHeader(\"To\", recipients[0])\n\t\tif len(recipients) > 1 {\n\t\t\tmailer.SetHeader(\"Cc\", recipients[1])\n\t\t}\n\t\tmailer.SetHeader(\"Subject\", subject)\n\t\tmailer.SetBody(\"text/plain\", message)\n\n\t\tdialer := gomail.NewPlainDialer(Config[\"host\"].(string),\n\t\t\tConfig[\"port\"].(int),\n\t\t\tConfig[\"email\"].(string),\n\t\t\tConfig[\"password\"].(string))\n\n\t\terr := dialer.DialAndSend(mailer)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func SendEmailNotification(email string, notification *arn.PushNotification) error {\n\tm := gomail.NewMessage()\n\tm.SetHeader(\"From\", arn.APIKeys.SMTP.Address)\n\tm.SetHeader(\"To\", email)\n\tm.SetHeader(\"Subject\", notification.Title)\n\tm.SetBody(\"text/html\", \"<h2>\"+notification.Message+\"</h2><p><a href='\"+notification.Link+\"' target='_blank'><img src='\"+notification.Icon+\"' alt='Anime cover image' style='width:125px;height:181px;'></a></p>\")\n\n\td := gomail.NewDialer(arn.APIKeys.SMTP.Server, 587, arn.APIKeys.SMTP.Address, arn.APIKeys.SMTP.Password)\n\n\t// Send the email\n\treturn d.DialAndSend(m)\n}" ]
[ "0.7391516", "0.71107477", "0.705149", "0.6940533", "0.69082105", "0.68004864", "0.67699456", "0.6758246", "0.67541605", "0.67424625", "0.6731583", "0.6714901", "0.6697611", "0.66768765", "0.659905", "0.6598201", "0.6596002", "0.65796757", "0.6521858", "0.64662987", "0.64662987", "0.64662987", "0.64662987", "0.64133537", "0.63919425", "0.6374648", "0.6361144", "0.6291102", "0.62765837", "0.6262985", "0.6251369", "0.6229964", "0.6189388", "0.61873686", "0.6180899", "0.61747265", "0.6156933", "0.6153347", "0.6127814", "0.6109971", "0.61062306", "0.60921335", "0.6083546", "0.6069078", "0.6043147", "0.60244435", "0.6015934", "0.6003941", "0.5996379", "0.59929675", "0.59861875", "0.59775543", "0.59526503", "0.5945211", "0.59416384", "0.59255683", "0.59200656", "0.591579", "0.5903478", "0.58897454", "0.58825135", "0.5880665", "0.58783555", "0.5850345", "0.58281195", "0.5819274", "0.5812664", "0.5798924", "0.5772966", "0.5764524", "0.5761115", "0.57603604", "0.57599163", "0.57464087", "0.5741121", "0.57399696", "0.5722037", "0.57055575", "0.5704641", "0.56866086", "0.5684627", "0.56820905", "0.567567", "0.5675034", "0.5674032", "0.56724757", "0.5669666", "0.5663396", "0.5634842", "0.563311", "0.5625594", "0.562543", "0.56212723", "0.5600117", "0.5594132", "0.55914664", "0.5574811", "0.5568693", "0.5567329", "0.55568635" ]
0.746237
0
Run executes the agent using the given config and backend. It uses SQS for its internal queues. When the function finishes it returns an exit code of 0 if the agent terminated gracefully, either by receiving a TERM signal or because it passed more time than configured without reading a message.
func Run(cfg config.Config, store storage.Store, back backend.Backend, logger log.Logger) int { // Build queue writer. qw, err := sqs.NewWriter(cfg.SQSWriter.ARN, cfg.SQSWriter.Endpoint, logger) if err != nil { logger.Errorf("error creating SQS writer: %+v", err) return 1 } // Build queue reader. var maxTimeNoMsg *time.Duration if cfg.Agent.MaxNoMsgsInterval > 0 { t := time.Duration(cfg.Agent.MaxNoMsgsInterval) * time.Second maxTimeNoMsg = &t } // A nil queue.MessageProcessor is passed as argument because // RunWithQueues will set it before starting reading messages. qr, err := sqs.NewReader(logger, cfg.SQSReader, maxTimeNoMsg, nil) if err != nil { logger.Errorf("error creating SQS reader: %+v", err) return 1 } // Run agent with SQS queues. return RunWithQueues(cfg, store, back, qw, qr, logger) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RunLoop(regInfo *RegistrationInfo, regInfoUpdatesCh <-chan string, eventsChannel chan<- *Event, regChannel chan<- time.Time) {\n\n\tlogging.Info(\"Initializing SQS client.\", nil)\n\tsvc := getSQSClient(regInfo)\n\tqueue := regInfo.ActionQueueEndpoint\n\n\tshouldLogError := true\n\tnumFailures := 0\n\tfor {\n\t\tshouldSleep := true\n\t\tselect {\n\n\t\t// Check if the registration info has changed and reinitialize the SQS client if required.\n\t\tcase <-regInfoUpdatesCh:\n\t\t\tlogging.Info(\"Initializing SQS client.\", nil)\n\t\t\tsvc = getSQSClient(regInfo)\n\t\t\tqueue = regInfo.ActionQueueEndpoint\n\n\t\tdefault:\n\t\t\tt1 := time.Now()\n\t\t\tif resp, err := getMessages(svc, queue); err == nil {\n\t\t\t\tshouldLogError = true\n\t\t\t\tnumFailures = 0\n\t\t\t\tUpdateStatus(QueuePollingSucceeded)\n\t\t\t\tlogging.Debug(\"Received messages.\", logging.Fields{\"count\": len(resp.Messages)})\n\n\t\t\t\tfor _, msg := range resp.Messages {\n\t\t\t\t\tbodyStr := *msg.Body\n\t\t\t\t\tmessageId := *msg.MessageId\n\n\t\t\t\t\tagentId, ok := msg.MessageAttributes[\"agentId\"]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogging.Error(\"Received message does not have agentId attribute.\", logging.Fields{\"msgId\": messageId})\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tif regInfo.AgentId == *agentId.StringValue {\n\t\t\t\t\t\tlogging.Debug(\"Received a message for me. Checking message integrity.\", nil)\n\n\t\t\t\t\t\tsignature, ok := msg.MessageAttributes[\"signature\"]\n\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\tlogging.Error(\"Received message does not have signature attribute.\", logging.Fields{\"msgId\": messageId})\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif valid, err := VerifyMessage(bodyStr, *signature.StringValue); valid && err == nil {\n\t\t\t\t\t\t\tvar event Event\n\t\t\t\t\t\t\terr = json.Unmarshal([]byte(bodyStr), &event)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlogging.Error(\"Could not deserialize the SQS message.\", logging.Fields{\"error\": err})\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tevent.SQSMessageId = messageId\n\t\t\t\t\t\t\t\tevent.ReceiptHandle = *msg.ReceiptHandle\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Now that the message signature is verified, recheck the agent id from the message payload.\n\t\t\t\t\t\t\t// This should guard against the cases where someone would have changed the message attributes\n\t\t\t\t\t\t\t// and set a different agent id in the attributes but didn't tamper with the message.\n\t\t\t\t\t\t\tif regInfo.AgentId == event.AgentId {\n\n\t\t\t\t\t\t\t\t// Keep a buffer of 2 seconds in addition to the timeout received in the event.\n\t\t\t\t\t\t\t\t// This helps to avoid race conditions while handling the action timeout.\n\t\t\t\t\t\t\t\tchangeMessageVisibility(svc, queue, event.ReceiptHandle, int64(event.Timeout+2))\n\n\t\t\t\t\t\t\t\t// Push into a separate queue so that the action thread picks the message.\n\t\t\t\t\t\t\t\tlogging.Debug(\"Pushing the message for processing\", logging.Fields{\"eventId\": event.EventId})\n\t\t\t\t\t\t\t\teventsChannel <- &event\n\t\t\t\t\t\t\t\tshouldSleep = false\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// This means something is wrong. Ideally the agent id in message attribute and\n\t\t\t\t\t\t\t\t// message payload should always match but otherwise, it's an issue.\n\t\t\t\t\t\t\t\t// Don't process this message and delete it immediately.\n\t\t\t\t\t\t\t\tlogging.Error(\"Something is wrong!! Agent id present in the message attributes matches but \"+\n\t\t\t\t\t\t\t\t\t\"agent id in event does not match. Deleting the message.\",\n\t\t\t\t\t\t\t\t\tlogging.Fields{\"msgId\": messageId})\n\t\t\t\t\t\t\t\tDeleteMessage(regInfo, msg.ReceiptHandle)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlogging.Error(\"Could not verify the message with signature so deleting the message.\",\n\t\t\t\t\t\t\t\tlogging.Fields{\"msgId\": messageId, \"error\": err})\n\t\t\t\t\t\t\tDeleteMessage(regInfo, msg.ReceiptHandle)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogging.Debug(\"Releasing a message which is not for me.\", logging.Fields{\"msgId\": messageId})\n\t\t\t\t\t\tchangeMessageVisibility(svc, queue, *msg.ReceiptHandle, int64(0))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if shouldLogError {\n\t\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t\t// Message from an error.\n\t\t\t\tlogging.Error(\"Could not receive messages from SQS.\", logging.Fields{\n\t\t\t\t\t\"error\": err,\n\t\t\t\t\t\"response\": resp,\n\t\t\t\t})\n\t\t\t\tshouldLogError = false\n\t\t\t\tnumFailures += 1\n\t\t\t} else {\n\t\t\t\tnumFailures += 1\n\n\t\t\t\t// Re-trigger the registration if we fail to poll the queue 10 times in succession.\n\t\t\t\tif numFailures == numSQSFailuresBeforeReregistration {\n\t\t\t\t\tnumFailures = 0\n\t\t\t\t\tshouldLogError = true\n\t\t\t\t\tregChannel <- time.Now()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sleep if required. We make sure there is at least sqsPollingFrequencySecs gap between successive SQS polls.\n\t\t\tif shouldSleep {\n\t\t\t\tif duration := t1.Add(time.Second * sqsPollingFrequencySecs).Sub(time.Now()); duration > 0 {\n\t\t\t\t\tlogging.Debug(\"Sleeping between two polls.\", logging.Fields{\"duration\": duration})\n\t\t\t\t\ttime.Sleep(duration)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Handler) Run() (err error) {\n\n\t// Connect to activemq\n\tclient, err := h.getAMQPClient()\n\tif err != nil {\n\t\tlog.Logger.Fatal(\"Dialing AMQP server:\", err)\n\t\treturn\n\t}\n\tlog.Logger.Info(\"Connected\")\n\n\t// Open queue channel for reading\n\tchannel, err := client.Channel()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tqueue, err := channel.Consume(\n\t\th.RabbitMQ.Queue,\n\t\th.RabbitMQ.Consumer,\n\t\tfalse,\n\t\tfalse,\n\t\ttrue,\n\t\tfalse,\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// process messages\n\tfor message := range queue {\n\n\t\tfiksMsg := fiksMessage{&message}\n\n\t\tlog := fiksMsg.LoggerWithFields()\n\t\terr = h.handleAMQMessage(fiksMsg)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to handle AMQP message: %s\", fiksMsg.GetMeldingID(), err)\n\t\t} else {\n\t\t\tlog.Infof(\"Successfully handled message\")\n\t\t}\n\n\t\t// Always ack.\n\t\t//TODO: Consider alternate processing on errors\n\t\t//\t\tI.e. if report failure fails.\n\t\tmessage.Ack(true)\n\t}\n\n\t// TODO: consider reconnecting rather than shutting down.\n\t// connection broken, return err.\n\treturn\n}", "func Run() (err error) {\n\n\t// Register Message Queue handler\n\thandler := mq.MsgHandler{Handler: msgHandler, UserData: nil}\n\tsbi.handlerId, err = sbi.mqLocal.RegisterHandler(handler)\n\tif err != nil {\n\t\tlog.Error(\"Failed to register local Msg Queue listener: \", err.Error())\n\t\treturn err\n\t}\n\tlog.Info(\"Registered local Msg Queue listener\")\n\n\treturn nil\n}", "func (q *queueDriverDefault) Run(ctx context.Context) error {\n\tvar (\n\t\tmsg etl.Message\n\t\tsize int\n\t\terr error\n\t\tok bool\n\t)\n\tfor {\n\t\tfor true {\n\t\t\t// dequeue message\n\t\t\tmsg, size, ok = q.dequeue()\n\t\t\t// if no message was dequeued, break and wait for new message in a queue\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// send dequeued message to output channel\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tcase q.outputCh <- msg:\n\t\t\t}\n\n\t\t\t// call dequeue hooks\n\t\t\terr = q.callDequeueHooks(ctx, size)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// wait until new item is enqueued\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-q.enqueuedCh:\n\t\t}\n\t}\n\n\treturn nil\n}", "func Go(params Params) {\n\tlog.Println(\"starting worker...\")\n\n\tawsConfig := awsconfig.Config{\n\t\tRegion: params.Region,\n\t\tEndpointURL: &params.Endpoint,\n\t}\n\n\tqueueURL := fmt.Sprintf(\"%s/%s\", params.Endpoint, params.QueueName)\n\n\tconfig := aws.SQSConfig{\n\t\tConfig: awsConfig,\n\t\tQueueURL: queueURL,\n\t}\n\n\tlog.Println(config)\n\tsub, err := aws.NewSubscriber(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terrc := make(chan error, 1)\n\tgo handleError(errc)\n\n\tmsgs := sub.Start()\n\tdefer sub.Stop()\n\n\tp := Processor{}\n\n\tfor msg := range msgs {\n\t\tgo p.Process(msg)\n\t}\n}", "func RunWithQueues(cfg config.Config, store storage.Store, back backend.Backend, statesQueue queue.Writer, jobsQueue AgentQueueReader, logger log.Logger) int {\n\t// Build state updater.\n\tstateUpdater := stateupdater.New(statesQueue)\n\tupdater := struct {\n\t\t*stateupdater.Updater\n\t\tstorage.Store\n\t}{stateUpdater, store}\n\n\t// Build job runner.\n\tjrunner, err := newJobRunner(cfg, back, updater, logger)\n\tif err != nil {\n\t\tlogger.Errorf(\"error creating job runner: %+v\", err)\n\t\treturn 1\n\t}\n\n\t// Set queue's message processor.\n\tjobsQueue.SetMessageProcessor(jrunner)\n\n\t// Run agent.\n\tif err := run(cfg, jrunner, updater, jobsQueue, logger); err != nil {\n\t\tlogger.Errorf(\"error running agent: %+v\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}", "func (aq *AwardQueue) Run(ctx context.Context) error {\n\tctx, span := beeline.StartSpan(ctx, \"awardqueue\")\n\tdefer span.Send()\n\n\toriginalDB := aq.db\n\tdefer func() { aq.db = originalDB }()\n\n\treturn aq.db.Transaction(func(tx *pop.Connection) error {\n\t\t// ensure that all parts of the AQ run inside the transaction\n\t\taq.db = tx\n\n\t\taq.logger.Info(\"Waiting to acquire advisory lock...\")\n\t\terr := waitForLock(ctx, tx, awardQueueLockID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\taq.logger.Info(\"Acquired pg_advisory_xact_lock\")\n\n\t\tif err := aq.assignPerformanceBands(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// This method should also return an error\n\t\taq.assignShipments(ctx)\n\t\treturn nil\n\t})\n\n}", "func Run(qChan fTypes.QChan, cfg config.Config) {\n\tbg := qChan.Data.Join()\n\tinStr, err := cfg.String(\"handler.log.inputs\")\n\tif err != nil {\n\t\tinStr = \"\"\n\t}\n\tinputs := strings.Split(inStr, \",\")\n\tfor {\n\t\tval := bg.Recv()\n\t\tswitch val.(type) {\n\t\tcase qtypes.Message:\n\t\t\tqm := val.(qtypes.Message)\n\t\t\tif len(inputs) != 0 && ! qutils.IsInput(inputs, qm.Source) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Printf(\"%s %-7s sType:%-6s sName:[%d]%-10s %s:%s\\n\", qm.TimeString(), qm.LogString(), qm.Type, qm.SourceID, qm.Source, qm.Name, qm.Msg)\n\t\t}\n\t}\n}", "func Run() (err error) {\n\n\terr = sm.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = as.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start Swagger API Manager (provider)\n\terr = apiMgr.Start(true, false)\n\tif err != nil {\n\t\tlog.Error(\"Failed to start Swagger API Manager with error: \", err.Error())\n\t\treturn err\n\t}\n\tlog.Info(\"Swagger API Manager started\")\n\n\t// Add module Swagger APIs\n\terr = apiMgr.AddApis()\n\tif err != nil {\n\t\tlog.Error(\"Failed to add Swagger APIs with error: \", err.Error())\n\t\treturn err\n\t}\n\tlog.Info(\"Swagger APIs successfully added\")\n\n\t// Register Message Queue handler\n\thandler := mq.MsgHandler{Handler: msgHandler, UserData: nil}\n\thandlerId, err = mqLocal.RegisterHandler(handler)\n\tif err != nil {\n\t\tlog.Error(\"Failed to register local Msg Queue listener: \", err.Error())\n\t\treturn err\n\t}\n\tlog.Info(\"Registered local Msg Queue listener\")\n\n\t// Initalize metric store\n\tupdateStoreName()\n\n\treturn nil\n}", "func (a *Agent) Run(ctx context.Context) error {\n\ta.Context = ctx\n\tlog.Printf(\"I! [agent] Config: Interval:%s, Quiet:%#v, Hostname:%#v, \"+\n\t\t\"Flush Interval:%s\",\n\t\ta.Config.Agent.Interval.Duration, a.Config.Agent.Quiet,\n\t\ta.Config.Agent.Hostname, a.Config.Agent.FlushInterval.Duration)\n\n\tlog.Printf(\"D! [agent] Initializing plugins\")\n\terr := a.initPlugins()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstartTime := time.Now()\n\tlog.Printf(\"D! [agent] Connecting outputs\")\n\tnext, ou, err := a.startOutputs(ctx, a.Config.Outputs)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.ou = ou\n\tvar apu []*processorUnit\n\tvar au *aggregatorUnit\n\tif len(a.Config.Aggregators) != 0 {\n\t\taggC := next\n\t\tif len(a.Config.AggProcessors) != 0 {\n\t\t\taggC, apu, err = a.startProcessors(next, a.Config.AggProcessors)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tnext, au, err = a.startAggregators(aggC, next, a.Config.Aggregators)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar pu []*processorUnit\n\tif len(a.Config.Processors) != 0 {\n\t\tnext, pu, err = a.startProcessors(next, a.Config.Processors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tiu, err := a.startInputs(next, a.Config.Inputs)\n\ta.iu = iu\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := a.runOutputs(ou)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"E! [agent] Error running outputs: %v\", err)\n\t\t}\n\t}()\n\n\tif au != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terr := a.runProcessors(apu)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error running processors: %v\", err)\n\t\t\t}\n\t\t}()\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terr := a.runAggregators(startTime, au)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error running aggregators: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\tif pu != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terr := a.runProcessors(pu)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error running processors: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := a.runInputs(ctx, startTime, iu)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"E! [agent] Error running inputs: %v\", err)\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tlog.Printf(\"D! [agent] Stopped Successfully\")\n\treturn err\n}", "func runAllQueues(conf *config.Config) {\n\twaitFor(\n\t\tfunc() { watchPageReview(conf) },\n\t\tfunc() { watchDigitizedScans(conf) },\n\t\tfunc() {\n\t\t\t// Jobs which are exclusively disk IO are in the first runner to avoid\n\t\t\t// too much FS stuff hapenning concurrently\n\t\t\twatchJobTypes(conf,\n\t\t\t\tmodels.JobTypeArchiveBackups,\n\t\t\t\tmodels.JobTypeMoveDerivatives,\n\t\t\t\tmodels.JobTypeSyncRecursive,\n\t\t\t\tmodels.JobTypeVerifyRecursive,\n\t\t\t\tmodels.JobTypeKillDir,\n\t\t\t\tmodels.JobTypeWriteBagitManifest,\n\t\t\t)\n\t\t},\n\t\tfunc() {\n\t\t\t// Jobs which primarily use CPU are grouped next, so we aren't trying to\n\t\t\t// share CPU too much\n\t\t\twatchJobTypes(conf,\n\t\t\t\tmodels.JobTypePageSplit,\n\t\t\t\tmodels.JobTypeMakeDerivatives,\n\t\t\t)\n\t\t},\n\t\tfunc() {\n\t\t\t// Fast - but not instant - jobs are here: file renaming, hard-linking,\n\t\t\t// running templates for very simple XML output, etc. These typically\n\t\t\t// take very little CPU or disk IO, but they aren't \"critical\" jobs that\n\t\t\t// need to be real-time.\n\t\t\twatchJobTypes(conf,\n\t\t\t\tmodels.JobTypeBuildMETS,\n\t\t\t\tmodels.JobTypeCreateBatchStructure,\n\t\t\t\tmodels.JobTypeMakeBatchXML,\n\t\t\t\tmodels.JobTypeRenameDir,\n\t\t\t\tmodels.JobTypeCleanFiles,\n\t\t\t\tmodels.JobTypeRemoveFile,\n\t\t\t\tmodels.JobTypeWriteActionLog,\n\t\t\t\tmodels.JobTypeRenumberPages,\n\t\t\t\tmodels.JobTypeValidateTagManifest,\n\t\t\t\tmodels.JobTypeMarkBatchLive,\n\t\t\t)\n\t\t},\n\t\tfunc() {\n\t\t\t// Extremely fast data-setting jobs get a custom runner that operates\n\t\t\t// every second to ensure nearly real-time updates to things like a job's\n\t\t\t// workflow state\n\t\t\tvar r = jobs.NewRunner(conf, logLevel,\n\t\t\t\tmodels.JobTypeSetIssueWS,\n\t\t\t\tmodels.JobTypeSetIssueBackupLoc,\n\t\t\t\tmodels.JobTypeSetIssueLocation,\n\t\t\t\tmodels.JobTypeFinalizeBatchFlaggedIssue,\n\t\t\t\tmodels.JobTypeEmptyBatchFlaggedIssuesList,\n\t\t\t\tmodels.JobTypeIgnoreIssue,\n\t\t\t\tmodels.JobTypeSetBatchStatus,\n\t\t\t\tmodels.JobTypeSetBatchNeedsStagingPurge,\n\t\t\t\tmodels.JobTypeSetBatchLocation,\n\t\t\t\tmodels.JobTypeIssueAction,\n\t\t\t\tmodels.JobTypeBatchAction,\n\t\t\t\tmodels.JobTypeCancelJob,\n\t\t\t\tmodels.JobTypeDeleteBatch,\n\t\t\t)\n\t\t\taddRunner(r)\n\t\t\tr.Watch(time.Second * 1)\n\t\t},\n\t)\n}", "func run(cfg config.Config, jrunner *jobrunner.Runner, updater api.CheckStateUpdater, jobsQueue queue.Reader, logger log.Logger) error {\n\t// Build metrics component.\n\tmetrics := metrics.NewMetrics(logger, cfg.DataDog, jrunner)\n\n\t// Create a context to orchestrate the shutdown of the\n\t// different components.\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t// Initialize check cancel stream if an endpoint is provided.\n\tvar (\n\t\terr error\n\t\tstreamDone <-chan error\n\t)\n\tif cfg.Stream.Endpoint == \"\" {\n\t\tlogger.Infof(\"check cancel stream disabled\")\n\t} else {\n\t\tre := retryer.NewRetryer(cfg.Stream.Retries, cfg.Stream.RetryInterval, logger)\n\t\t// metrics is passed as a stream message processor to\n\t\t// abort checks.\n\t\tstream := stream.New(logger, metrics, re, cfg.Stream.Endpoint)\n\t\tstreamDone, err = stream.ListenAndProcess(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"stream start: %w\", err)\n\t\t}\n\t}\n\n\t// Build stats components that exposes information about the\n\t// agent.\n\tstats := struct {\n\t\t*jobrunner.Runner\n\t\tqueue.Reader\n\t}{jrunner, jobsQueue}\n\n\t// Start agent's HTTP API.\n\tapi := api.New(logger, updater, stats)\n\trouter := httprouter.New()\n\thttpapi.NewREST(logger, api, router)\n\n\tsrv := http.Server{Handler: router}\n\n\thttpDone := make(chan error)\n\tgo func() {\n\t\tvar err error\n\t\tif cfg.API.Listener != nil {\n\t\t\terr = srv.Serve(cfg.API.Listener)\n\t\t} else {\n\t\t\tsrv.Addr = cfg.API.Port\n\t\t\terr = srv.ListenAndServe()\n\t\t}\n\t\thttpDone <- err\n\t\tclose(httpDone)\n\t}()\n\n\t// Wait while the agent runs.\n\tqrdone := jobsQueue.StartReading(ctx)\n\tmetricsDone := metrics.StartPolling(ctx)\n\n\tvar agentAddr string\n\tif cfg.API.Listener != nil {\n\t\tagentAddr = cfg.API.Listener.Addr().String()\n\t} else {\n\t\tagentAddr = cfg.API.Port\n\t}\n\tlogger.Infof(\"agent running on address %s\", agentAddr)\n\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)\n\n\tselect {\n\tcase <-sig:\n\t\t// Signal SQS queue reader to stop reading messages\n\t\t// from the queue.\n\t\tlogger.Infof(\"SIG received, stopping agent\")\n\t\tcancel()\n\tcase err := <-httpDone:\n\t\tlogger.Errorf(\"error running agent: %+v\", err)\n\t\tcancel()\n\tcase err := <-qrdone:\n\t\tcancel()\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, queue.ErrMaxTimeNoRead) && !errors.Is(err, context.Canceled) {\n\t\t\t\treturn fmt.Errorf(\"agent run: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Wait for all pending jobs to finish.\n\tlogger.Infof(\"waiting for checks to finish\")\n\terr = <-qrdone\n\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\tlogger.Errorf(\"error waiting for checks to finish %+v\", err)\n\t}\n\n\t// Wait for metrics to stop polling.\n\tlogger.Debugf(\"waiting for metrics to stop\")\n\t<-metricsDone\n\n\t// Stop listening API HTTP requests.\n\tlogger.Debugf(\"stop listening API requests\")\n\terr = srv.Shutdown(context.Background())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"http server shutdown: %w\", err)\n\t}\n\n\t// Wait for HTTP API to shutdown.\n\terr = <-httpDone\n\tif err != nil && !errors.Is(err, http.ErrServerClosed) {\n\t\treturn fmt.Errorf(\"http server shutdown wait: %w\", err)\n\t}\n\n\t// Wait for stream to finish.\n\tif streamDone != nil {\n\t\tlogger.Debugf(\"waiting for stream to stop\")\n\t\terr = <-streamDone\n\t\tif err != nil && !errors.Is(err, context.Canceled) {\n\t\t\treturn fmt.Errorf(\"stream stop wait: %w\", err)\n\t\t}\n\t}\n\n\tlogger.Infof(\"agent finished gracefully\")\n\treturn nil\n}", "func (a *Agent) Run() (err error) {\n\talog.Info(\"Starting up agent...\")\n\t// start listening for ipc messages\n\t_ = a.notificationHandler.Start()\n\n\tcfg := a.Context.cfg\n\n\tf := a.cpuProfileStart()\n\tif f != nil {\n\t\tdefer a.cpuProfileStop(f)\n\t}\n\n\tgo a.intervalMemoryProfile()\n\n\tif cfg.ConnectEnabled {\n\t\tgo a.connect()\n\t}\n\n\talog.Debug(\"Starting Plugins.\")\n\ta.startPlugins()\n\n\tif err != nil {\n\t\talog.WithError(err).Error(\"failed to start troubleshooting handler\")\n\t}\n\n\tif a.Context.eventSender != nil {\n\t\tif err := a.Context.eventSender.Start(); err != nil {\n\t\t\talog.WithError(err).Error(\"failed to start event sender\")\n\t\t}\n\t}\n\n\tif a.metricsSender != nil {\n\t\tif err := a.metricsSender.Start(); err != nil {\n\t\t\talog.WithError(err).Error(\"failed to start metrics subsystem\")\n\t\t}\n\t}\n\n\t// Timers\n\treapInventoryTimer := time.NewTicker(cfg.FirstReapInterval)\n\tsendInventoryTimer := time.NewTimer(cfg.SendInterval) // Send any deltas every X seconds\n\tdebugTimer := time.Tick(time.Duration(a.Context.Config().DebugLogSec) * time.Second)\n\n\t//Remove send timer\n\tif !a.shouldSendInventory() {\n\t\tsendInventoryTimer.Stop()\n\t\treapInventoryTimer.Stop()\n\t\talog.Info(\"inventory submission disabled\")\n\t}\n\n\t// Timer to engage the process of deleting entities that haven't been reported information during this time\n\tremoveEntitiesPeriod, err := time.ParseDuration(a.Context.Config().RemoveEntitiesPeriod)\n\tif removeEntitiesPeriod <= 0 || err != nil {\n\t\tremoveEntitiesPeriod = defaultRemoveEntitiesPeriod\n\t\terr = nil\n\t}\n\n\tremoveEntitiesTicker := time.NewTicker(removeEntitiesPeriod)\n\treportedEntities := map[string]bool{}\n\n\t// Wait no more than this long for initial inventory reap even if some plugins haven't reported data\n\tinitialReapTimeout := time.NewTimer(config.INITIAL_REAP_MAX_WAIT_SECONDS * time.Second)\n\n\t// keep track of which plugins have phone home\n\tidsReporting := make(map[ids.PluginID]bool)\n\tdistinctPlugins := make(map[ids.PluginID]Plugin)\n\tfor _, p := range a.plugins {\n\t\tdistinctPlugins[p.Id()] = p\n\t}\n\n\t// Register local entity inventory\n\t// This will make the agent submitting unsent deltas from a previous execution (e.g. if an inventory was reaped\n\t// but the agent was restarted before sending it)\n\tif _, ok := a.inventories[a.Context.EntityKey()]; !ok {\n\t\t_ = a.registerEntityInventory(entity.NewFromNameWithoutID(a.Context.EntityKey()))\n\t}\n\n\texit := make(chan struct{})\n\n\tgo func() {\n\t\t<-a.Context.Ctx.Done()\n\n\t\ta.exitGracefully(sendInventoryTimer, reapInventoryTimer, removeEntitiesTicker)\n\n\t\tclose(exit)\n\n\t\t// Should not reach here, just a guard.\n\t\t//<-time.After(service.GracefulExitTimeout)\n\t\t//log.Warn(\"graceful stop time exceeded... forcing stop\")\n\t\t//os.Exit(0)\n\t}()\n\n\t// three states\n\t// -- reading data to write to json\n\t// -- reaping\n\t// -- sending\n\t// ready to consume events\n\tfor {\n\t\tselect {\n\t\tcase <-exit:\n\t\t\treturn nil\n\t\t\t// agent gets notified about active entities\n\t\tcase ent := <-a.Context.activeEntities:\n\t\t\treportedEntities[ent] = true\n\t\t\t// read data from plugin and write json\n\t\tcase data := <-a.Context.ch:\n\t\t\t{\n\t\t\t\tidsReporting[data.Id] = true\n\n\t\t\t\tif data.Id == hostAliasesPluginID {\n\t\t\t\t\t_ = a.updateIDLookupTable(data.Data)\n\t\t\t\t}\n\n\t\t\t\tentityKey := data.Entity.Key.String()\n\t\t\t\tif _, ok := a.inventories[entityKey]; !ok {\n\t\t\t\t\t_ = a.registerEntityInventory(data.Entity)\n\t\t\t\t}\n\n\t\t\t\tif !data.NotApplicable {\n\t\t\t\t\tif err := a.storePluginOutput(data); err != nil {\n\t\t\t\t\t\talog.WithError(err).Error(\"problem storing plugin output\")\n\t\t\t\t\t}\n\t\t\t\t\ta.inventories[entityKey].needsReaping = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-reapInventoryTimer.C:\n\t\t\t{\n\t\t\t\tfor _, inventory := range a.inventories {\n\t\t\t\t\tif !a.inv.readyToReap {\n\t\t\t\t\t\tif len(distinctPlugins) <= len(idsReporting) {\n\t\t\t\t\t\t\talog.Debug(\"Signalling initial reap.\")\n\t\t\t\t\t\t\ta.inv.readyToReap = true\n\t\t\t\t\t\t\tinventory.needsCleanup = true\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpluginIds := make([]ids.PluginID, 0)\n\t\t\t\t\t\t\tfor plgId := range distinctPlugins {\n\t\t\t\t\t\t\t\tif !idsReporting[plgId] {\n\t\t\t\t\t\t\t\t\tpluginIds = append(pluginIds, plgId)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\talog.WithField(\"pluginIds\", pluginIds).Debug(\"Still waiting on plugins.\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif a.inv.readyToReap && inventory.needsReaping {\n\t\t\t\t\t\treapInventoryTimer.Stop()\n\t\t\t\t\t\treapInventoryTimer = time.NewTicker(cfg.ReapInterval)\n\t\t\t\t\t\tinventory.reaper.Reap()\n\t\t\t\t\t\tif inventory.needsCleanup {\n\t\t\t\t\t\t\tinventory.reaper.CleanupOldPlugins(a.oldPlugins)\n\t\t\t\t\t\t\tinventory.needsCleanup = false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinventory.needsReaping = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-initialReapTimeout.C:\n\t\t\t// If we've waited too long and still not received data from all plugins, we can just send what we have.\n\t\t\tif !a.inv.readyToReap {\n\t\t\t\talog.Debug(\"Maximum initial reap delay exceeded - marking inventory as ready to report.\")\n\t\t\t\ta.inv.readyToReap = true\n\t\t\t\tfor _, inventory := range a.inventories {\n\t\t\t\t\tinventory.needsCleanup = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-sendInventoryTimer.C:\n\t\t\ta.sendInventory(sendInventoryTimer)\n\t\tcase <-debugTimer:\n\t\t\t{\n\t\t\t\tdebugInfo, err := a.debugProvide()\n\t\t\t\tif err != nil {\n\t\t\t\t\talog.WithError(err).Error(\"debug error\")\n\t\t\t\t} else if debugInfo != \"\" {\n\t\t\t\t\talog.Debug(debugInfo)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-removeEntitiesTicker.C:\n\t\t\tpastPeriodReportedEntities := reportedEntities\n\t\t\treportedEntities = map[string]bool{} // reset the set of reporting entities the next period\n\t\t\talog.Debug(\"Triggered periodic removal of outdated entities.\")\n\t\t\ta.removeOutdatedEntities(pastPeriodReportedEntities)\n\t\t}\n\t}\n}", "func main() {\n sess := session.Must(session.NewSessionWithOptions(session.Options{\n SharedConfigState: session.SharedConfigEnable,\n }))\n\n svc := sqs.New(sess)\n\n // URL to our queue\n qURL := \"QueueURL\"\n\n result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{\n AttributeNames: []*string{\n aws.String(sqs.MessageSystemAttributeNameSentTimestamp),\n },\n MessageAttributeNames: []*string{\n aws.String(sqs.QueueAttributeNameAll),\n },\n QueueUrl: &qURL,\n MaxNumberOfMessages: aws.Int64(10),\n VisibilityTimeout: aws.Int64(60), // 60 seconds\n WaitTimeSeconds: aws.Int64(0),\n })\n if err != nil {\n fmt.Println(\"Error\", err)\n return\n }\n if len(result.Messages) == 0 {\n fmt.Println(\"Received no messages\")\n return\n }\n\n fmt.Printf(\"Success: %+v\\n\", result.Messages)\n}", "func Run(endpoint string, handler *Handler) error {\n\n\tprocessor := processor.NewTransactionProcessor(endpoint)\n\tprocessor.AddHandler(handler)\n\tprocessor.ShutdownOnSignal(syscall.SIGINT, syscall.SIGTERM)\n\treturn processor.Start()\n}", "func Handler(messageOutgoingQueue <-chan []string, s Statser) {\n\tregion = awsFormatRegion(regionString)\n\tsqsConn := newSqsConn(*accessKey, *secretKey, region, *queueName)\n\tfor m := range messageOutgoingQueue {\n\t\t_, err := sqsConn.SendMessageBatchString(m)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"SQS batch error: %s\\n\", err)\n\t\t}\n\t\ts.IncrSent(int64(len(m)))\n\t}\n}", "func (wh *Webhooks) Run(ctx context.Context) {\n\twh.workersNum.Inc()\n\tdefer wh.workersNum.Dec()\n\tfor {\n\t\tenqueuedItem, err := wh.queue.Pop(ctx)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\twh.queuedNum.Dec()\n\t\ttmpFile, err := wh.openStoredRequestFile(enqueuedItem)\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to process\", enqueuedItem.RequestFile, \"-\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\twh.processRequestAsync(ctx, enqueuedItem.Manifest, tmpFile)\n\t\t_ = tmpFile.Close()\n\t\t_ = os.RemoveAll(tmpFile.Name())\n\t}\n}", "func (q *ChannelQueue) Run(atShutdown, atTerminate func(func())) {\n\tpprof.SetGoroutineLabels(q.baseCtx)\n\tatShutdown(q.Shutdown)\n\tatTerminate(q.Terminate)\n\tlog.Debug(\"ChannelQueue: %s Starting\", q.name)\n\t_ = q.AddWorkers(q.workers, 0)\n}", "func (s *Sinker) Run() {\n\tvar err error\n\tvar newCfg *config.Config\n\tdefer func() {\n\t\ts.stopped <- struct{}{}\n\t}()\n\tif cmdOps.PushGatewayAddrs != \"\" {\n\t\taddrs := strings.Split(cmdOps.PushGatewayAddrs, \",\")\n\t\ts.pusher = statistics.NewPusher(addrs, cmdOps.PushInterval, httpAddr)\n\t\tif err = s.pusher.Init(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tgo s.pusher.Run()\n\t}\n\tif s.rcm == nil {\n\t\tif _, err = os.Stat(cmdOps.LocalCfgFile); err == nil {\n\t\t\tif newCfg, err = config.ParseLocalCfgFile(cmdOps.LocalCfgFile); err != nil {\n\t\t\t\tutil.Logger.Fatal(\"config.ParseLocalCfgFile failed\", zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tutil.Logger.Fatal(\"expect --local-cfg-file or --nacos-dataid\")\n\t\t\treturn\n\t\t}\n\t\tif err = newCfg.Normallize(); err != nil {\n\t\t\tutil.Logger.Fatal(\"newCfg.Normallize failed\", zap.Error(err))\n\t\t\treturn\n\t\t}\n\t\tif err = s.applyConfig(newCfg); err != nil {\n\t\t\tutil.Logger.Fatal(\"s.applyConfig failed\", zap.Error(err))\n\t\t\treturn\n\t\t}\n\t\t<-s.ctx.Done()\n\t} else {\n\t\tif cmdOps.NacosServiceName != \"\" {\n\t\t\tgo s.rcm.Run()\n\t\t}\n\t\t// Golang <-time.After() is not garbage collected before expiry.\n\t\tticker := time.NewTicker(10 * time.Second)\n\t\tdefer ticker.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.ctx.Done():\n\t\t\t\tutil.Logger.Info(\"Sinker.Run quit due to context has been canceled\")\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tif newCfg, err = s.rcm.GetConfig(); err != nil {\n\t\t\t\t\tutil.Logger.Error(\"s.rcm.GetConfig failed\", zap.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err = newCfg.Normallize(); err != nil {\n\t\t\t\t\tutil.Logger.Error(\"newCfg.Normallize failed\", zap.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err = s.applyConfig(newCfg); err != nil {\n\t\t\t\t\tutil.Logger.Error(\"s.applyConfig failed\", zap.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (s *SQSServer) run(pollctx, taskctx context.Context, q *queue, visibilityTimeout int32) {\n\tfailAttempts := 0\n\tbackoff := time.Duration(0)\n\tfor {\n\t\tselect {\n\t\tcase <-pollctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tif backoff.Seconds() > 0 {\n\t\t\t\ttime.Sleep(backoff)\n\t\t\t}\n\n\t\t\tattributeNames := []types.QueueAttributeName{}\n\t\t\tfor _, attr := range q.attributesToReturn {\n\t\t\t\tattributeNames = append(attributeNames, types.QueueAttributeName(attr))\n\t\t\t}\n\t\t\t// Receive only one message at a time to ensure job load is spread over all machines\n\t\t\treqInput := &sqs.ReceiveMessageInput{\n\t\t\t\tQueueUrl: &q.url,\n\t\t\t\tMaxNumberOfMessages: int32(q.ReadBatch),\n\t\t\t\tWaitTimeSeconds: 20,\n\t\t\t\tAttributeNames: attributeNames,\n\t\t\t\tMessageAttributeNames: q.attributesToReturn,\n\t\t\t}\n\n\t\t\tresp, err := s.sqsSrv(q.QueueConf).ReceiveMessage(pollctx, reqInput)\n\t\t\tif err != nil {\n\t\t\t\tq.Metrics(MetricPollFailure, 1, int(atomic.LoadInt32(&q.inprocess)))\n\t\t\t\tfailAttempts++\n\t\t\t\tif failAttempts > 20 {\n\t\t\t\t\tpanic(fmt.Sprintf(\" %s - Failed to poll for too long. Panicing (not picnicing).\", q.Name))\n\t\t\t\t}\n\t\t\t\tbackoff = time.Duration(math.Min(float64(failAttempts*20), 120))\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tbackoff = time.Duration(0)\n\t\t\t\tfailAttempts = 0\n\t\t\t}\n\n\t\t\tstart := time.Now()\n\t\t\tinflight := atomic.AddInt32(&q.inprocess, int32(len(resp.Messages)))\n\t\t\tq.Metrics(MetricReceive, float64(len(resp.Messages)), int(inflight))\n\t\t\tctxWithTime := context.WithValue(taskctx, \"start\", start)\n\t\t\tfor i := range resp.Messages {\n\t\t\t\tmsg := resp.Messages[i]\n\t\t\t\t// Run each request/message in its own goroutine\n\t\t\t\tgo s.serveMessage(ctxWithTime, q, msg, visibilityTimeout)\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Sagify) Handle(r *job.Request) {\n\th.job = r\n\n\t// IMPORTANT: set a unique SageMaker ID. As of this writing, SageMaker does not offer a job deletion API.\n\t// Setting the ID to a pseudo-constant value e.g. \"kenza-{projectID}-{jobID}\" will cause issues among\n\t// Kenza installations targeting the same AWS account. https://forums.aws.amazon.com/thread.jspa?threadID=268989\n\tprojectID, jobID := toString(h.job.JobQueued.ProjectID), toString(h.job.JobQueued.JobID)\n\th.sageMakerJobID = \"kenza-\" + projectID + \"-\" + jobID + \"-\" + toString(time.Now().UTC().UnixNano()) // avoid SageMaker ID conflicts\n\tr.SageMakerJobID = h.sageMakerJobID\n\n\th.parseConfiguration()\n\n\t// Install project dependencies and extract sagify version / info and apply\n\t// AWS region. These happen regardless of job type (scheduled or normal) and\n\t// always happen first so we can determine if the requested Sagify version is supported.\n\th.addPipInstallCommand()\n\th.addSagifyInfoCommand()\n\tr.Region = h.config.Region\n\n\tif err := h.addTrainOrTuningCommand(); err != nil {\n\t\tr.Fail(err)\n\t\treturn\n\t}\n\th.addBatchTransformCommand()\n\tif err := h.job.Notify(); err != nil {\n\t\te(err.Error())\n\t}\n\n\th.notifySchedules()\n\n\tif err := run(h.commands, r.WorkDir, map[string]string{},\n\t\th.buildConfig.HyperparameterTuning.winningModelResolver); err != nil {\n\t\tr.Fail(err)\n\t\treturn\n\t}\n\n\tr.Status = \"completed\"\n\tif err := r.Notify(); err != nil {\n\t\te(err.Error())\n\t}\n}", "func (c *QueueController) Run(cmd *runner.Command) (runner.RunStatus, error) {\n\tresultCh := make(chan result)\n\tc.reqCh <- runReq{cmd, resultCh}\n\tresult := <-resultCh\n\treturn result.st, result.err\n}", "func (jq *jobQueue) run(s *Scheduler) {\n\n\tgo func() {\n\t\tlog.Debugf(\"Job queue is running...\")\n\t\tfor jq.process(s) {\n\t\t\t// empty\n\t\t}\n\t\tjq.stopped <- true\n\t}()\n}", "func Test_handleMessage_resend(t *testing.T) {\n\tsession := &Mock4handleMessageAWSSession{}\n\tfinish := make(chan bool)\n\n\tconst expectedReceipt = \"a receipt handle\"\n\tconst expectedMessage = \"a message\"\n\n\thandler := func(msg interface{}) error {\n\t\tgo func() {\n\t\t\tfinish <- true\n\t\t}()\n\t\tassert.Equal(t, expectedMessage, msg)\n\t\treturn errors.New(\"intentional error\") // this triggers the resend process\n\t}\n\n\tqueue := queueSQS{\n\t\tthens: map[string][]MessageHandler{},\n\t\tSQS: session,\n\t\tURL: \"\",\n\t\tmsgIDerrs: map[string]int{},\n\t}\n\n\tmsg := sqs.Message{}\n\tmsg.Body = aws.String(expectedMessage)\n\tmsg.ReceiptHandle = aws.String(expectedReceipt)\n\tmsg.MessageId = aws.String(\"messageID\")\n\tmsg.MD5OfBody = aws.String(\"messageID\")\n\terr := queue.handleMessage(handler, &msg)\n\n\t<-finish\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, 1, session.TimesCalledDeleteMessage)\n\tassert.Equal(t, 1, session.TimesCalledSendMessage)\n\tassert.Equal(t, expectedReceipt, session.Receipt)\n}", "func (s *SQSServer) ListenAndServeQueues(queues ...QueueConf) error {\n\tif len(queues) == 0 {\n\t\treturn fmt.Errorf(\"Must specify at least one SQS queue to poll\")\n\t}\n\tpollctx, pollcancel := context.WithCancel(context.Background())\n\ttaskctx, taskcancel := context.WithCancel(context.Background())\n\ts.stopPolling = pollcancel\n\ts.stopTasks = taskcancel\n\tfor i := range queues {\n\t\tif queues[i].Name == \"\" {\n\t\t\treturn fmt.Errorf(\"Queue configuration must have a Name\")\n\t\t}\n\t\tif queues[i].Region == \"\" {\n\t\t\tqueues[i].Region = s.defaultRegion\n\t\t}\n\t\tif queues[i].ReadBatch == 0 {\n\t\t\tqueues[i].ReadBatch = defaultReadBatchSize\n\t\t}\n\t\tif queues[i].Metrics == nil {\n\t\t\tqueues[i].Metrics = func(MetricType, float64, int) {}\n\t\t}\n\t}\n\treturn s.pollQueues(pollctx, taskctx, queues)\n}", "func (s *Consumer) Run() error {\n\t// check queue status\n\tselect {\n\tcase <-s.stop:\n\t\treturn ErrQueueShutdown\n\tdefault:\n\t}\n\n\tfor task := range s.taskQueue {\n\t\tvar data Job\n\t\t_ = json.Unmarshal(task.Bytes(), &data)\n\t\tif v, ok := task.(Job); ok {\n\t\t\tif v.Task != nil {\n\t\t\t\tdata.Task = v.Task\n\t\t\t}\n\t\t}\n\t\tif err := s.handle(data); err != nil {\n\t\t\ts.logger.Error(err.Error())\n\t\t}\n\t}\n\treturn nil\n}", "func (worker *Worker) Run() error {\n\tworker.log.WithField(\"queueNames\", worker.getQueueNames()).Info(\"Run\")\n\tdefer func() {\n\t\tworker.log.Info(\"Exiting\")\n\t\tif worker.onStop != nil {\n\t\t\tworker.onStop()\n\t\t}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-worker.StopChan:\n\t\t\treturn nil\n\t\tdefault:\n\t\t\tif attemptedJob, err := worker.PerformNextJob(); err != nil {\n\t\t\t\treturn errorx.Decorate(err, \"exiting job runner\")\n\t\t\t} else if !attemptedJob {\n\t\t\t\t// we didn't find a job. Take a nap.\n\t\t\t\ttime.Sleep(worker.jobPollingInterval)\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *Agent) Run() {\n\tagent.RegisterAPIValidator(a.validateAPI)\n\tagent.OnConfigChange(a.onConfigChange)\n\n\tgo a.discoveryLoop()\n\tgo a.publishLoop()\n\n\tselect {\n\tcase <-a.stopAgent:\n\t\tlog.Info(\"Received request to kill agent\")\n\t\ta.stopDiscovery <- true\n\t\ta.stopPublish <- true\n\t\treturn\n\t}\n}", "func (a App) Run() error {\n\ta.log.Printf(\"config %+v\", a.params)\n\twg := &sync.WaitGroup{}\n\tqueue := make(chan string)\n\tresults := make(chan result)\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer close(queue)\n\t\ta.log.Printf(\"queue sender started\")\n\t\tfor _, url := range a.params.URLs {\n\t\t\ta.log.Printf(\"send to queue: %s\", url)\n\t\t\tqueue <- url\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tfor i := 0; i < a.params.Parallel; i++ {\n\t\ti := i\n\t\twg.Add(1)\n\t\tgo func(queue <-chan string, results chan<- result, wg *sync.WaitGroup) {\n\t\t\ta.log.Printf(\"worker %d started\", i)\n\t\t\tfor job := range queue {\n\t\t\t\tif requestedURL, body, err := download(a.client, job); err != nil {\n\t\t\t\t\ta.log.Printf(\"downloaded with error: %s\", err)\n\t\t\t\t\tresults <- result{\n\t\t\t\t\t\terr: err,\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ta.log.Printf(\"%s downloaded successfully\", requestedURL)\n\t\t\t\t\tresults <- result{\n\t\t\t\t\t\tbody: fmt.Sprintf(\"%x\", md5.Sum(body)),\n\t\t\t\t\t\turl: requestedURL,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\twg.Done()\n\t\t\ta.log.Printf(\"worker done: %d\", i)\n\t\t}(queue, results, wg)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\ta.log.Printf(\"close results\")\n\t\tclose(results)\n\t}()\n\n\tfor r := range results {\n\t\tif r.err != nil {\n\t\t\ta.log.Printf(\"error: %s\", r.err)\n\t\t} else {\n\t\t\tif _, err := fmt.Fprintf(a.w, \"%s %s\\n\", r.url, r.body); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error writing results: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (ng *AlertNG) Run(ctx context.Context) error {\n\tng.Log.Debug(\"Starting\")\n\tng.stateManager.Warm(ctx, ng.store)\n\n\tchildren, subCtx := errgroup.WithContext(ctx)\n\n\tchildren.Go(func() error {\n\t\treturn ng.stateManager.Run(subCtx)\n\t})\n\n\tchildren.Go(func() error {\n\t\treturn ng.MultiOrgAlertmanager.Run(subCtx)\n\t})\n\tchildren.Go(func() error {\n\t\treturn ng.AlertsRouter.Run(subCtx)\n\t})\n\n\tif ng.Cfg.UnifiedAlerting.ExecuteAlerts {\n\t\tchildren.Go(func() error {\n\t\t\treturn ng.schedule.Run(subCtx)\n\t\t})\n\t}\n\treturn children.Wait()\n}", "func (e *AlertEngine) Run(ctx context.Context) error {\n\talertGroup, ctx := errgroup.WithContext(ctx)\n\talertGroup.Go(func() error { return e.alertingTicker(ctx) })\n\talertGroup.Go(func() error { return e.runJobDispatcher(ctx) })\n\n\terr := alertGroup.Wait()\n\treturn err\n}", "func Run(ctx context.Context, mgr manager.Manager, handlerMap map[string]admission.Handler) error {\n\tif err := mgr.AddReadyzCheck(\"webhook-ready\", health.Checker); err != nil {\n\t\treturn fmt.Errorf(\"unable to add readyz check\")\n\t}\n\n\tc, err := webhookcontroller.New(mgr.GetConfig(), handlerMap)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tc.Start(ctx)\n\t}()\n\n\ttimer := time.NewTimer(time.Second * 20)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-webhookcontroller.Inited():\n\t\treturn waitReady()\n\tcase <-timer.C:\n\t\treturn fmt.Errorf(\"failed to start webhook controller for waiting more than 5s\")\n\t}\n\n\tserver := mgr.GetWebhookServer()\n\tserver.Host = \"0.0.0.0\"\n\tserver.Port = webhookutil.GetPort()\n\tserver.CertDir = webhookutil.GetCertDir()\n\treturn nil\n}", "func (e *BatchEngine) Run(ctx context.Context) error {\n\te.pollMessages(ctx, e.stream)\n\treturn e.processorError\n}", "func (s *Sender) Run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase e := <-s.queue:\n\t\t\tswitch e.Type {\n\t\t\tcase EventAdd:\n\t\t\t\tresult, err := s.cmdbClient.CreatePod(s.clusterInfo.BizID, &cmdb.CreatePod{\n\t\t\t\t\tPod: e.Pod.ToMapInterface(),\n\t\t\t\t})\n\t\t\t\tif err != nil || !result.Result {\n\t\t\t\t\tblog.Warnf(\"%s create pod failed, %+v, %+v\", s.logPre(), result, err)\n\t\t\t\t}\n\t\t\tcase EventUpdate:\n\t\t\t\tresult, err := s.cmdbClient.UpdatePod(s.clusterInfo.BizID, &cmdb.UpdatePod{\n\t\t\t\t\tUpdateOption: cmdb.UpdateOption{\n\t\t\t\t\t\tCondition: map[string]interface{}{\n\t\t\t\t\t\t\t\"bk_pod_name\": e.Pod.PodName,\n\t\t\t\t\t\t\t\"bk_pod_namespace\": e.Pod.PodNamespace,\n\t\t\t\t\t\t\t\"bk_pod_cluster\": e.Pod.PodCluster,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tData: e.Pod.ToMapInterface(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tif err != nil || !result.Result {\n\t\t\t\t\tblog.Warnf(\"%s update pod failed, %+v, %+v\", s.logPre(), result, err)\n\t\t\t\t}\n\t\t\tcase EventDel:\n\t\t\t\tresult, err := s.cmdbClient.DeletePod(s.clusterInfo.BizID, &cmdb.DeletePod{\n\t\t\t\t\tDeleteOption: cmdb.DeleteOption{\n\t\t\t\t\t\tCondition: map[string]interface{}{\n\t\t\t\t\t\t\t\"bk_pod_name\": e.Pod.PodName,\n\t\t\t\t\t\t\t\"bk_pod_namespace\": e.Pod.PodNamespace,\n\t\t\t\t\t\t\t\"bk_pod_cluster\": e.Pod.PodCluster,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tif err != nil || !result.Result {\n\t\t\t\t\tblog.Warnf(\"%s delete pod failed, %+v, %+v\", s.logPre(), result, err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tblog.Infof(\"%s context done\", s.logPre())\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Manager) Run(ctx context.Context) error {\n\t// start log broadcaster\n\t_ = utils.Pool.Submit(func() { m.logBroadcaster.run(ctx) })\n\n\t// initWorkloadStatus container\n\tif err := m.initWorkloadStatus(ctx); err != nil {\n\t\treturn err\n\t}\n\n\t// start status watcher\n\t_ = utils.Pool.Submit(func() { m.monitor(ctx) })\n\n\t// start health check\n\t_ = utils.Pool.Submit(func() { m.healthCheck(ctx) })\n\n\t// wait for signal\n\t<-ctx.Done()\n\tlog.WithFunc(\"Run\").Info(ctx, \"exiting\")\n\treturn nil\n}", "func (s *server) Run(options *Options) {\n\ts.options = options\n\tglog.Infof(\"Starting server (options %+v)\", *s.options)\n\n\tInitializeMetrics(options)\n\n\tclient := dnsmasq.NewMetricsClient(options.DnsMasqAddr, options.DnsMasqPort)\n\n\tfor {\n\t\tmetrics, err := client.GetMetrics()\n\t\tif err != nil {\n\t\t\tglog.Warningf(\"Error getting metrics from dnsmasq: %v\", err)\n\t\t\terrorsCounter.Add(1)\n\t\t} else {\n\t\t\tglog.V(3).Infof(\"DnsMasq metrics %+v\", metrics)\n\t\t\texportMetrics(metrics)\n\t\t}\n\n\t\ttime.Sleep(time.Duration(options.DnsMasqPollIntervalMs) * time.Millisecond)\n\t}\n}", "func (d *AlertsRouter) Run(ctx context.Context) error {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(d.adminConfigPollInterval):\n\t\t\tif err := d.SyncAndApplyConfigFromDatabase(); err != nil {\n\t\t\t\td.logger.Error(\"Unable to sync admin configuration\", \"error\", err)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\t// Stop sending alerts to all external Alertmanager(s).\n\t\t\td.adminConfigMtx.Lock()\n\t\t\tfor orgID, s := range d.externalAlertmanagers {\n\t\t\t\tdelete(d.externalAlertmanagers, orgID) // delete before we stop to make sure we don't accept any more alerts.\n\t\t\t\ts.Stop()\n\t\t\t}\n\t\t\td.adminConfigMtx.Unlock()\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func Run(ctx context.Context, message []byte) error {\n\tstopwatch := globalBackendStatsClient().TaskExecutionTime().Start()\n\tdefer stopwatch.Stop()\n\n\tvar s fnSignature\n\tif err := GlobalBackend().Encoder().Unmarshal(message, &s); err != nil {\n\t\treturn errors.Wrap(err, \"unable to decode the message\")\n\t}\n\t// TODO (madhu): Do we need a timeout here?\n\tretValues, err := s.Execute(ctx)\n\tif err != nil {\n\t\tglobalBackendStatsClient().TaskExecuteFail().Inc(1)\n\t\treturn err\n\t}\n\t// Assume only an error will be returned since that is verified before adding to fnRegister\n\treturn castToError(retValues[0])\n}", "func (t *TestPhase) Run(_ context.Context, queue *Queue, _, _ chan message.Message, _ RoundUpdate, step uint8) PhaseFn {\n\tt.callback(t.req, t.packet, t.streamer, t.aChan)\n\treturn nil\n}", "func (b *BcBotAction) Handler() {\n\tif b.jobs.Queue.Size() == 0 {\n\t\tfor _, bt := range b.jobs.BotList {\n\t\t\t_, err := b.NewWallet(bt)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr = bt.SetState(bot.BotStateNew)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// issue to admin wallet\n\t\tif _, err := b.Issue(b.jobs.AdminBot); err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor {\n\t\tget, err := b.jobs.Queue.Get()\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t\ttarget := get.(*bot.Bot)\n\t\tevent := target.GetState()\n\n\t\tswitch event {\n\t\tcase bot.BotStateNew:\n\t\t\tif err = target.SetState(bot.BotStateTrade); err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase bot.BotStateIssue:\n\t\t\tchargeAmount, err := strconv.ParseFloat(b.jobs.Config.ChargeAmount, 64)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgo func() {\n\t\t\t\tif b.jobs.AdminBot.Balance < chargeAmount {\n\t\t\t\t\tif _, err = b.Issue(b.jobs.AdminBot); err != nil {\n\t\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif _, err = b.Trade(b.jobs.AdminBot, target); err != nil {\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tif err = target.SetState(bot.BotStateTrade); err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase bot.BotStateTrade:\n\t\t\tamount, fee := getAmountAndFee(b.jobs.Config)\n\t\t\tif amount == -1 {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif target.Balance > amount+fee {\n\t\t\t\tgo func() {\n\t\t\t\t\treceiver := b.jobs.BotList[rand.Intn(b.jobs.Config.MemberCount)]\n\t\t\t\t\tif _, err = b.Trade(target, receiver); err != nil {\n\t\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tif err = target.SetState(bot.BotStateTrade); err != nil {\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// trade admin -> wallet\n\t\t\t\terr = target.SetState(bot.BotStateIssue)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tb.jobs.Queue.Put(target)\n\t\tfmt.Println(target.Id, \": \", target.GetState())\n\n\t\td, err := strconv.Atoi(b.jobs.Config.TxInterval)\n\t\tif err != nil {\n\t\t\tfmt.Println(err.Error())\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Duration(d) * time.Millisecond)\n\t}\n}", "func (s *Storage) Run() {\n\tfor _, q := range s.queues {\n\t\tgo q.Run()\n\t}\n}", "func (s *Scheduler) Run(client *clientv3.Client) error {\n\ts.client = client\n\ts.queue = recipe.NewPriorityQueue(client, common.QueuePrefix)\n\n\ts.logger.Infof(\"starting main scheduler\")\n\n\tgo s.watchDone()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.ready:\n\t\t\ts.process()\n\t\tcase <-s.ctx.Done():\n\t\t\treturn s.ctx.Err()\n\t\tcase <-s.done:\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (q *Queue) Run() {\n\tfor i := uint8(0); i < q.concurrency; i++ {\n\t\tgo q.work()\n\t}\n\tfor {\n\t\t// dequeue the job\n\t\t// jobJSONSlice will always be 2 length\n\t\tjobJSONSlice, err := client.BLPop(0, q.queueName).Result()\n\t\tif err != nil {\n\t\t\tq.errorHandler(q, \"\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tq.jobChannel <- jobJSONSlice[1]\n\t}\n}", "func (s *SubscriptionOps) Run(ctx context.Context) error {\n\tif s.Client == nil {\n\t\treturn errors.New(\"pub/sub client is nil\")\n\t}\n\tlogger := logging.FromContext(ctx)\n\n\tlogger = logger.With(\n\t\tzap.String(\"action\", s.Action),\n\t\tzap.String(\"project\", s.Project),\n\t\tzap.String(\"topic\", s.Topic),\n\t\tzap.String(\"subscription\", s.Subscription),\n\t)\n\n\tlogger.Info(\"Pub/Sub Subscription Job.\")\n\n\t// Load the subscription.\n\tsub := s.Client.Subscription(s.Subscription)\n\texists, err := sub.Exists(ctx)\n\tif err != nil {\n\t\treturn s.terminationErr(logger, fmt.Errorf(\"failed to verify topic exists: %s\", err))\n\t}\n\n\tswitch s.Action {\n\tcase operations.ActionExists:\n\t\t// If subscription doesn't exist, that is an error.\n\t\tif !exists {\n\t\t\treturn errors.New(\"subscription does not exist\")\n\t\t}\n\t\tlogger.Info(\"Previously created.\")\n\n\tcase operations.ActionCreate:\n\t\t// Load the topic.\n\t\ttopic, err := s.getTopic(ctx)\n\t\tif err != nil {\n\t\t\treturn s.terminationErr(logger, fmt.Errorf(\"failed to get topic, %s\", err))\n\t\t}\n\t\t// subConfig is the wanted config based on settings.\n\t\tsubConfig := pubsub.SubscriptionConfig{\n\t\t\tTopic: topic,\n\t\t\tAckDeadline: s.AckDeadline,\n\t\t\tRetainAckedMessages: s.RetainAckedMessages,\n\t\t\tRetentionDuration: s.RetentionDuration,\n\t\t}\n\n\t\t// If topic doesn't exist, create it.\n\t\tif !exists {\n\t\t\t// Create a new subscription to the previous topic with the given name.\n\t\t\tsub, err = s.Client.CreateSubscription(ctx, s.Subscription, subConfig)\n\t\t\tif err != nil {\n\t\t\t\treturn s.terminationErr(logger, fmt.Errorf(\"failed to create subscription, %s\", err))\n\t\t\t}\n\t\t\tlogger.Info(\"Successfully created.\")\n\t\t} else {\n\t\t\t// TODO: here is where we could update config.\n\t\t\tlogger.Info(\"Previously created.\")\n\t\t\t// Get current config.\n\t\t\tcurrentConfig, err := sub.Config(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn s.terminationErr(logger, fmt.Errorf(\"failed to get subscription config, %s\", err))\n\t\t\t}\n\t\t\t// Compare the current config to the expected config. Update if different.\n\t\t\tif diff := cmp.Diff(subConfig, currentConfig, ignoreSubConfig); diff != \"\" {\n\t\t\t\t_, err := sub.Update(ctx, pubsub.SubscriptionConfig{\n\t\t\t\t\tAckDeadline: s.AckDeadline,\n\t\t\t\t\tRetainAckedMessages: s.RetainAckedMessages,\n\t\t\t\t\tRetentionDuration: s.RetentionDuration,\n\t\t\t\t\tLabels: currentConfig.Labels,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn s.terminationErr(logger, fmt.Errorf(\"failed to update subscription config, %s\", err))\n\t\t\t\t}\n\t\t\t\tlogger.Info(\"Updated subscription config.\", zap.String(\"diff\", diff))\n\n\t\t\t}\n\t\t}\n\n\tcase operations.ActionDelete:\n\t\tif exists {\n\t\t\tif err := sub.Delete(ctx); err != nil {\n\t\t\t\treturn s.terminationErr(logger, fmt.Errorf(\"failed to delete subscription, %s\", err))\n\t\t\t}\n\t\t\tlogger.Info(\"Successfully deleted.\")\n\t\t} else {\n\t\t\tlogger.Info(\"Previously deleted.\")\n\t\t}\n\n\tdefault:\n\t\treturn s.terminationErr(logger, fmt.Errorf(\"unknown action value %v\", s.Action))\n\t}\n\n\ts.writeTerminationMessage(&SubActionResult{})\n\tlogger.Info(\"Done.\")\n\treturn nil\n}", "func (c *EBSCommand) Run(args []string) int {\n\n\t// Decorate this CLI's UI\n\tc.Ui = &cli.PrefixedUi{\n\t\tOutputPrefix: \" \",\n\t\tInfoPrefix: \"INFO: \",\n\t\tErrorPrefix: \"ERROR: \",\n\t\tUi: c.Ui,\n\t}\n\n\t// Set the args which may have the mtest config\n\tc.args = args\n\n\t// Dependency Injection\n\tif !c.IsInitialized() {\n\t\terr := c.SetAll()\n\t\tif err != nil {\n\t\t\tc.Ui.Error(err.Error())\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tif c.wtrVarsMake == nil {\n\t\tc.Ui.Error(fmt.Sprintf(\"Writer-variants-maker instance is nil.\"))\n\t\treturn 1\n\t}\n\n\t// Defer flush the gatedWriter which is linked to this\n\t// CLI's io.writer during Dependency Injection\n\tgatedLogger := c.wtrVarsMake.GatedWriter()\n\tif gatedLogger == nil {\n\t\treturn 1\n\t}\n\tdefer gatedLogger.Flush()\n\n\tif c.mtestMake == nil {\n\t\tc.Ui.Error(fmt.Sprintf(\"Mtest-maker instance is nil.\"))\n\t\treturn 1\n\t}\n\n\t// ebs cli is meant to run Maya Server\n\t// Get a Mtest instance that is associated with Maya Server\n\tmt, err := c.mtestMake.Make()\n\tif err != nil {\n\t\tc.Ui.Error(err.Error())\n\t\treturn 1\n\t}\n\n\t// Output the header that the server has started\n\tc.Ui.Output(\"Mtest ebs run started! Log data will start streaming:\\n\")\n\n\t// Start EBS use cases\n\trpts, err := mt.Start()\n\tdefer mt.Stop()\n\n\tif err != nil {\n\t\tc.Ui.Error(err.Error())\n\t\t// Exit code is set to 0 as this has nothing to do\n\t\t// with running of CLI. CLI execution was fine.\n\t\treturn 0\n\t}\n\n\tc.Ui.Info(fmt.Sprintf(\"%+s\", rpts))\n\n\treturn 0\n}", "func (c *SystemdCheck) Run() error {\n\tsender, err := c.GetSender()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := c.connect(sender)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer c.stats.CloseConn(conn)\n\n\tc.submitVersion(conn)\n\tc.submitSystemdState(sender, conn)\n\n\terr = c.submitMetrics(sender, conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsender.Commit()\n\n\treturn nil\n}", "func (e *Signer) Run(ctx context.Context) {\n\t// Shut down queues\n\tdefer utilruntime.HandleCrash()\n\tdefer e.syncQueue.ShutDown()\n\n\tif !cache.WaitForNamedCacheSync(\"bootstrap_signer\", ctx.Done(), e.configMapSynced, e.secretSynced) {\n\t\treturn\n\t}\n\n\tlogger := klog.FromContext(ctx)\n\tlogger.V(5).Info(\"Starting workers\")\n\tgo wait.UntilWithContext(ctx, e.serviceConfigMapQueue, 0)\n\t<-ctx.Done()\n\tlogger.V(1).Info(\"Shutting down\")\n}", "func SendEmails() {\n\t// Create Hectane email queue\n\tcfg := &queue.Config{\n\t\tDirectory: Conf.Event.EmailQueueDir,\n\t\tDisableSSLVerification: true,\n\t}\n\tq, err := queue.NewQueue(cfg)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't start Hectane queue: %s\", err.Error())\n\t\treturn\n\t}\n\tlog.Printf(\"Created Hectane email queue in '%s'. Queue processing loop refreshes every %d seconds\",\n\t\tConf.Event.EmailQueueDir, Conf.Event.EmailQueueProcessingDelay)\n\n\tfor {\n\t\t// Retrieve unsent emails from the email_queue\n\t\ttype eml struct {\n\t\t\tAddress string\n\t\t\tBody string\n\t\t\tID int64\n\t\t\tSubject string\n\t\t}\n\t\tvar emailList []eml\n\t\tdbQuery := `\n\t\t\t\tSELECT email_id, mail_to, subject, body\n\t\t\t\tFROM email_queue\n\t\t\t\tWHERE sent = false`\n\t\trows, err := pdb.Query(dbQuery)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Database query failed: %v\", err.Error())\n\t\t\treturn // Abort, as we don't want to continuously resend the same emails\n\t\t}\n\t\tfor rows.Next() {\n\t\t\tvar oneRow eml\n\t\t\terr = rows.Scan(&oneRow.ID, &oneRow.Address, &oneRow.Subject, &oneRow.Body)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error retrieving queued emails: %v\", err.Error())\n\t\t\t\trows.Close()\n\t\t\t\treturn // Abort, as we don't want to continuously resend the same emails\n\t\t\t}\n\t\t\temailList = append(emailList, oneRow)\n\t\t}\n\t\trows.Close()\n\n\t\t// Send emails\n\t\tfor _, j := range emailList {\n\t\t\te := &email.Email{\n\t\t\t\tFrom: \"[email protected]\",\n\t\t\t\tTo: []string{j.Address},\n\t\t\t\tSubject: j.Subject,\n\t\t\t\tText: j.Body,\n\t\t\t}\n\t\t\tmsgs, err := e.Messages(q.Storage)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Queuing email in Hectane failed: %v\", err.Error())\n\t\t\t\treturn // Abort, as we don't want to continuously resend the same emails\n\t\t\t}\n\t\t\tfor _, m := range msgs {\n\t\t\t\tq.Deliver(m)\n\t\t\t}\n\n\t\t\t// Mark message as sent\n\t\t\tdbQuery := `\n\t\t\t\tUPDATE email_queue\n\t\t\t\tSET sent = true, sent_timestamp = now()\n\t\t\t\tWHERE email_id = $1`\n\t\t\tcommandTag, err := pdb.Exec(dbQuery, j.ID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Changing email status to sent failed for email '%v': '%v'\", j.ID, err.Error())\n\t\t\t\treturn // Abort, as we don't want to continuously resend the same emails\n\t\t\t}\n\t\t\tif numRows := commandTag.RowsAffected(); numRows != 1 {\n\t\t\t\tlog.Printf(\"Wrong # of rows (%v) affected when changing email status to sent for email '%v'\",\n\t\t\t\t\tnumRows, j.ID)\n\t\t\t}\n\t\t}\n\n\t\t// Pause before running the loop again\n\t\ttime.Sleep(Conf.Event.EmailQueueProcessingDelay * time.Second)\n\t}\n}", "func (q *Queen) Run() {\n\n\tlog.L.Debugf(\"Obtaining a run lock for %v\", q.config.ID)\n\n\t//wait for the lock\n\tq.runMutex.Lock()\n\tq.State = running\n\n\tdefer func() {\n\t\tq.runMutex.Unlock()\n\t\tq.LastRun = time.Now()\n\t}()\n\n\tlog.L.Infof(\"Starting run of %v.\", q.config.ID)\n\n\t//before we get the info from the store, we need to have the caterpillar\n\tcat, err := caterpillar.GetCaterpillar(q.config.Type)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get the caterpillar %v.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.State = errorwaiting\n\t\tq.LastError = err.Error()\n\t\treturn\n\t}\n\n\t//Register the info struct so it'll come back with an assertable type in the interface that was written.\n\tcat.RegisterGobStructs()\n\n\t//get the information from the store\n\tinfo, err := store.GetInfo(q.config.ID)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get information for caterpillar %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\tlog.L.Debugf(\"State before run: %v\", info)\n\n\t//get the feeder, from that we can get the number of events.\n\tfeed, err := feeder.GetFeeder(q.config, info.LastEventTime)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get feeder for %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tcount, err := feed.GetCount()\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get event count from feeder for %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\t//Run the caterpillar - this should block until the cateprillar is done chewing through the data.\n\tstate, err := cat.Run(q.config.ID, count, info, q.nydusChannel, q.config, feed.StartFeeding)\n\tif err != nil {\n\t\tlog.L.Error(err.Addf(\"There was an error running caterpillar %v: %v\", q.config.ID, err.Error()))\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tlog.L.Debugf(\"State after run; %v\", state)\n\n\terr = store.PutInfo(q.config.ID, state)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't store information for caterpillar %v to info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tq.LastError = \"\"\n\tq.State = donewaiting\n\n}", "func Run() int {\n\tflag.Parse()\n\n\tif *txsPerSecondFlag == 0.0 {\n\t\t*txsPerSecondFlag = math.Inf(1)\n\t}\n\n\t// Init logger\n\tlogFile, err := os.OpenFile(*logFileFlag, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer logFile.Close()\n\tlogger := InitLoggers(logFile, *debugFlag)\n\n\t// Load submitter account keypairs\n\tkeypairs, err := InitKeypairs(*accountsFileFlag)\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", err)\n\t\treturn 1\n\t}\n\n\t// Load destination account keypairs\n\tdestinations, err := InitKeypairs(*destinationFileFlag)\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"msg\", err)\n\t\treturn 1\n\t}\n\n\tvar clients []horizon.Client\n\tfor _, endpoint := range horizonEndpointFlags {\n\t\tclient := horizon.Client{\n\t\t\tURL: endpoint,\n\t\t\tHTTP: &http.Client{Timeout: ClientTimeout},\n\t\t}\n\n\t\tclients = append(clients, client)\n\t}\n\n\t// Init rate limiter\n\tlimiter := rate.NewLimiter(rate.Limit(*txsPerSecondFlag), *burstLimitFlag)\n\n\t// Create top-level context. Will be sent to submitter goroutines for stopping them\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel() // Cancel the context if not done so already when test is complete.\n\n\tnetwork := build.Network{*stellarPassphraseFlag}\n\n\tif *numSubmittersFlag <= 0 || *numSubmittersFlag > len(keypairs) {\n\t\t*numSubmittersFlag = len(keypairs)\n\t}\n\n\t// Generate workers for submitting operations.\n\tsubmitters := make([]*submitter.Submitter, *numSubmittersFlag)\n\tsequenceProvider := sequence.New(&clients[0], logger)\n\tfor i := 0; i < *numSubmittersFlag; i++ {\n\t\tlevel.Debug(logger).Log(\"msg\", \"creating submitter\", \"submitter_index\", i)\n\t\tsubmitters[i], err = submitter.New(clients, network, sequenceProvider, keypairs[i].(*keypair.Full), destinations, *transactionAmountFlag, *opsPerTxFlag)\n\t\tif err != nil {\n\t\t\tlevel.Error(logger).Log(\"msg\", err, \"submitter_index\", i)\n\t\t\treturn 1\n\t\t}\n\t}\n\n\t// Start transaction submission\n\tstartTime := time.Now()\n\tfor i := 0; i < *numSubmittersFlag; i++ {\n\t\tsubmitters[i].StartSubmission(ctx, limiter, logger, *nativeAssetFlag)\n\t}\n\n\t// Listen for OS signals\n\tdone := make(chan os.Signal, 1)\n\tsignal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)\n\n\t// Stop when timer is up or when a signal is caught\n\tselect {\n\tcase <-time.After(time.Duration(*testTimeLengthFlag) * time.Second):\n\t\tlevel.Info(logger).Log(\"msg\", \"test time reached\")\n\t\tbreak\n\tcase s := <-done:\n\t\tlevel.Info(logger).Log(\"msg\", \"received signal\", \"type\", s)\n\t\tbreak\n\t}\n\tlevel.Info(logger).Log(\"msg\", \"closing\")\n\n\t// Stop all submitters\n\tcancel()\n\tvar wg sync.WaitGroup\n\tfor i, s := range submitters {\n\t\twg.Add(1)\n\t\tgo func(i int, s *submitter.Submitter) {\n\t\t\tdefer wg.Done()\n\t\t\t<-submitters[i].Stopped\n\t\t}(i, s)\n\t}\n\twg.Wait()\n\n\tlevel.Info(logger).Log(\"execution_time\", time.Since(startTime))\n\n\treturn 0\n}", "func (q *Queue) RunWithTimer(c *config.Config) error {\n\tstart := time.Now()\n\tif err := q.run(c); err != nil {\n\t\treturn fmt.Errorf(\"run queue failed: %s\", err)\n\t}\n\tlog.Printf(\"%sFinished in %.3f seconds%s\", colors.Green,\n\t\ttime.Since(start).Seconds(), colors.Reset)\n\treturn nil\n}", "func (q *SQSQueue) Queue(ctx context.Context, h Headers, b Body) error {\n\t_, span := trace.StartSpan(ctx, \"sqs/Queue\")\n\tdefer span.End()\n\n\tbody, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelay := aws.Int64(0)\n\tattributes := make(map[string]*sqs.MessageAttributeValue)\n\n\tfor k, v := range h {\n\t\tattributes[k] = &sqs.MessageAttributeValue{\n\t\t\tDataType: aws.String(\"String\"),\n\t\t\tStringValue: aws.String(v),\n\t\t}\n\t}\n\n\tmsg := &sqs.SendMessageInput{\n\t\tDelaySeconds: delay,\n\t\tMessageAttributes: attributes,\n\t\tMessageBody: aws.String(string(body)),\n\t\tQueueUrl: aws.String(q.name),\n\t}\n\n\t_, err = q.svc.SendMessage(msg)\n\treturn err\n}", "func (e RunJob) Run() {\n\tswitch e.request.requestType {\n\tcase \"http\":\n\t\tmakeHTTP(e)\n\tcase \"redis\":\n\t\tmakeRedis(e)\n\t}\n}", "func executeLang(contentsJSON []byte, done chan bool, httpAddr string, store fsm.Store) {\n var queue Queue\n json.Unmarshal(contentsJSON, &queue)\n go queue.BatchRun(httpAddr, store)\n go queue.UpdateRuns(httpAddr)\n done<- true\n return\n}", "func (w *Worker) Run() {\n\tconn := w.Pool.Get()\n\tdefer conn.Close()\n\n\tvar msgs = make([]Impression, 0, w.Size)\n\ttick := time.NewTicker(w.Interval)\n\n\tw.verbose(\"active\")\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-w.Queue:\n\t\t\tw.verbose(\"buffer (%d/%d) %v\", len(msgs), w.Size, msg)\n\t\t\tmsgs = append(msgs, msg)\n\t\t\tif len(msgs) >= w.Size {\n\t\t\t\tw.verbose(\"exceeded %d messages – flushing\", w.Size)\n\t\t\t\tw.send(conn, msgs)\n\t\t\t\tmsgs = make([]Impression, 0, w.Size)\n\t\t\t}\n\t\tcase <-tick.C:\n\t\t\tif len(msgs) > 0 {\n\t\t\t\tw.verbose(\"interval reached - flushing %d\", len(msgs))\n\t\t\t\tw.send(conn, msgs)\n\t\t\t\tmsgs = make([]Impression, 0, w.Size)\n\t\t\t} else {\n\t\t\t\tw.verbose(\"interval reached – nothing to send\")\n\t\t\t}\n\t\tcase <-w.quit:\n\t\t\ttick.Stop()\n\t\t\tw.verbose(\"exit requested – draining msgs\")\n\t\t\t// drain the msg channel.\n\t\t\tfor msg := range w.Queue {\n\t\t\t\tw.verbose(\"buffer (%d/%d) %v\", len(msgs), w.Size, msg)\n\t\t\t\tmsgs = append(msgs, msg)\n\t\t\t}\n\t\t\tw.verbose(\"exit requested – flushing %d\", len(msgs))\n\t\t\tw.send(conn, msgs)\n\t\t\tw.verbose(\"exit\")\n\t\t\tw.shutdown <- struct{}{}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (a *App) HandleRun(w http.ResponseWriter, r *http.Request) {\n\n\t// Get variables from the request\n\tvars := mux.Vars(r)\n\tvar variables RequestVariable\n\terr := variables.GetVariablesFromRequestVars(vars)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Check if the secret we passed in is valid, otherwise, return error 400\n\tif !a.Secret.Valid(variables.Secret) {\n\t\ta.DmnLogFile.Log.Println(\"Bad secret!\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tabortcmd := func(reason string) {\n\t\ta.DmnLogFile.Log.Println(reason)\n\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tvar sc ScheduledCommand\n\t\tsc.Status = Failed\n\t\tsc.Coutput = reason\n\t\tout, _ := json.Marshal(sc)\n\t\tio.WriteString(w, string(out))\n\t}\n\n\t// Select the dmn.Command, otherwise, if the dmn.Command hash cannot be found, return error 400\n\tselectedCmd, cerr := a.SelectCmd(variables.CmdHash)\n\n\tif cerr != nil {\n\t\tabortcmd(\"Unable to select hash: \" + variables.CmdHash)\n\t\treturn\n\t}\n\n\t// if selectedCmd.CmdHash == \"\" {\n\t// \tabortcmd(\"Invalid hash\")\n\t// \treturn\n\t// }\n\n\t_, err = os.Stat(selectedCmd.WorkingDirectory)\n\tif os.IsNotExist(err) {\n\t\tabortcmd(\"Invalid working directory: \" + selectedCmd.WorkingDirectory)\n\t\treturn\n\t}\n\n\ta.DmnLogFile.Log.Printf(\"Scheduling command %v: %v\\n\", selectedCmd.CmdHash, selectedCmd.Status)\n\tselectedCmd.Status = Scheduled\n\ta.CommandScheduler.QueuedCommands = append(a.CommandScheduler.QueuedCommands, selectedCmd)\n\ta.CommandScheduler.CommandQueue <- selectedCmd\n\n\ta.DmnLogFile.Log.Printf(\"Completed command %v: %v\\n\", selectedCmd.CmdHash, selectedCmd.Status)\n\n\tcompletedCommand := <-a.CommandScheduler.CompletedQueue\n\n\ta.DmnLogFile.Log.Printf(\"Command received from CompletedQueue: %v: %v\\n\", completedCommand.CmdHash, selectedCmd.Status)\n\n\ta.UpdateCommandDuration(selectedCmd, completedCommand.Duration)\n\n\tfor index, cmd := range a.CommandScheduler.QueuedCommands {\n\t\tif cmd.CmdHash == selectedCmd.CmdHash {\n\t\t\ta.DmnLogFile.Log.Printf(\"Updating status for %v: %v\\n\", cmd.CmdHash, Completed)\n\t\t\ta.CommandScheduler.QueuedCommands[index].Status = Completed\n\t\t\tbreak\n\t\t}\n\t}\n\n\ta.DmnLogFile.Log.Printf(\"Vacuuming command %v\\n\", selectedCmd.CmdHash)\n\ta.CommandScheduler.VacuumQueue <- selectedCmd\n\n\tout, _ := json.Marshal(completedCommand)\n\tio.WriteString(w, string(out))\n}", "func (p *Pool) Run(j job) {\n\t_, from, to := j.info()\n\tp.sugar.Infow(\"putting new job to queue\",\n\t\t\"func\", caller.GetCurrentFunctionName(),\n\t\t\"from\", from.String(),\n\t\t\"to\", to.String())\n\tp.jobCh <- j\n}", "func (c *Client) SendMessage(falcopayload types.FalcoPayload) {\r\n\tsvc := sqs.New(c.AWSSession)\r\n\r\n\tf, _ := json.Marshal(falcopayload)\r\n\r\n\tinput := &sqs.SendMessageInput{\r\n\t\tMessageBody: aws.String(string(f)),\r\n\t\tQueueUrl: aws.String(c.Config.AWS.SQS.URL),\r\n\t}\r\n\r\n\tc.Stats.AWSSQS.Add(\"total\", 1)\r\n\r\n\tresp, err := svc.SendMessage(input)\r\n\tif err != nil {\r\n\t\tgo c.CountMetric(\"outputs\", 1, []string{\"output:awssqs\", \"status:error\"})\r\n\t\tc.Stats.AWSSQS.Add(\"error\", 1)\r\n\t\tlog.Printf(\"[ERROR] : %v SQS - %v\\n\", c.OutputType, err.Error())\r\n\t\treturn\r\n\t}\r\n\r\n\tif c.Config.Debug == true {\r\n\t\tlog.Printf(\"[DEBUG] : %v SQS - MD5OfMessageBody : %v\\n\", c.OutputType, *resp.MD5OfMessageBody)\r\n\t}\r\n\r\n\tlog.Printf(\"[INFO] : %v SQS - Send Message OK (%v)\\n\", c.OutputType, *resp.MessageId)\r\n\tgo c.CountMetric(\"outputs\", 1, []string{\"output:awssqs\", \"status:ok\"})\r\n\tc.Stats.AWSSQS.Add(\"ok\", 1)\r\n}", "func handle(msg *queue.Message) {\n\tswitch msg.Action {\n\tcase RegenerateApprcAndStart:\n\t\tfallthrough\n\tcase regenerateApprc:\n\t\tif len(msg.Args) < 1 {\n\t\t\tlog.Printf(\"Error handling %q: this action requires at least 1 argument.\", msg.Action)\n\t\t\tmsg.Delete()\n\t\t\treturn\n\t\t}\n\t\tapp, err := ensureAppIsStarted(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\t\tmsg.Delete()\n\t\tapp.SerializeEnvVars()\n\t\tfallthrough\n\tcase startApp:\n\t\tif msg.Action == regenerateApprc {\n\t\t\tbreak\n\t\t}\n\t\tif len(msg.Args) < 1 {\n\t\t\tlog.Printf(\"Error handling %q: this action requires at least 1 argument.\", msg.Action)\n\t\t}\n\t\tapp, err := ensureAppIsStarted(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\t\terr = app.Restart(ioutil.Discard)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error handling %q. App failed to start:\\n%s.\", msg.Action, err)\n\t\t\treturn\n\t\t}\n\t\tmsg.Delete()\n\tcase bindService:\n\t\terr := bindUnit(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\t\tmsg.Delete()\n\tdefault:\n\t\tlog.Printf(\"Error handling %q: invalid action.\", msg.Action)\n\t\tmsg.Delete()\n\t}\n}", "func startOutgoingJobs() {\n\tfor relayName, queue := range outgoingQueues {\n\t\tgo outgoingSchedular(queue, config.Relays[relayName].Throughput)\n\t}\n}", "func main() {\n\n\tcfg := webhook.LoadConfiguration(\"./config/\")\n\tqueue := webhook.NewMessagingQueue(cfg.QueueURI, cfg.ExchangeName, cfg.PoolConfig)\n\thook := webhook.NewWebHook(queue)\n\n\tiris.Post(\"/\" + cfg.EndpointName, hook.Process)\n\tgo cleanup(queue)\n\n\tiris.Listen(fmt.Sprintf(\":%d\", cfg.WebServerPort))\n\n}", "func (act *ActionConfig) Run() error {\n\t// prepre for configuration\n\t// recovery from log\n\treturn act.next()\n}", "func (a *agent) runWorker() error {\n\tif a.workerFunc == nil {\n\t\treturn nil\n\t}\n\n\tconsumerUUID := uuid.New().String()\n\tlogger := a.logger.WithField(\"consumer_uuid\", consumerUUID)\n\n\t// Stop an agent's running worker (if any) before spawning a new worker goroutine.\n\t// This is to ensure that there's only one active/running worker for each agent.\n\tif a.workerCancel != nil {\n\t\tlogger.InfoF(\"stopping running workers, if any\")\n\t\ta.workerCancel()\n\t}\n\tworkerCtx, workerCancel := context.WithCancel(a.ctx)\n\n\tvar msgs <-chan amqp.Delivery\n\tvar err error\n\n\ta.mu.Lock()\n\t// Set worker cancel func to agent for reference\n\ta.workerCancel = workerCancel\n\n\tif err = a.ch.Qos(\n\t\t1, // prefetch count\n\t\t0, // prefetch size\n\t\tfalse, // global\n\t); err == nil {\n\t\tmsgs, err = a.ch.Consume(\n\t\t\ta.queueName, // queue\n\t\t\tconsumerUUID, // consumer\n\t\t\ta.autoAck, // auto-ack\n\n\t\t\tfalse, // exclusive\n\t\t\tfalse, // no-local\n\t\t\tfalse, // no-wait\n\t\t\tnil, // args\n\t\t)\n\t}\n\ta.mu.Unlock()\n\n\tif err == nil {\n\t\tlogger.InfoF(\"started worker\")\n\t\ta.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer a.wg.Done()\n\t\t\tdefer workerCancel()\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-workerCtx.Done(): // Worker context cancelled/done\n\t\t\t\t\tlogger.InfoF(\"worker context ended\")\n\t\t\t\t\treturn\n\t\t\t\tcase <-a.ctx.Done(): // Agent context cancelled/done\n\t\t\t\t\tlogger.InfoF(\"agent context ended\")\n\t\t\t\t\treturn\n\t\t\t\tcase d, ok := <-msgs:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogger.InfoF(\"messages ended; close connection to trigger reconnect logic\")\n\t\t\t\t\t\tif err := a.conn.Close(); err != nil {\n\t\t\t\t\t\t\tlogger.ErrorF(\"close connection failed: %q\", err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr = a.workerFunc(a.ctx, d.Body)\n\t\t\t\t\tlogger.InfoF(\"received %#v %s\", err, string(d.Body))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\ta.reportError(err)\n\t\t\t\t\t}\n\t\t\t\t\tif !a.autoAck {\n\t\t\t\t\t\t// only this message; not \"all messages before this\"\n\t\t\t\t\t\tif err := d.Ack(false); err != nil {\n\t\t\t\t\t\t\tlogger.ErrorF(\"ack failed: %q\", err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn err\n}", "func (m *MockJob) Run(v0 context.Context, v1 database.DB, v2 streaming.Sender) (*search.Alert, error) {\n\tr0, r1 := m.RunFunc.nextHook()(v0, v1, v2)\n\tm.RunFunc.appendCall(JobRunFuncCall{v0, v1, v2, r0, r1})\n\treturn r0, r1\n}", "func (a *Aggregator) Run() {\n\tevents := make(chan []byte)\n\turls := make(chan URL)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\t// Catch SIGINT/SIGTERM signals and call cancel() before exiting to\n\t// gracefully stop goroutines\n\tsignalCh := make(chan os.Signal, 1)\n\tsignal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)\n\n\tgo func() {\n\t\t<-signalCh\n\t\tcancel()\n\t\tos.Exit(1)\n\t}()\n\n\t// Run an event listener goroutine, compute aggregation on `ServerStatus`\n\t// events coming from the message queue\n\tgo func(ctx context.Context) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-events:\n\t\t\t\tvar status ServerStatus\n\t\t\t\terr := json.Unmarshal(event, &status)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.logger.Println(\"Error decoding status event\")\n\t\t\t\t} else {\n\t\t\t\t\ta.aggregate(&status)\n\t\t\t\t\turls <- status.Url\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\ta.mq.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(ctx)\n\n\t// Just print results of aggreation fo each received URL\n\tgo func(ctx context.Context) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase url := <-urls:\n\t\t\t\tstats, _ := a.servers[url]\n\t\t\t\ta.logger.Printf(\"%s alive=%v avail.(%%)=%.2f res(ms)=%v min(ms)=%v max(ms)=%v avg(ms)=%v status_codes=%v\\n\",\n\t\t\t\t\turl, stats.Alive, stats.Availability,\n\t\t\t\t\tstats.LatestResponseTime, stats.MovingAverageStats.Min(),\n\t\t\t\t\tstats.MovingAverageStats.Max(), stats.MovingAverageStats.Mean(),\n\t\t\t\t\tstats.ResponseStatusMap)\n\t\t\t\t// Send stats to presenter\n\t\t\t\tpresenterStats := Stats{\n\t\t\t\t\tUrl: url,\n\t\t\t\t\tAlive: stats.Alive,\n\t\t\t\t\tAvgResponseTime: stats.MovingAverageStats.Mean(),\n\t\t\t\t\tAvailability: stats.Availability,\n\t\t\t\t\tStatusCodes: stats.ResponseStatusMap,\n\t\t\t\t}\n\t\t\t\tpayload, err := json.Marshal(presenterStats)\n\t\t\t\tif err != nil {\n\t\t\t\t\ta.logger.Println(\"Unable to marshal presenter stats\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ta.mq.Produce(\"stats\", payload)\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(ctx)\n\n\tif err := a.mq.Consume(\"urlstatus\", 1, events); err != nil {\n\t\ta.logger.Fatal(err)\n\t}\n}", "func (runner *TestRunner) handleQueue (queueControl <-chan batchExecQueueControl) {\n\texecEndSignal := make(chan string)\n\n\texecute := func (enq batchExecQueueControlEnqueue, stopRequest <-chan struct{}, executionLogQuery <-chan chan<- string) {\n\t\t// Handle the execution log in a separate goroutine rather than in\n\t\t// the main loop of runner.executeBatch, so that any stalls in\n\t\t// executeBatch don't delay execution log queries.\n\t\t// The handler is controlled via the following channels.\n\t\texecutionLogAppend\t:= make(chan string)\t// Append a string to the log; don't commit to DB yet.\n\t\texecutionLogCommit\t:= make(chan struct{})\t// Commit uncommitted changes to DB.\n\t\texecutionLogStop\t:= make(chan struct{})\t// Stop the goroutine.\n\t\tgo func() {\n\t\t\texecutionLog := bytes.Buffer{}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\t\tcase dst := <-executionLogQuery:\n\t\t\t\t\t\tdst <- runner.getBatchResultPastExecutionLog(enq.batchResultId) + executionLog.String()\n\t\t\t\t\tcase str := <-executionLogAppend:\n\t\t\t\t\t\texecutionLog.WriteString(str)\n\t\t\t\t\tcase <-executionLogCommit:\n\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\topSet.Call(typeBatchResultExecutionLog, enq.batchResultId, \"Append\", executionLog.String())\n\t\t\t\t\t\terr := runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\texecutionLog.Reset()\n\t\t\t\t\tcase <-executionLogStop:\n\t\t\t\t\t\tif executionLog.Len() > 0 { panic(\"Execution log handler stopped, but non-committed data remains\") }\n\t\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\texecutionLogAppend <- fmt.Sprintf(\"Batch reached front of its queue at %v\\n\", time.Now().Format(defaultHumanReadableTimeFormat))\n\n\t\tvar batchResult BatchResult\n\t\terr := runner.rtdbServer.GetObject(enq.batchResultId, &batchResult)\n\t\tif err != nil { panic(err) }\n\n\t\tvar testCaseList TestCaseList\n\t\terr = runner.rtdbServer.GetObject(enq.batchResultId, &testCaseList)\n\t\tif err != nil { panic(err) }\n\n\t\tcasePaths := testCaseList.Paths\n\t\tif runner.isPartiallyExecutedBatch(enq.batchResultId) {\n\t\t\texecutionLogAppend <- fmt.Sprintf(\"Batch is partially executed, filtering pending cases\\n\")\n\t\t\tcasePaths = runner.filterPendingCasePaths(enq.batchResultId, casePaths)\n\t\t}\n\n\t\trunner.executeBatch(enq.batchResultId, batchResult.ExecParams, casePaths, stopRequest, executionLogAppend)\n\n\t\texecutionLogCommit <- struct{}{}\n\t\texecEndSignal <- enq.queueId\n\t\texecutionLogStop <- struct{}{}\n\t}\n\n\tqueueStopRequest\t\t:= make(map[string]chan<- struct{})\n\tqueueExecutionLogQuery\t:= make(map[string]chan<- chan<- string)\n\n\tlaunch := func (enq batchExecQueueControlEnqueue) {\n\t\tstopRequest\t\t\t:= make(chan struct{}, 1)\n\t\texecutionLogQuery\t:= make(chan chan<- string, 1)\n\t\tqueueStopRequest[enq.queueId]\t\t\t= stopRequest\n\t\tqueueExecutionLogQuery[enq.queueId]\t\t= executionLogQuery\n\t\tgo execute(enq, stopRequest, executionLogQuery)\n\t}\n\n\tfor {\n\t\tselect {\n\t\t\tcase command := <-queueControl:\n\t\t\t\tswitch cmd := command.(type) {\n\t\t\t\t\tcase batchExecQueueControlEnqueue:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t// Queue does not exist; create it.\n\n\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueueList, \"deviceBatchQueueList\", \"Append\", cmd.queueId)\n\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Init\")\n\t\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\t\t\t\tlog.Printf(\"[runner] created queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Append\", cmd.batchResultId)\n\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\t\t\tif len(queue.BatchResultIds) == 0 { // \\note queue is the queue before appending.\n\t\t\t\t\t\t\tlaunch(cmd);\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlStopBatch:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: stop request for non-existent queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfound := false\n\t\t\t\t\t\tfor ndx, enqueuedId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueuedId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tif ndx == 0 {\n\t\t\t\t\t\t\t\t\tselect {\n\t\t\t\t\t\t\t\t\t\tcase queueStopRequest[cmd.queueId] <- struct{}{}:\n\t\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] stop request sent for batch '%s'\\n\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] stop request already sent for batch '%s'\\n\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] cancelled pending batch '%s'\\n\", cmd.batchResultId)\n\n\t\t\t\t\t\t\t\t\t// Set batch status, and remove it from the queue and active batch list.\n\t\t\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\t\t\topSet.Call(typeBatchResult, cmd.batchResultId, \"SetStatus\", BATCH_STATUS_CODE_CANCELED)\n\t\t\t\t\t\t\t\t\topSet.Call(typeActiveBatchResultList, \"activeBatchResultList\", \"Remove\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Remove\", cmd.batchResultId)\n\t\t\t\t\t\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !found {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: stop request for batch '%s', does not exist in queue '%s'\\n\", cmd.batchResultId, cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlMove:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: move command for non-existent queue '%s'\", cmd.queueId)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfound := false\n\t\t\t\t\t\tfor srcNdx, enqueuedId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueuedId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tdstNdx := srcNdx + cmd.offset\n\t\t\t\t\t\t\t\tif srcNdx == 0 || dstNdx == 0 {\n\t\t\t\t\t\t\t\t\t// \\todo [nuutti] Support moving running batch? We'd have to automatically\n\t\t\t\t\t\t\t\t\t//\t\t\t\t stop it first, which can be slow, so it could get confusing?\n\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: trying to move currently to/from running batch in queue\\n\")\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif dstNdx < 0 || dstNdx >= len(queue.BatchResultIds) {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: trying to move batch to position %d\\n\", dstNdx)\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\t\t\t\t\t\t\topSet.Call(typeDeviceBatchQueue, cmd.queueId, \"Move\", srcNdx, dstNdx)\n\t\t\t\t\t\t\t\t\t\terr := runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\t\t\t\t\t\t\tif err != nil { panic(err) }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !found {\n\t\t\t\t\t\t\tlog.Printf(\"[runner] WARNING: move command for batch '%s', does not exist in queue '%s'\\n\", cmd.batchResultId, cmd.queueId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\tcase batchExecQueueControlExecutionLogQuery:\n\t\t\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\t\t\terr := runner.rtdbServer.GetObject(cmd.queueId, &queue)\n\t\t\t\t\t\tif err != nil { cmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId); continue }\n\n\t\t\t\t\t\tquerySent := false\n\t\t\t\t\t\tfor ndx, enqueueId := range queue.BatchResultIds {\n\t\t\t\t\t\t\tif enqueueId == cmd.batchResultId {\n\t\t\t\t\t\t\t\tif ndx == 0 {\n\t\t\t\t\t\t\t\t\tqueueExecutionLogQuery[cmd.queueId] <- cmd.dst\n\t\t\t\t\t\t\t\t\tquerySent = true\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif !querySent {\n\t\t\t\t\t\t\tcmd.dst <- runner.getBatchResultPastExecutionLog(cmd.batchResultId)\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase queueId := <-execEndSignal:\n\t\t\t\tvar queue DeviceBatchQueue\n\t\t\t\terr := runner.rtdbServer.GetObject(queueId, &queue)\n\t\t\t\tif err != nil { panic(err) } // \\note This shouldn't happen (a batch run ends while it's not even in the queue).\n\n\t\t\t\topSet := rtdb.NewOpSet()\n\t\t\t\topSet.Call(typeDeviceBatchQueue, queueId, \"Remove\", queue.BatchResultIds[0])\n\t\t\t\terr = runner.rtdbServer.ExecuteOpSet(opSet)\n\t\t\t\tif err != nil { panic(err) }\n\n\t\t\t\tif len(queue.BatchResultIds) > 1 { // \\note queue is the queue before removal.\n\t\t\t\t\tlaunch(batchExecQueueControlEnqueue{\n\t\t\t\t\t\tbatchResultId:\tqueue.BatchResultIds[1],\n\t\t\t\t\t\tqueueId:\t\tqueueId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t}\n\t}\n}", "func runSendMetricsLoop(ctx context.Context, config *Config, instanceRepo *service.Repository) error {\n\tconst lastSendTSFile = \"/tmp/pgscv-last-send.timestamp\"\n\n\tlog.Infof(\"sending metrics to %s every %d seconds\", config.SendMetricsURL, config.SendMetricsInterval/time.Second)\n\n\t// Before sending metrics wait until any services appear in the repo, else need to wait an one MetricsSendInterval.\n\t// This is the one-time operation and here is using a naive approach with 'for loop + sleep' instead of channels/sync stuff.\n\tlog.Debugln(\"waiting for services appear in service repo...\")\n\tfor {\n\t\ttime.Sleep(time.Second)\n\t\tif n := instanceRepo.TotalServices(); n > 0 {\n\t\t\tlog.Debugln(\"done, services found: \", n)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tsendClient, err := newSendClient(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize last send timestamp from file.\n\tlastSendTS := readLastSendTS(lastSendTSFile)\n\n\t// Do one-time sleep depending on last send timestamp staleness.\n\ttime.Sleep(lastSendStaleness(lastSendTS, config.SendMetricsInterval))\n\n\tticker := time.NewTicker(config.SendMetricsInterval)\n\n\tvar delay time.Duration\n\tfor {\n\t\tif delay > 0 {\n\t\t\tlog.Debugf(\"waiting for delay %s\", delay.String())\n\t\t\ttime.Sleep(delay)\n\t\t}\n\n\t\tbuf, err := sendClient.readMetrics()\n\t\tif err != nil {\n\t\t\tdelay = time.Second\n\t\t\tlog.Infof(\"read metrics failed: %s, retry after %s\", err, delay.String())\n\t\t\tcontinue\n\t\t}\n\n\t\tlastSendTS = time.Now().Unix()\n\n\t\terr = sendClient.sendMetrics(buf)\n\t\tif err != nil {\n\t\t\tdelay = addDelay(delay)\n\t\t\tlog.Infof(\"send metrics failed: %s, retry after %s\", err, delay.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// Reading and sending successful, reset delay.\n\t\tdelay = 0\n\n\t\t// Update last successful send timestamp, in case of pgSCV restarts\n\t\twriteLastSendTS(lastSendTS, lastSendTSFile)\n\n\t\t// Sleeping for next iteration.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Info(\"exit signaled, stop metrics sending\")\n\t\t\tticker.Stop()\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func runSendMetricsLoop(ctx context.Context, config *Config, instanceRepo *service.Repository) error {\n\tconst lastSendTSFile = \"/tmp/pgscv-last-send.timestamp\"\n\n\tlog.Infof(\"sending metrics to %s every %d seconds\", config.SendMetricsURL, config.SendMetricsInterval/time.Second)\n\n\t// Before sending metrics wait until any services appear in the repo, else need to wait an one MetricsSendInterval.\n\t// This is the one-time operation and here is using a naive approach with 'for loop + sleep' instead of channels/sync stuff.\n\tlog.Debugln(\"waiting for services appear in service repo...\")\n\tfor {\n\t\ttime.Sleep(time.Second)\n\t\tif n := instanceRepo.TotalServices(); n > 0 {\n\t\t\tlog.Debugln(\"done, services found: \", n)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tsendClient, err := newSendClient(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize last send timestamp from file.\n\tlastSendTS := readLastSendTS(lastSendTSFile)\n\n\t// Do one-time sleep depending on last send timestamp staleness.\n\ttime.Sleep(lastSendStaleness(lastSendTS, config.SendMetricsInterval))\n\n\tticker := time.NewTicker(config.SendMetricsInterval)\n\n\tvar delay time.Duration\n\tfor {\n\t\tif delay > 0 {\n\t\t\tlog.Debugf(\"waiting for delay %s\", delay.String())\n\t\t\ttime.Sleep(delay)\n\t\t}\n\n\t\tbuf, err := sendClient.readMetrics()\n\t\tif err != nil {\n\t\t\tdelay = time.Second\n\t\t\tlog.Infof(\"read metrics failed: %s, retry after %s\", err, delay.String())\n\t\t\tcontinue\n\t\t}\n\n\t\tlastSendTS = time.Now().Unix()\n\n\t\terr = sendClient.sendMetrics(buf)\n\t\tif err != nil {\n\t\t\tdelay = addDelay(delay)\n\t\t\tlog.Infof(\"send metrics failed: %s, retry after %s\", err, delay.String())\n\t\t\tcontinue\n\t\t}\n\n\t\t// Reading and sending successful, reset delay.\n\t\tdelay = 0\n\n\t\t// Update last successful send timestamp, in case of pgSCV restarts\n\t\twriteLastSendTS(lastSendTS, lastSendTSFile)\n\n\t\t// Sleeping for next iteration.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Info(\"exit signaled, stop metrics sending\")\n\t\t\tticker.Stop()\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (b *RunStep) Run(state quantum.StateBag) error {\n\trunner := state.Get(\"runner\").(quantum.Runner)\n\tconn := state.Get(\"conn\").(quantum.AgentConn)\n\toutCh := conn.Logs()\n\tsigCh := conn.Signals()\n\n\tif b.Command == \"\" {\n\t\tcommandRaw, ok := state.GetOk(\"command\")\n\t\tif ok {\n\t\t\tb.Command = commandRaw.(string)\n\t\t}\n\t}\n\n\tlog.Printf(\"Running command: %v\", b.Command)\n\n\terr := runner.Run(b.Command, outCh, sigCh)\n\tif err != nil {\n\t\treturn errors.New(\"Cmd: \" + b.Command + \" failed: \" + err.Error())\n\t}\n\treturn nil\n}", "func handler(ctx context.Context, evt queue.SQSEvent) error {\n\n\tfmt.Println(\"INFO: setting up tracing\")\n\txe, err := xray.NewExporter(\n\t\txray.WithVersion(\"latest\"),\n\t\txray.WithOnExport(func(in xray.OnExport) {\n\t\t\tfmt.Println(\"publishing trace,\", in.TraceID)\n\t\t}),\n\t)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to create the AWS X-Ray exporter: %v\", err)\n\t}\n\ttrace.RegisterExporter(xe)\n\ttrace.ApplyConfig(trace.Config{\n\t\tDefaultSampler: trace.AlwaysSample(),\n\t})\n\tfmt.Println(\"INFO: tracing set-up without error\")\n\n\tspanCtx, span := trace.StartSpan(ctx, \"msgFlagger/handler\")\n\tfor _, msg := range evt.Records {\n\n\t\tm := slack.MessageAction{}\n\t\terr := json.Unmarshal([]byte(msg.Body), &m)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR: unable to parse message action:\", err)\n\t\t}\n\n\t\tif err := flagMessage(spanCtx, m); err != nil {\n\t\t\tfmt.Println(\"ERROR: unable to flag message:\", err)\n\t\t}\n\t}\n\tspan.End()\n\txe.Flush()\n\txe.Close()\n\treturn nil\n}", "func (b *Work) Run() {\n\t// append hey's user agent\n\tua := b.Request.UserAgent()\n\tif ua == \"\" {\n\t\tua = megSenderUA\n\t} else {\n\t\tua += \" \" + megSenderUA\n\t}\n\n\tb.results = make(chan *result)\n\tb.stopCh = make(chan struct{}, b.C)\n\tb.startTime = time.Now()\n\tb.report = newReport(b.writer(), b.results, b.Output)\n\tb.report.start()\n\n\tb.runWorkers()\n\tb.Finish()\n}", "func (o *Orchestrator) Run() {\n\tv := newValidator(o.Plugin)\n\tm := newMetrics(o.healthzPath, o.healthzPort, o.metricsPath, o.metricsPort)\n\n\tv.mustValidatePrerequisites()\n\n\to.mustServeKMSRequests()\n\n\t// Giving some time for kmsPlugin to start Serving.\n\t// TODO: Must be a better way than to sleep.\n\ttime.Sleep(3 * time.Millisecond)\n\n\tv.mustPingRPC()\n\tmustGatherMetrics()\n\n\tm.mustServeHealthzAndMetrics()\n\n\t// Giving some time for HealthZ and Metrics to start Serving.\n\t// TODO: Must be a better way than to sleep.\n\ttime.Sleep(3 * time.Millisecond)\n\tmustEmitOKHealthz()\n\tmustEmitMetrics()\n}", "func Run(evt event.Event) error {\n\tenvs := env.GetEnvs()\n\tif len(evt.LogLevel) == 0 {\n\t\tevt.LogLevel = constants.DefaultWorkerLogLevel\n\t}\n\n\tif len(envs.Region) == 0 {\n\t\treturn fmt.Errorf(\"region is not specified. please check environment variables\")\n\t}\n\tlogrus.Infof(\"this is lambda function in %s\", envs.Region)\n\n\tswitch envs.Mode {\n\tcase constants.ManagerMode:\n\t\treturn workermanager.New().Run(envs)\n\tcase constants.WorkerMode:\n\t\treturn worker.NewWorker().Run(envs, evt)\n\t}\n\n\treturn nil\n}", "func Run() {\n\tcfg, err := config.Read()\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalf(\"cannot read configuration.\")\n\t}\n\n\tlogging.ConfigureLogging(cfg)\n\tbeConn, err := rpc.GRPCClientFromConfig(cfg, \"api.backend\")\n\tif err != nil {\n\t\tlogger.Fatalf(\"failed to connect to Open Match Backend, got %v\", err)\n\t}\n\n\tdefer beConn.Close()\n\tbe := pb.NewBackendClient(beConn)\n\n\tfeConn, err := rpc.GRPCClientFromConfig(cfg, \"api.frontend\")\n\tif err != nil {\n\t\tlogger.Fatalf(\"failed to connect to Open Match Frontend, got %v\", err)\n\t}\n\n\tdefer feConn.Close()\n\tfe := pb.NewFrontendClient(feConn)\n\n\tgo doFetch(cfg, be)\n\tgo doAssign(be)\n\tgo doDelete(fe)\n\n\tselect {}\n\n}", "func (c *Controllor) Run(ctx context.Context) {\n\tlog.Logger.Info(\"running...\")\n\tenv := gutils.Settings.GetString(\"env\")\n\n\tjournal := c.initJournal(ctx)\n\n\treceivers := c.initRecvs(env)\n\tacceptor := c.initAcceptor(ctx, journal, receivers)\n\tacceptorPipeline, err := c.initAcceptorPipeline(ctx, env)\n\tif err != nil {\n\t\tlog.Logger.Panic(\"initAcceptorPipeline\", zap.Error(err))\n\t}\n\n\twaitCommitChan := journal.GetCommitChan()\n\twaitAccepPipelineSyncChan := acceptor.GetSyncOutChan()\n\twaitAccepPipelineAsyncChan := acceptor.GetAsyncOutChan()\n\twaitDumpChan, skipDumpChan := acceptorPipeline.Wrap(ctx, waitAccepPipelineAsyncChan, waitAccepPipelineSyncChan)\n\n\t// after `journal.DumpMsgFlow`, every discarded msg should commit to waitCommitChan\n\twaitDispatchChan := journal.DumpMsgFlow(ctx, c.msgPool, waitDumpChan, skipDumpChan)\n\n\ttagPipeline := c.initTagPipeline(ctx, env, waitCommitChan)\n\tdispatcher := c.initDispatcher(ctx, waitDispatchChan, tagPipeline)\n\twaitPostPipelineChan := dispatcher.GetOutChan()\n\tpostPipeline := c.initPostPipeline(env, waitCommitChan)\n\twaitProduceChan := postPipeline.Wrap(ctx, waitPostPipelineChan)\n\tproducerSenders := c.initSenders(env)\n\tproducer := c.initProducer(env, waitProduceChan, waitCommitChan, producerSenders)\n\n\t// heartbeat\n\tgo c.runHeartBeat(ctx)\n\n\t// monitor\n\tmonitor.AddMetric(\"controllor\", func() map[string]interface{} {\n\t\treturn map[string]interface{}{\n\t\t\t\"goroutine\": runtime.NumGoroutine(),\n\t\t\t\"waitAccepPipelineSyncChanLen\": len(waitAccepPipelineSyncChan),\n\t\t\t\"waitAccepPipelineSyncChanCap\": cap(waitAccepPipelineSyncChan),\n\t\t\t\"waitAccepPipelineAsyncChanLen\": len(waitAccepPipelineAsyncChan),\n\t\t\t\"waitAccepPipelineAsyncChanCap\": cap(waitAccepPipelineAsyncChan),\n\t\t\t\"waitDumpChanLen\": len(waitDumpChan),\n\t\t\t\"waitDumpChanCap\": cap(waitDumpChan),\n\t\t\t\"skipDumpChanLen\": len(skipDumpChan),\n\t\t\t\"skipDumpChanCap\": cap(skipDumpChan),\n\t\t\t\"waitDispatchChanLen\": len(waitDispatchChan),\n\t\t\t\"waitDispatchChanCap\": cap(waitDispatchChan),\n\t\t\t\"waitPostPipelineChanLen\": len(waitPostPipelineChan),\n\t\t\t\"waitPostPipelineChanCap\": cap(waitPostPipelineChan),\n\t\t\t\"waitProduceChanLen\": len(waitProduceChan),\n\t\t\t\"waitProduceChanCap\": cap(waitProduceChan),\n\t\t\t\"waitCommitChanLen\": len(waitCommitChan),\n\t\t\t\"waitCommitChanCap\": cap(waitCommitChan),\n\t\t}\n\t})\n\tmonitor.BindHTTP(server)\n\n\tgo producer.Run(ctx)\n\tRunServer(ctx, gutils.Settings.GetString(\"addr\"))\n}", "func (s *Server) Run(ctx context.Context, optionValues ...Option) {\n\tvar opts options\n\tfor _, o := range optionValues {\n\t\to(&opts)\n\t}\n\n\tif !s.initialized {\n\t\tif err := s.identityProvider.Init(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif err := s.queue.init(ctx, s.backoffHandler, s.identityProvider); err != nil {\n\t\tlog.Println(\"Error initializing request queue:\", err)\n\t\treturn\n\t}\n\n\tinitRefresher(ctx, &s.queue, s.identityProvider)\n\n\tif opts.server {\n\t\tsocketName := \"token_server\"\n\t\tif opts.socketNameSuffix != \"\" {\n\t\t\tsocketName = fmt.Sprintf(\"%s_%s\", socketName, opts.socketNameSuffix)\n\t\t}\n\n\t\tserv, err := s.initServer(ctx, socketName)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error creating token server:\", err)\n\t\t\treturn\n\t\t}\n\n\t\tfor c := range serv.NewConns() {\n\t\t\tgo s.handleConn(c)\n\t\t}\n\t}\n\t// if server isn't requested, our background routines will handle requests\n\t// and there's no need for this function to block\n}", "func main() {\n\tflag.Parse()\n\tvar ex execer.Execer\n\tswitch *execerType {\n\tcase \"sim\":\n\t\tex = execers.NewSimExecer()\n\tcase \"os\":\n\t\tex = os_exec.NewExecer()\n\tdefault:\n\t\tlog.Fatalf(\"Unknown execer type %v\", *execerType)\n\t}\n\n\ttempDir, err := temp.TempDirDefault()\n\tif err != nil {\n\t\tlog.Fatal(\"error creating temp dir: \", err)\n\t}\n\t//defer os.RemoveAll(tempDir.Dir) //TODO: this may become necessary if we start testing with larger snapshots.\n\n\ttmp, err := temp.NewTempDir(\"\", \"daemon\")\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot create tmp dir: \", err)\n\t}\n\n\toutputCreator, err := runners.NewHttpOutputCreator(tempDir, \"\")\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot create OutputCreator: \", err)\n\t}\n\tfiler := snapshots.MakeTempFiler(tempDir)\n\tr := runners.NewQueueRunner(ex, filer, outputCreator, tmp, *qLen)\n\th := server.NewHandler(r, filer, 50*time.Millisecond)\n\ts, err := server.NewServer(h)\n\tif err != nil {\n\t\tlog.Fatal(\"Cannot create Scoot server: \", err)\n\t}\n\terr = s.ListenAndServe()\n\tif err != nil {\n\t\tlog.Fatal(\"Error serving Scoot Daemon: \", err)\n\t}\n}", "func main(){\n\t//Connect to local host server\n\tport, err := amqp.Dial(\"amqp://guest:guest@rabbitmq:5672/\")\n\tfailError(err, \"Failed to connect to RabbitMQ.\")\n\tdefer port.Close()\n\n\t//Create a channel on port\n\tch, err := port.Channel()\n\tfailError(err, \"Failed to open a channel on port.\")\n\tdefer ch.Close()\n\n\t//Declare a callback queue\n\tqueue, err := ch.QueueDeclare(\n\t\t\"rpc_queue\", // name\n\t\tfalse, // durable flag\n\t\tfalse, // auto delete flag\n\t\tfalse, // exclusive flat\n\t\tfalse, // no-wait flag\n\t\tnil, // extra arguments\n\t)\n\tfailError(err, \"Failed to create a queue for channel.\")\n\n\t//Set QoS\n\terr = ch.Qos(\n\t\t1,\n\t\t0,\n\t\tfalse,\n\t\t)\n\tfailError(err, \"Failed to set channel QoS.\")\n\n\t//Register a client\n\tmsgs, err := ch.Consume(\n\t\tqueue.Name, // queue\n\t\t\"\", // consumer\n\t\tfalse, // auto-ack\n\t\tfalse, // exclusive\n\t\tfalse, // no-local\n\t\tfalse, // no-wait\n\t\tnil, // args\n\t)\n\tfailError(err, \"Failed to register a consumer\")\n\n\t//Channel repeats receiving to keep server running\n\tloop := make(chan bool)\n\n\t//Process message and reply\n\tgo func() {\n\t\tfor d := range msgs {\n\t\t\t//Receive a message from client\n\t\t\tphrase := string(d.Body)\n\n\t\t\t//Convert phrase into fields\n\t\t\tphraseArr := strings.Fields(phrase)\n\n\t\t\t//Extract array elements\n\t\t\ta, _ := strconv.Atoi(phraseArr[1])\n\t\t\tb, _ := strconv.Atoi(phraseArr[2])\n\t\t\tc, _ := strconv.Atoi(phraseArr[3])\n\n\t\t\tvar response string\n\n\t\t\t//Perform an image processing function based on input\n\t\t\tswitch{\n\t\t\tcase a == 1:\n\t\t\t\tlog.Printf(\"Scaling %s\\n\", phraseArr[0])\n\t\t\t\tresponse = scaleImg(phraseArr[0], b)\n\t\t\tcase a == 2:\n\t\t\t\tlog.Printf(\"Copying %s\\n\", phraseArr[0])\n\t\t\t\tresponse = copyImg(phraseArr[0], b, c)\n\n\t\t\tcase a == 3:\n\t\t\t\tlog.Printf(\"Recursing %s\\n\", phraseArr[0])\n\t\t\t\tresponse = recurseImg(phraseArr[0])\n\t\t\t}\n\n\n\t\t\terr = ch.Publish(\n\t\t\t\t\"\", // exchange\n\t\t\t\td.ReplyTo, // routing key\n\t\t\t\tfalse, // mandatory\n\t\t\t\tfalse, // immediate\n\t\t\t\tamqp.Publishing{\n\t\t\t\t\tContentType: \"text/plain\",\n\t\t\t\t\tCorrelationId: d.CorrelationId,\n\t\t\t\t\tBody: []byte(response),\n\t\t\t\t})\n\t\t\tfailError(err, \"Failed to publish a reply.\")\n\n\t\t\td.Ack(false)\n\t\t}\n\t}()\n\n\t//Waiting on messages\n\tlog.Printf(\"Waiting on RPC Message\")\n\t<-loop\n}", "func Test_handleMessage_resend_maxNumberOfRetries_reached(t *testing.T) {\n\tsession := &Mock4handleMessageAWSSession{}\n\n\tconst expectedReceipt = \"a receipt handle\"\n\tconst expectedMessage = \"a message\"\n\n\ti := 0\n\thandler := func(msg interface{}) error {\n\t\ti++\n\t\tassert.Equal(t, expectedMessage, msg)\n\t\treturn errors.New(\"intentional error\") // this triggers the resend process\n\t}\n\n\tqueue := queueSQS{\n\t\tthens: map[string][]MessageHandler{},\n\t\tSQS: session,\n\t\tURL: \"\",\n\t\tmsgIDerrs: map[string]int{},\n\t}\n\n\tmsg := sqs.Message{}\n\tmsg.Body = aws.String(expectedMessage)\n\tmsg.ReceiptHandle = aws.String(expectedReceipt)\n\tmsg.MessageId = aws.String(\"messageID\")\n\tmsg.MD5OfBody = aws.String(\"messageID\")\n\n\tj := 0\n\terr := func() error {\n\t\tfor {\n\t\t\terr := queue.handleMessage(handler, &msg)\n\t\t\tj++\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}()\n\n\tassert.NotNil(t, err)\n\tassert.Equal(t, i+1, j)\n\tassert.Equal(t, ErrorRequestMaxRetries, err)\n\tassert.Equal(t, maxNumberOfRetries+1, session.TimesCalledDeleteMessage)\n\tassert.Equal(t, maxNumberOfRetries, session.TimesCalledSendMessage)\n\tassert.Equal(t, expectedReceipt, session.Receipt)\n}", "func main() {\n\tctx := cliContext()\n\tflag.Parse()\n\tpool := &red.Pool{\n\t\tDial: func() (red.Conn, error) {\n\t\t\treturn red.Dial(\"tcp\", *redisServer)\n\t\t},\n\t\tTestOnBorrow: func(c red.Conn, _ time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t\tMaxIdle: 1,\n\t}\n\t// Create the driver for queue\n\tdriver, err := redis.NewDriver(\n\t\tctx,\n\t\tredis.WithQueuePrefix(*prefix),\n\t\tredis.WithRedisPool(pool),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Create the manager\n\tm := workers.NewManager(driver, driver)\n\t// Register a global middleware\n\tm.RegisterMiddleware(\n\t\tmiddleware(\"Global\"),\n\t\tstorage.NewStorageMiddleware(&redisStorage{red: pool}),\n\t)\n\t// Register workers\n\terr = m.RegisterWorker(\"dummy\", dummyWorker{}, workers.WithMiddleware(middleware(\"DummyMiddle\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// Process queues\n\t// this hangs until the context is done\n\tm.Process(ctx, workers.WithParallelLimit(10), workers.WithRetryCount(1))\n}", "func EnsureQueue(ctx context.Context, cli sqsiface.SQSAPI) (string /*arn*/, error) {\n\tsrc := commonv1alpha1.ReconcilableFromContext(ctx)\n\ttypedSrc := src.(*v1alpha1.AWSS3Source)\n\n\tstatus := &typedSrc.Status\n\n\tif dest := typedSrc.Spec.Destination; dest != nil {\n\t\tif userProvidedQueue := dest.SQS; userProvidedQueue != nil {\n\t\t\tstatus.QueueARN = &userProvidedQueue.QueueARN\n\t\t\treturn userProvidedQueue.QueueARN.String(), nil\n\t\t}\n\t}\n\n\tqueueName := queueName(typedSrc)\n\n\tqueueURL, err := sqs.QueueURL(cli, queueName)\n\tswitch {\n\tcase isNotFound(err):\n\t\tqueueURL, err = sqs.CreateQueue(cli, queueName, queueTags(typedSrc))\n\t\tif err != nil {\n\t\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Unable to create SQS queue\")\n\t\t\treturn \"\", fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedQueue,\n\t\t\t\t\"Error creating SQS queue for event notifications: %s\", toErrMsg(err)))\n\t\t}\n\t\tevent.Normal(ctx, ReasonQueueCreated, \"Created SQS queue %q\", queueURL)\n\n\tcase isAWSError(err):\n\t\t// All documented API errors require some user intervention and\n\t\t// are not to be retried.\n\t\t// https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Request to SQS API got rejected\")\n\t\treturn \"\", controller.NewPermanentError(reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Failed to synchronize SQS queue: %s\", toErrMsg(err)))\n\n\tcase err != nil:\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Cannot synchronize SQS queue\")\n\t\treturn \"\", fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Failed to determine URL of SQS queue: %s\", toErrMsg(err)))\n\t}\n\n\tgetAttrs := []string{awssqs.QueueAttributeNameQueueArn, awssqs.QueueAttributeNamePolicy}\n\tqueueAttrs, err := sqs.QueueAttributes(cli, queueURL, getAttrs)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getting attributes of SQS queue: %w\", err)\n\t}\n\n\tqueueARN := queueAttrs[awssqs.QueueAttributeNameQueueArn]\n\n\tqueueARNStruct, err := arnStrToARN(queueARN)\n\tif err != nil {\n\t\treturn queueARN, fmt.Errorf(\"converting ARN string to structured ARN: %w\", err)\n\t}\n\n\t// it is essential that we propagate the queue's ARN here,\n\t// otherwise BuildAdapter() won't be able to configure the SQS\n\t// adapter properly\n\tstatus.QueueARN = queueARNStruct\n\n\tcurrentPol := unmarshalQueuePolicy(queueAttrs[awssqs.QueueAttributeNamePolicy])\n\tdesiredPol := makeQueuePolicy(queueARN, typedSrc)\n\n\tif err := syncQueuePolicy(cli, queueURL, currentPol, desiredPol); err != nil {\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Cannot synchronize SQS queue\")\n\t\treturn queueARN, fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Error synchronizing policy of SQS queue: %s\", toErrMsg(err)))\n\t}\n\n\treturn queueARN, nil\n}", "func (w *Worker) Run(wg *sync.WaitGroup, queue chan *Job) {\n\tdefer wg.Done()\n\tfor {\n\t\tselect {\n\t\tcase j, ok := <-queue:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tmd := j.ChartVersion.Metadata\n\t\t\tw.logger.Debug().\n\t\t\t\tStr(\"repo\", j.Repo.Name).\n\t\t\t\tStr(\"chart\", md.Name).\n\t\t\t\tStr(\"version\", md.Version).\n\t\t\t\tInt(\"jobKind\", int(j.Kind)).\n\t\t\t\tMsg(\"handling job\")\n\t\t\tvar err error\n\t\t\tswitch j.Kind {\n\t\t\tcase Register:\n\t\t\t\terr = w.handleRegisterJob(j)\n\t\t\tcase Unregister:\n\t\t\t\terr = w.handleUnregisterJob(j)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tw.logger.Error().\n\t\t\t\t\tErr(err).\n\t\t\t\t\tStr(\"repo\", j.Repo.Name).\n\t\t\t\t\tStr(\"chart\", md.Name).\n\t\t\t\t\tStr(\"version\", md.Version).\n\t\t\t\t\tInt(\"jobKind\", int(j.Kind)).\n\t\t\t\t\tMsg(\"error handling job\")\n\t\t\t}\n\t\tcase <-w.ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (g generic) Run(job Job, ctx *Ctx) (interface{}, error) {\n\tif job.String() == \"first\" {\n\t\treturn ctx.Do(NewJob(\"generic\", \"second\")), nil\n\t} else if job.String() == \"second\" {\n\t\treturn ctx.Do(NewJob(\"generic\", \"last\")), nil\n\t} else if job.String() == \"fail\" {\n\t\treturn nil, errors.New(\"error\")\n\t}\n\n\treturn job.String(), nil\n}", "func Run(conf *config.Config) {\n\n\tvar eventHandler = ParseEventHandler(conf)\n\tcontroller.Start(conf, eventHandler)\n}", "func (e *EndComponent) Run(ctx context.Context, config *ucfg.Config) error {\n\treturn nil\n}", "func (f Job) Run(ctx context.Context) {\n\tf(ctx)\n}", "func (q *Queue) Run() {\n\tvar ticker = time.NewTicker(q.rate)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tq.l.Debugw(\"preparing to flush\")\n\t\t\tq.flush()\n\n\t\tcase action := <-q.pendingC:\n\t\t\tq.l.Debugw(\"executing and adding to flush queue\")\n\t\t\tgo q.queue(action)\n\n\t\tcase <-q.stopC:\n\t\t\tq.l.Infow(\"stopping background job\")\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (a *ServerQueryAPI) Run(parentContext context.Context) error {\n\tctx, ctxCancel := context.WithCancel(parentContext)\n\tdefer ctxCancel()\n\tgo a.readPump(ctx)\n\tgo func() {\n\t\ta.eventListenersMtx.Lock()\n\t\tfor _, list := range a.eventListeners {\n\t\t\tclose(list)\n\t\t}\n\t\ta.eventListeners = nil\n\t\ta.eventListenersMtx.Unlock()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn context.Canceled\n\t\tcase cmd := <-a.commandQueue:\n\t\t\tres, err := a.submitCommand(ctx, cmd)\n\t\t\tcmd.result = res\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn context.Canceled\n\t\t\tcase cmd.doneCh <- err:\n\t\t\t}\n\t\tcase env, ok := <-a.readQueue:\n\t\t\tif !ok {\n\t\t\t\tif a.readError == nil {\n\t\t\t\t\treturn context.Canceled\n\t\t\t\t}\n\t\t\t\treturn a.readError\n\t\t\t}\n\t\t\ta.processEvent(ctx, env)\n\t\t}\n\t}\n}", "func (q *Queue) Run(w http.ResponseWriter, req *http.Request) {\n\tfor _, f := range q.list {\n\t\tif w, req = f(w, req); req == nil {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (p *Plugin) Run() {\n\tp.Log(\"notice\", fmt.Sprintf(\"Start %s handler: %sv%s\", pluginPkg, p.Name, version))\n\tbg := p.QChan.Data.Join()\n\tp.Connect()\n\tp.cleanDgraph()\n\tfor {\n\t\tselect {\n\t\tcase val := <-bg.Read:\n\t\t\tswitch val.(type) {\n\t\t\t// TODO: That has to be an interface!\n\t\t\tcase qtypes_messages.Message:\n\t\t\t\tqm := val.(qtypes_messages.Message)\n\t\t\t\tif qm.StopProcessing(p.Plugin, false) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tp.Log(\"info\" , fmt.Sprintf(\"%-15s : %s\", strings.Join(qm.SourcePath, \"->\"), qm.Msg))\n\t\t\tcase qcache_inventory.ContainerRequest:\n\t\t\t\tcontinue\n\t\t\tcase qtypes_docker_events.ContainerEvent:\n\t\t\t\tce := val.(qtypes_docker_events.ContainerEvent)\n\t\t\t\tp.handleContainerEvent(ce)\n\t\t\tcase qtypes_docker_events.NetworkEvent:\n\t\t\t\tne := val.(qtypes_docker_events.NetworkEvent)\n\t\t\t\tp.handleNetworkEvent(ne)\n\t\t\tcase qtypes_docker_events.DockerEvent:\n\t\t\t\tde := val.(qtypes_docker_events.DockerEvent)\n\t\t\t\t//TODO: Extract engine info\n\t\t\t\tp.Log(\"info\", fmt.Sprintf(\"Got word: connected to '%s': %v\", de.Engine.Name, de.Engine.ServerVersion))\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\tp.Log(\"info\", fmt.Sprintf(\"Dunno type '%s': %v\", reflect.TypeOf(val), val))\n\t\t\t}\n\t\t}\n\t}\n}", "func (job *Job) Run(script, UUID, ip string, args []string) int {\n\tjob.Name = script\n\tjob.UUID = UUID\n\tjob.Params = args\n\tjob.Status = JobSubmitted\n\tjob.outChan = make(chan string, 1)\n\tjob.stateChan = make(chan string, 1)\n\tjob.ip = ip\n\n\tLogInf(logContextRunner, \"Run [%v], State[%v]\", script, job.Status)\n\n\tname, exist := hasScript(job.Name)\n\tif !exist {\n\t\tLogErr(logContextRunner, \"Script [%v] does not exist\", script)\n\t\treturn -1\n\t}\n\n\tscriptPath := filepath.Join(localScriptPath, name)\n\tgo runLoop(job, scriptPath)\n\treturn 0\n}", "func (r *Runner) Run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase job := <-r.jobs:\n\t\t\tjobID, jobType := job.ID(), job.Type()\n\t\t\tl := r.l.WithFields(logrus.Fields{\"id\": jobID, \"type\": jobType})\n\n\t\t\tvar nCtx context.Context\n\t\t\tvar cancel context.CancelFunc\n\t\t\tif timeout := job.Timeout(); timeout != 0 {\n\t\t\t\tnCtx, cancel = context.WithTimeout(ctx, timeout)\n\t\t\t} else {\n\t\t\t\tnCtx, cancel = context.WithCancel(ctx)\n\t\t\t}\n\n\t\t\tr.addJobCancel(jobID, cancel)\n\t\t\tr.runningJobs.Add(1)\n\t\t\trun := func(ctx context.Context) {\n\t\t\t\tl.Infof(\"Job started.\")\n\n\t\t\t\tdefer func(start time.Time) {\n\t\t\t\t\tl.WithField(\"duration\", time.Since(start).String()).Info(\"Job finished.\")\n\t\t\t\t}(time.Now())\n\n\t\t\t\tdefer r.runningJobs.Done()\n\t\t\t\tdefer cancel()\n\t\t\t\tdefer r.removeJobCancel(jobID)\n\n\t\t\t\terr := job.Run(ctx, r.send)\n\t\t\t\tif err != nil {\n\t\t\t\t\tr.send(&agentpb.JobResult{\n\t\t\t\t\t\tJobId: job.ID(),\n\t\t\t\t\t\tTimestamp: timestamppb.Now(),\n\t\t\t\t\t\tResult: &agentpb.JobResult_Error_{\n\t\t\t\t\t\t\tError: &agentpb.JobResult_Error{\n\t\t\t\t\t\t\t\tMessage: err.Error(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\tl.Warnf(\"Job terminated with error: %+v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgo pprof.Do(nCtx, pprof.Labels(\"jobID\", jobID, \"type\", string(jobType)), run)\n\t\tcase <-ctx.Done():\n\t\t\tr.runningJobs.Wait() // wait for all jobs termination\n\t\t\tclose(r.messages)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *ServiceImpl) RunDemo(body MessageBody, rabbit RabbitClient, db DBClient) (output bool, err error){\n\n\tconfigs := body.Configs\n\tlog.Println(\"number of messages to send: \", len(configs))\n\n\t//\tbuild and publish each config message\n\tfor _, config := range configs {\n\t\tmsg := s.BuildConfigMessage(config, db)\n\t\t// determine routing key\n\t\tnextQueue := strconv.Itoa(config.ID)\n\t\tlog.Println(\"sending this config message: \", msg)\n\t\terr = rabbit.Publish(msg, nextQueue)\n\t}\n\n\t// build and publish each direct input message to nextKeys\n\tfor i, nextKey := range s.config.NextKeys {\n\t\tinput := body.Input[i]\n\t\tmsg := s.BuildInputMessage(input)\n\t\tlog.Println(\"sending this input message: \", msg)\n\t\tnextQueue := strconv.Itoa(nextKey)\n\t\terr = rabbit.Publish(msg, nextQueue)\n\t}\n\n\tlog.Println(\"waiting for output...\")\n\toutput, err = rabbit.RunConsumer()\n\tlog.Println(\"received output: \", output)\n\tlog.Println(\"received err: \", err)\n\n\treturn output, err\n\n}", "func (s *scheduler) run(ctx context.Context) error {\n\tctx, cancel := context.WithCancel(ctx)\n\tdefer cancel()\n\n\twg := sync.WaitGroup{}\n\n\t// Run healthcheck loop\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ts.runHealthcheckLoopFn(ctx)\n\t}()\n\n\t// Manage available Worker capacity\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ts.manageWorkerCapacityFn(ctx)\n\t}()\n\n\t// Manage available Job capacity\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ts.manageJobCapacityFn(ctx)\n\t}()\n\n\t// Monitor for new/deleted projects at a regular interval. Launch new or kill\n\t// existing project-specific Worker and Job loops as needed.\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ts.manageProjectsFn(ctx)\n\t}()\n\n\t// Wait for an error or a completed context\n\tvar err error\n\tselect {\n\t// In essence, this comprises the Scheduler's \"healthcheck\" logic.\n\t// Whenever we receive an error on this channel, we cancel the context and\n\t// shut down. E.g., if one loop fails, everything fails.\n\t// This includes:\n\t// 1. an error listing projects at the start of the project loop\n\t// (Scheduler <-> API comms)\n\t// 2. an error instantiating a reader in any of the worker/job loops\n\t// 3. an error instantiating a reader, reading a message or acking a\n\t// message in the healhcheck loop, which runs regularly and may spot\n\t// connectivity issues when the Brigade server is otherwise dormant\n\t// (Scheduler <-> Messaging queue comms)\n\tcase err = <-s.errCh:\n\t\tcancel() // Shut it all down\n\tcase <-ctx.Done():\n\t\terr = ctx.Err()\n\t}\n\n\t// Adapt wg to a channel that can be used in a select\n\tdoneCh := make(chan struct{})\n\tgo func() {\n\t\tdefer close(doneCh)\n\t\twg.Wait()\n\t}()\n\n\tselect {\n\tcase <-doneCh:\n\tcase <-time.After(3 * time.Second):\n\t\t// Probably doesn't matter that this is hardcoded. Relatively speaking, 3\n\t\t// seconds is a lot of time for things to wrap up.\n\t}\n\n\treturn err\n}", "func (ab *AddBackend) Run(args []string) int {\n\tlog.Debug(\"AddBackend run commands \", args)\n\tvar name, serverList, loadBalancerPolicy, caCertPath string\n\tvar tlsOnly bool\n\tcmdFlags := flag.NewFlagSet(\"add-backend\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { ab.UI.Output(ab.Help()) }\n\tcmdFlags.StringVar(&name, \"name\", \"\", \"\")\n\tcmdFlags.StringVar(&serverList, \"servers\", \"\", \"\")\n\tcmdFlags.StringVar(&loadBalancerPolicy, \"load-balancer-policy\", \"\", \"\")\n\tcmdFlags.StringVar(&caCertPath, \"cacert-path\", \"\", \"\")\n\tcmdFlags.BoolVar(&tlsOnly, \"tls-only\", false, \"\")\n\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\targErr := false\n\n\tif name == \"\" {\n\t\tab.UI.Error(\"Name must be specified\")\n\t\targErr = true\n\t}\n\n\tif serverList == \"\" {\n\t\tab.UI.Error(\"Server list must be specified\")\n\t\targErr = true\n\t}\n\n\tif argErr {\n\t\tab.UI.Error(\"\")\n\t\tab.UI.Error(ab.Help())\n\t\treturn 1\n\t}\n\n\t//Check load balancer policy\n\tif loadBalancerPolicy != \"\" && !loadbalancer.IsKnownLoadBalancerPolicy(loadBalancerPolicy) {\n\t\tab.UI.Error(fmt.Sprintf(\"Unknown load balancer policy %s\", loadBalancerPolicy))\n\t\tab.UI.Error(fmt.Sprintf(\" Known policies: %s\", loadbalancer.RegisteredLoadBalancers()))\n\t\treturn 1\n\t}\n\n\t//Check cacert and TLS config\n\tif err := ab.validCertAndTLS(caCertPath, tlsOnly); err != nil {\n\t\tab.UI.Error(err.Error())\n\t\treturn 1\n\t}\n\n\tbackend := &config.BackendConfig{\n\t\tName: name,\n\t\tServerNames: strings.Split(serverList, \",\"),\n\t\tLoadBalancerPolicy: loadBalancerPolicy,\n\t\tTLSOnly: tlsOnly,\n\t\tCACertPath: caCertPath,\n\t}\n\n\tif err := backend.Store(ab.KVStore); err != nil {\n\t\tab.UI.Error(err.Error())\n\t\treturn 1\n\t}\n\n\tif err := ab.KVStore.Flush(); err != nil {\n\t\tab.UI.Error(err.Error())\n\t\treturn 1\n\t}\n\n\treturn 0\n\n}", "func (a *App) Run() error {\n\n\t// If an echo service url is supplied then launch a Go routine that pings\n\t// the echo service once a minute.\n\tif a.echoServiceURL != \"\" {\n\t\tgo func() {\n\t\t\tclient, err := google.DefaultClient(context.Background(), \"https://www.googleapis.com/auth/cloud-platform\")\n\t\t\tif err != nil {\n\t\t\t\tsklog.Errorf(\"Failed building authenticated HTTP client: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequest := `{\"request\": \"echo\"}`\n\t\t\tfor range time.Tick(time.Minute) {\n\t\t\t\tresp, err := client.Post(a.echoServiceURL, \"application/json\", bytes.NewReader([]byte(request)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tsklog.Infof(\"Echo request failed: %s\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tsklog.Infof(\"Echo Reading response body failed: %s\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tsklog.Infof(\"Echo got response: %q\", string(b))\n\t\t\t}\n\t\t}()\n\t}\n\n\t// Add all routing.\n\tr := chi.NewRouter()\n\tr.Post(\"/send\", a.incomingEmaiHandler)\n\n\t// We must specify that we handle /healthz or it will never flow through to\n\t// our middleware. Even though this handler is never actually called (due to\n\t// the early termination in httputils.HealthzAndHTTPS), we need to have it\n\t// added to the routes we handle.\n\tr.HandleFunc(\"/healthz\", httputils.ReadyHandleFunc)\n\n\tsklog.Infof(\"Ready to serve on port %s\", a.port)\n\tserver := &http.Server{\n\t\tAddr: a.port,\n\t\tHandler: r,\n\t\tReadTimeout: serverReadTimeout,\n\t\tWriteTimeout: serverWriteTimeout,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\treturn server.ListenAndServe()\n}", "func (b *batchSender) Run(ctx context.Context) {\n\tdefer close(b.done)\n\n\tfor b.sleeper(ctx, b.interval) {\n\t\tmsgs, done := b.getBatch(ctx, b.maxBatch)\n\n\t\t// Channel has been closed and drained.\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(msgs) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := b.sendBatchWithRetries(ctx, msgs); err != nil {\n\t\t\t// TODO: what to do with error?\n\t\t\t_ = err\n\t\t}\n\t}\n}", "func (sche *Scheduler) Run() {\n\tsche.HandleDelayedItems()\n}", "func (s *S3Consumer) Run(\n\tctx context.Context,\n\tmessageChan chan message,\n) error {\n\tobjectChan := make(chan s3ObjTask, s.NumWorkers)\n\terrChan := make(chan error, s.NumWorkers+1)\n\n\tfor i := 0; i < s.NumWorkers; i++ {\n\t\tgo func() {\n\t\t\terrChan <- s.runSubTasks(ctx, messageChan, objectChan)\n\t\t}()\n\t}\n\n\tgo func() {\n\t\terrChan <- s.processPrefixes(ctx, objectChan)\n\t\tclose(objectChan)\n\t}()\n\n\tfor i := 0; i < s.NumWorkers+1; i++ {\n\t\tif err := <-errChan; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o Options) Run(ctx context.Context, spec *downwardapi.JobSpec, extra map[string]gcs.UploadFunc) error {\n\tlogrus.WithField(\"options\", o).Debug(\"Uploading to blob storage\")\n\n\tfor extension, mediaType := range o.GCSConfiguration.MediaTypes {\n\t\tmime.AddExtensionType(\".\"+extension, mediaType)\n\t}\n\n\tuploadTargets, extraTargets, err := o.assembleTargets(spec, extra)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"assembleTargets: %w\", err)\n\t}\n\n\terr = completeUpload(ctx, o, uploadTargets)\n\n\tif extraErr := completeUpload(ctx, o, extraTargets); extraErr != nil {\n\t\tif err == nil {\n\t\t\terr = extraErr\n\t\t} else {\n\t\t\tlogrus.WithError(extraErr).Info(\"Also failed to upload extra targets\")\n\t\t}\n\t}\n\n\treturn err\n}" ]
[ "0.6085722", "0.59596044", "0.58610517", "0.5824352", "0.57012486", "0.56319433", "0.5514261", "0.5386275", "0.534189", "0.53253037", "0.5299745", "0.5179622", "0.51693946", "0.5121386", "0.51029456", "0.50969225", "0.50817096", "0.5079898", "0.5044915", "0.49995443", "0.49990103", "0.49910077", "0.49802965", "0.4911483", "0.49023664", "0.4894899", "0.488992", "0.4885835", "0.48764294", "0.48680088", "0.48587516", "0.48544198", "0.48259288", "0.4817189", "0.48103735", "0.48037243", "0.47951677", "0.47829506", "0.4768502", "0.476346", "0.47587064", "0.47577822", "0.47454694", "0.4713453", "0.47117752", "0.47098312", "0.4709011", "0.47025442", "0.46796784", "0.46697825", "0.46687275", "0.46652484", "0.46649706", "0.46639526", "0.4660226", "0.46600544", "0.46573925", "0.46523827", "0.4649151", "0.4641111", "0.4631968", "0.46288934", "0.46281365", "0.46097144", "0.460498", "0.45957687", "0.45932102", "0.45932102", "0.459298", "0.45909867", "0.45905456", "0.45858884", "0.4579514", "0.45793965", "0.45726752", "0.45721862", "0.45682344", "0.45658544", "0.4561187", "0.4560179", "0.45590046", "0.45558226", "0.45545563", "0.45536175", "0.45534685", "0.45496428", "0.4549224", "0.45482323", "0.4546888", "0.4546654", "0.45464438", "0.45463103", "0.45353466", "0.45289284", "0.4523466", "0.45228112", "0.45222616", "0.45213622", "0.4520764", "0.4520049" ]
0.78693676
0
RunWithQueues is like [Run] but accepts custom queue implementations. The fields [config.Config.SQSReader] and [config.Config.SQSWriter] must be zero.
func RunWithQueues(cfg config.Config, store storage.Store, back backend.Backend, statesQueue queue.Writer, jobsQueue AgentQueueReader, logger log.Logger) int { // Build state updater. stateUpdater := stateupdater.New(statesQueue) updater := struct { *stateupdater.Updater storage.Store }{stateUpdater, store} // Build job runner. jrunner, err := newJobRunner(cfg, back, updater, logger) if err != nil { logger.Errorf("error creating job runner: %+v", err) return 1 } // Set queue's message processor. jobsQueue.SetMessageProcessor(jrunner) // Run agent. if err := run(cfg, jrunner, updater, jobsQueue, logger); err != nil { logger.Errorf("error running agent: %+v", err) return 1 } return 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *SQSServer) ListenAndServeQueues(queues ...QueueConf) error {\n\tif len(queues) == 0 {\n\t\treturn fmt.Errorf(\"Must specify at least one SQS queue to poll\")\n\t}\n\tpollctx, pollcancel := context.WithCancel(context.Background())\n\ttaskctx, taskcancel := context.WithCancel(context.Background())\n\ts.stopPolling = pollcancel\n\ts.stopTasks = taskcancel\n\tfor i := range queues {\n\t\tif queues[i].Name == \"\" {\n\t\t\treturn fmt.Errorf(\"Queue configuration must have a Name\")\n\t\t}\n\t\tif queues[i].Region == \"\" {\n\t\t\tqueues[i].Region = s.defaultRegion\n\t\t}\n\t\tif queues[i].ReadBatch == 0 {\n\t\t\tqueues[i].ReadBatch = defaultReadBatchSize\n\t\t}\n\t\tif queues[i].Metrics == nil {\n\t\t\tqueues[i].Metrics = func(MetricType, float64, int) {}\n\t\t}\n\t}\n\treturn s.pollQueues(pollctx, taskctx, queues)\n}", "func PopulateQueues(c *gin.Context) {\n\tif queue == nil {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"msg\": \"queue doesn't exist, please create it!!!\",\n\t\t})\n\t\treturn\n\t}\n\tqueue = enqueue(queue, qMessage{\n\t\tUSER: \"roberto\",\n\t\tEMAIL: \"[email protected]\",\n\t\tUUID: \"1\",\n\t\tMSG: \"lindo\",\n\t})\n\tqueue = enqueue(queue, qMessage{\n\t\tUSER: \"alex\",\n\t\tEMAIL: \"[email protected]\",\n\t\tUUID: \"2\",\n\t\tMSG: \"lindox\",\n\t})\n\tqueue = enqueue(queue, qMessage{\n\t\tUSER: \"ale\",\n\t\tEMAIL: \"[email protected]\",\n\t\tUUID: \"3\",\n\t\tMSG: \"linduxo\",\n\t})\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"msg\": queue,\n\t})\n}", "func runAllQueues(conf *config.Config) {\n\twaitFor(\n\t\tfunc() { watchPageReview(conf) },\n\t\tfunc() { watchDigitizedScans(conf) },\n\t\tfunc() {\n\t\t\t// Jobs which are exclusively disk IO are in the first runner to avoid\n\t\t\t// too much FS stuff hapenning concurrently\n\t\t\twatchJobTypes(conf,\n\t\t\t\tmodels.JobTypeArchiveBackups,\n\t\t\t\tmodels.JobTypeMoveDerivatives,\n\t\t\t\tmodels.JobTypeSyncRecursive,\n\t\t\t\tmodels.JobTypeVerifyRecursive,\n\t\t\t\tmodels.JobTypeKillDir,\n\t\t\t\tmodels.JobTypeWriteBagitManifest,\n\t\t\t)\n\t\t},\n\t\tfunc() {\n\t\t\t// Jobs which primarily use CPU are grouped next, so we aren't trying to\n\t\t\t// share CPU too much\n\t\t\twatchJobTypes(conf,\n\t\t\t\tmodels.JobTypePageSplit,\n\t\t\t\tmodels.JobTypeMakeDerivatives,\n\t\t\t)\n\t\t},\n\t\tfunc() {\n\t\t\t// Fast - but not instant - jobs are here: file renaming, hard-linking,\n\t\t\t// running templates for very simple XML output, etc. These typically\n\t\t\t// take very little CPU or disk IO, but they aren't \"critical\" jobs that\n\t\t\t// need to be real-time.\n\t\t\twatchJobTypes(conf,\n\t\t\t\tmodels.JobTypeBuildMETS,\n\t\t\t\tmodels.JobTypeCreateBatchStructure,\n\t\t\t\tmodels.JobTypeMakeBatchXML,\n\t\t\t\tmodels.JobTypeRenameDir,\n\t\t\t\tmodels.JobTypeCleanFiles,\n\t\t\t\tmodels.JobTypeRemoveFile,\n\t\t\t\tmodels.JobTypeWriteActionLog,\n\t\t\t\tmodels.JobTypeRenumberPages,\n\t\t\t\tmodels.JobTypeValidateTagManifest,\n\t\t\t\tmodels.JobTypeMarkBatchLive,\n\t\t\t)\n\t\t},\n\t\tfunc() {\n\t\t\t// Extremely fast data-setting jobs get a custom runner that operates\n\t\t\t// every second to ensure nearly real-time updates to things like a job's\n\t\t\t// workflow state\n\t\t\tvar r = jobs.NewRunner(conf, logLevel,\n\t\t\t\tmodels.JobTypeSetIssueWS,\n\t\t\t\tmodels.JobTypeSetIssueBackupLoc,\n\t\t\t\tmodels.JobTypeSetIssueLocation,\n\t\t\t\tmodels.JobTypeFinalizeBatchFlaggedIssue,\n\t\t\t\tmodels.JobTypeEmptyBatchFlaggedIssuesList,\n\t\t\t\tmodels.JobTypeIgnoreIssue,\n\t\t\t\tmodels.JobTypeSetBatchStatus,\n\t\t\t\tmodels.JobTypeSetBatchNeedsStagingPurge,\n\t\t\t\tmodels.JobTypeSetBatchLocation,\n\t\t\t\tmodels.JobTypeIssueAction,\n\t\t\t\tmodels.JobTypeBatchAction,\n\t\t\t\tmodels.JobTypeCancelJob,\n\t\t\t\tmodels.JobTypeDeleteBatch,\n\t\t\t)\n\t\t\taddRunner(r)\n\t\t\tr.Watch(time.Second * 1)\n\t\t},\n\t)\n}", "func WithQueues(queues []string) Option {\n\treturn func(opts *Options) {\n\t\topts.Queues = queues\n\t}\n}", "func Run(cfg config.Config, store storage.Store, back backend.Backend, logger log.Logger) int {\n\t// Build queue writer.\n\tqw, err := sqs.NewWriter(cfg.SQSWriter.ARN, cfg.SQSWriter.Endpoint, logger)\n\tif err != nil {\n\t\tlogger.Errorf(\"error creating SQS writer: %+v\", err)\n\t\treturn 1\n\t}\n\n\t// Build queue reader.\n\tvar maxTimeNoMsg *time.Duration\n\tif cfg.Agent.MaxNoMsgsInterval > 0 {\n\t\tt := time.Duration(cfg.Agent.MaxNoMsgsInterval) * time.Second\n\t\tmaxTimeNoMsg = &t\n\t}\n\n\t// A nil queue.MessageProcessor is passed as argument because\n\t// RunWithQueues will set it before starting reading messages.\n\tqr, err := sqs.NewReader(logger, cfg.SQSReader, maxTimeNoMsg, nil)\n\tif err != nil {\n\t\tlogger.Errorf(\"error creating SQS reader: %+v\", err)\n\t\treturn 1\n\t}\n\n\t// Run agent with SQS queues.\n\treturn RunWithQueues(cfg, store, back, qw, qr, logger)\n}", "func (h *Hospital) ConsumeQueues(ctx context.Context, t *testing.T) (events int, messages []string) {\n\tt.Helper()\n\treturn h.ConsumeQueuesWithLimit(ctx, t, -1, true)\n}", "func (acnl *Channel) setupQueues(cnl *amqp.Channel) error {\n\t/*if _, err := cnl.QueueDeclare(QueueVNFMRegister, true, acnl.cfg.queues.autodelete,\n\t\tacnl.cfg.queues.exclusive, false, nil); err != nil {\n\n\t\treturn err\n\t}\n\n\tif err := cnl.QueueBind(QueueVNFMRegister, QueueVNFMRegister, acnl.cfg.exchange.name, false, nil); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := cnl.QueueDeclare(QueueVNFMUnregister, true, acnl.cfg.queues.autodelete,\n\t\tacnl.cfg.queues.exclusive, false, nil); err != nil {\n\n\t\treturn err\n\t}\n\n\tif err := cnl.QueueBind(QueueVNFMUnregister, QueueVNFMUnregister, acnl.cfg.exchange.name, false, nil); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := cnl.QueueDeclare(QueueVNFMCoreActions, true, acnl.cfg.queues.autodelete,\n\t\tacnl.cfg.queues.exclusive, false, nil); err != nil {\n\n\t\treturn err\n\t}\n\n\tif err := cnl.QueueBind(QueueVNFMCoreActions, QueueVNFMCoreActions, acnl.cfg.exchange.name, false, nil); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := cnl.QueueDeclare(QueueVNFMCoreActionsReply, true, acnl.cfg.queues.autodelete,\n\t\tacnl.cfg.queues.exclusive, false, nil); err != nil {\n\n\t\treturn err\n\t}\n\n\tif err := cnl.QueueBind(QueueVNFMCoreActionsReply, QueueVNFMCoreActionsReply, acnl.cfg.exchange.name, false, nil); err != nil {\n\t\treturn err\n\t}*/\n\n\t// is this needed?\n\tif _, err := cnl.QueueDeclare(acnl.cfg.queues.generic, true, acnl.cfg.queues.autodelete,\n\t\tacnl.cfg.queues.exclusive, false, nil); err != nil {\n\n\t\treturn err\n\t}\n\n\tif err := cnl.QueueBind(acnl.cfg.queues.generic, acnl.cfg.queues.generic, acnl.cfg.exchange.name, false, nil); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (b *backend) Queues(ctx context.Context, qq *entroq.QueuesQuery) (map[string]int, error) {\n\tresp, err := pb.NewEntroQClient(b.conn).Queues(ctx, &pb.QueuesRequest{\n\t\tMatchPrefix: qq.MatchPrefix,\n\t\tMatchExact: qq.MatchExact,\n\t\tLimit: int32(qq.Limit),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"grpc queues: %w\", unpackGRPCError(err))\n\t}\n\tqs := make(map[string]int)\n\tfor _, q := range resp.Queues {\n\t\tqs[q.Name] = int(q.NumTasks)\n\t}\n\treturn qs, nil\n}", "func deleteQueues(ctx *TestContext) {\n\tfor _, q := range ctx.Queues {\n\t\tDeleteQueue(ctx, q)\n\t}\n}", "func NewQueueRunner(\n\texec execer.Execer,\n\tfilerMap runner.RunTypeMap,\n\toutput runner.OutputCreator,\n\tcapacity int,\n\tstat stats.StatsReceiver,\n\tdirMonitor *stats.DirsMonitor,\n\trID runner.RunnerID,\n\tpreprocessors []func() error,\n\tpostprocessors []func() error,\n\tuploader LogUploader,\n) runner.Service {\n\tif stat == nil {\n\t\tstat = stats.NilStatsReceiver()\n\t}\n\n\t//FIXME(jschiller): proper history config rather than keying off of capacity and if this is a SingleRunner.\n\thistory := 1\n\tif capacity > 0 {\n\t\thistory = 0 // unlimited if acting as a queue (vs single runner).\n\t} else if capacity == 0 {\n\t\tcapacity = 1 // singleRunner, override capacity so it can actually run a command.\n\t}\n\n\tstatusManager := NewStatusManager(history)\n\tinv := NewInvoker(exec, filerMap, output, stat, dirMonitor, rID, preprocessors, postprocessors, uploader)\n\n\tcontroller := &QueueController{\n\t\tstatusManager: statusManager,\n\t\tinv: inv,\n\t\tfilerMap: filerMap,\n\t\tupdateReq: make(map[runner.RunType]bool),\n\t\tcapacity: capacity,\n\t\treqCh: make(chan interface{}),\n\t\tupdateCh: make(chan interface{}),\n\t\tcancelTimerCh: make(chan interface{}),\n\t}\n\trun := &Service{controller, statusManager}\n\n\t// QueueRunner waits on filers with InitDoneChannels defined to return,\n\t// and will not serve requests if any return an error\n\tvar wg sync.WaitGroup\n\tvar initErr error = nil\n\twait := false\n\n\tfor t, f := range filerMap {\n\t\tif f.IDC != nil {\n\t\t\tlog.Infof(\"Starting goroutine to wait on init for filer %v\", t)\n\t\t\twg.Add(1)\n\t\t\twait = true\n\n\t\t\tgo func(rt runner.RunType, idc snapshot.InitDoneCh) {\n\t\t\t\terr := <-idc\n\t\t\t\tif err != nil {\n\t\t\t\t\tinitErr = err\n\t\t\t\t\tlog.Errorf(\"Init channel for filer %v returned error: %s\", rt, err)\n\t\t\t\t}\n\t\t\t\twg.Done()\n\t\t\t}(t, f.IDC)\n\t\t}\n\t}\n\n\tif wait {\n\t\t// Wait for initialization to complete in a new goroutine to let this constructor return\n\t\tgo func() {\n\t\t\twg.Wait()\n\t\t\tif initErr != nil {\n\t\t\t\tstat.Counter(stats.WorkerDownloadInitFailure).Inc(1)\n\t\t\t\tstatusManager.UpdateService(runner.ServiceStatus{Initialized: false, Error: initErr})\n\t\t\t} else {\n\t\t\t\tstatusManager.UpdateService(runner.ServiceStatus{Initialized: true, IsHealthy: true})\n\t\t\t\tstat.Gauge(stats.WorkerUnhealthy).Update(0)\n\t\t\t\tcontroller.startUpdateTickers()\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tstatusManager.UpdateService(runner.ServiceStatus{Initialized: true, IsHealthy: true})\n\t\tstat.Gauge(stats.WorkerUnhealthy).Update(0)\n\t\tcontroller.startUpdateTickers()\n\t}\n\n\tgo controller.loop()\n\n\treturn run\n}", "func (q *queueDriverDefault) Run(ctx context.Context) error {\n\tvar (\n\t\tmsg etl.Message\n\t\tsize int\n\t\terr error\n\t\tok bool\n\t)\n\tfor {\n\t\tfor true {\n\t\t\t// dequeue message\n\t\t\tmsg, size, ok = q.dequeue()\n\t\t\t// if no message was dequeued, break and wait for new message in a queue\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// send dequeued message to output channel\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tcase q.outputCh <- msg:\n\t\t\t}\n\n\t\t\t// call dequeue hooks\n\t\t\terr = q.callDequeueHooks(ctx, size)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// wait until new item is enqueued\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-q.enqueuedCh:\n\t\t}\n\t}\n\n\treturn nil\n}", "func (q *QueueMethod) Setup() error {\n\tif err := q.declareExchange(q.Provider.AMQP.DeadLetterExchange, \"direct\", nil); err != nil {\n\t\treturn fmt.Errorf(\"declare exchange failed: name: %s, type: %s, message: %v\", q.Provider.AMQP.DeadLetterExchange, \"direct\", err)\n\t}\n\tif err := q.declareExchange(q.Provider.AMQP.ShardingQueueExchange, \"x-modulus-hash\", nil); err != nil {\n\t\treturn fmt.Errorf(\"declare exchange failed: name: %s, type: %s, message: %v\", q.Provider.AMQP.ShardingQueueExchange, \"x-modulus-hash\", err)\n\t}\n\tif err := q.declareExchange(q.Provider.AMQP.DelayMessageExchange, \"x-delayed-message\", amqp.Table{\"x-delayed-type\": \"x-modulus-hash\"}); err != nil {\n\t\treturn fmt.Errorf(\"declare exchange failed: name: %s, type: %s, message: %v\", q.Provider.AMQP.DelayMessageExchange, \"x-delayed-message\", err)\n\t}\n\tif err := q.bindExchange(q.Provider.AMQP.DelayMessageExchange, q.Provider.AMQP.ShardingQueueExchange, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"bind exchange failed: name: %s to %s, message: %v\", q.Provider.AMQP.DelayMessageExchange, q.Provider.AMQP.ShardingQueueExchange, err)\n\t}\n\n\tif err := q.createPolicy(RabbitMQHaMode, \"\", \"queues\", Definition{\n\t\tHaMode: \"exactly\",\n\t\tHaParam: 2,\n\t\tHaSyncMode: \"automatic\",\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"create policy failed: mode: %s, message: %v\", RabbitMQHaMode, err)\n\t}\n\n\tif err := q.createPolicy(RabbitMQShardMode, \"^sns.sharding$\", \"exchanges\", Definition{\n\t\tShardsPerNode: 2,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"create policy failed: mode: %s, message: %v\", RabbitMQShardMode, err)\n\t}\n\n\treturn nil\n}", "func (s *UserDataFilters) SetQueues(v []*string) *UserDataFilters {\n\ts.Queues = v\n\treturn s\n}", "func (s *Filters) SetQueues(v []*string) *Filters {\n\ts.Queues = v\n\treturn s\n}", "func (s *SQSServer) pollQueues(pollctx, taskctx context.Context, queues []QueueConf) error {\n\tfor _, qconf := range queues {\n\t\tq, err := s.getQueue(pollctx, qconf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treq := &sqs.GetQueueAttributesInput{\n\t\t\tAttributeNames: []types.QueueAttributeName{(\"VisibilityTimeout\")},\n\t\t\tQueueUrl: &q.url,\n\t\t}\n\t\tresp, err := s.sqsSrv(q.QueueConf).GetQueueAttributes(pollctx, req)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to get queue attributes for '%s' - %s\", q.Name, err.Error())\n\t\t}\n\t\tto := resp.Attributes[\"VisibilityTimeout\"]\n\t\tif to == \"\" {\n\t\t\treturn fmt.Errorf(\"No visibility timeout returned by SQS for queue '%s'\", q.Name)\n\t\t}\n\t\tvisTimeout, err := strconv.Atoi(to)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to convert visibility timeout from '%s' to int - '%s'\", to, err.Error())\n\t\t}\n\t\t// Each queue runs in a dedicated go routine.\n\t\tgo func(vt int32) {\n\t\t\ts.queuePollers.Add(1)\n\t\t\tdefer s.queuePollers.Done()\n\t\t\ts.run(pollctx, taskctx, q, vt)\n\t\t}(int32(visTimeout))\n\t}\n\n\treturn nil\n}", "func CreateQueues(ctx *TestContext) {\n\tBy(\"Creating Queues\")\n\n\tfor _, queue := range ctx.Queues {\n\t\tCreateQueue(ctx, queue)\n\t}\n\n\t// wait for all queues state open\n\ttime.Sleep(3 * time.Second)\n}", "func (m *MockSQSAPI) ListQueues(arg0 *sqs.ListQueuesInput) (*sqs.ListQueuesOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListQueues\", arg0)\n\tret0, _ := ret[0].(*sqs.ListQueuesOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func SNSSQSExistingQueueAndTopic(t *testing.T) {\n\tconsumerGroup1 := watcher.NewUnordered()\n\n\t// Set the partition key on all messages so they are written to the same partition. This allows for checking of ordered messages.\n\tmetadata := map[string]string{\n\t\tmessageKey: partition0,\n\t}\n\n\t// subscriber of the given topic\n\tsubscriberApplication := func(appID string, topicName string, messagesWatcher *watcher.Watcher) app.SetupFn {\n\t\treturn func(ctx flow.Context, s common.Service) error {\n\t\t\t// Simulate periodic errors.\n\t\t\tsim := simulate.PeriodicError(ctx, 100)\n\t\t\t// Setup the /orders event handler.\n\t\t\treturn multierr.Combine(\n\t\t\t\ts.AddTopicEventHandler(&common.Subscription{\n\t\t\t\t\tPubsubName: pubsubName,\n\t\t\t\t\tTopic: topicName,\n\t\t\t\t\tRoute: \"/orders\",\n\t\t\t\t}, func(_ context.Context, e *common.TopicEvent) (retry bool, err error) {\n\t\t\t\t\tif err := sim(); err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\n\t\t\t\t\t// Track/Observe the data of the event.\n\t\t\t\t\tmessagesWatcher.Observe(e.Data)\n\t\t\t\t\tctx.Logf(\"Message Received appID: %s,pubsub: %s, topic: %s, id: %s, data: %s\", appID, e.PubsubName, e.Topic, e.ID, e.Data)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t}\n\n\tpublishMessages := func(metadata map[string]string, sidecarName string, topicName string, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// prepare the messages\n\t\t\tmessages := make([]string, numMessages)\n\t\t\tfor i := range messages {\n\t\t\t\tmessages[i] = fmt.Sprintf(\"partitionKey: %s, message for topic: %s, index: %03d, uniqueId: %s\", metadata[messageKey], topicName, i, uuid.New().String())\n\t\t\t}\n\n\t\t\t// add the messages as expectations to the watchers\n\t\t\tfor _, messageWatcher := range messageWatchers {\n\t\t\t\tmessageWatcher.ExpectStrings(messages...)\n\t\t\t}\n\n\t\t\t// get the sidecar (dapr) client\n\t\t\tclient := sidecar.GetClient(ctx, sidecarName)\n\n\t\t\t// publish messages\n\t\t\tctx.Logf(\"Publishing messages. sidecarName: %s, topicName: %s\", sidecarName, topicName)\n\n\t\t\tvar publishOptions dapr.PublishEventOption\n\n\t\t\tif metadata != nil {\n\t\t\t\tpublishOptions = dapr.PublishEventWithMetadata(metadata)\n\t\t\t}\n\n\t\t\tfor _, message := range messages {\n\t\t\t\tctx.Logf(\"Publishing: %q\", message)\n\t\t\t\tvar err error\n\n\t\t\t\tif publishOptions != nil {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message, publishOptions)\n\t\t\t\t} else {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message)\n\t\t\t\t}\n\t\t\t\trequire.NoError(ctx, err, \"SNSSQSExistingQueueAndTopic - error publishing message\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tassertMessages := func(timeout time.Duration, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// assert for messages\n\t\t\tfor _, m := range messageWatchers {\n\t\t\t\tif !m.Assert(ctx, 25*timeout) {\n\t\t\t\t\tctx.Errorf(\"SNSSQSExistingQueueAndTopic - message assertion failed for watcher: %#v\\n\", m)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tflow.New(t, \"SNSSQS certification - Existing Queue Existing Topic\").\n\n\t\t// Run subscriberApplication app1\n\t\tStep(app.Run(appID1, fmt.Sprintf(\":%d\", appPort+portOffset*3),\n\t\t\tsubscriberApplication(appID1, existingTopic, consumerGroup1))).\n\n\t\t// Run the Dapr sidecar with ConsumerID \"PUBSUB_AWS_SNSSQS_QUEUE_3\"\n\t\tStep(sidecar.Run(sidecarName1,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/existing_queue\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort+portOffset*3)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort+portOffset*3)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort+portOffset*3)),\n\t\t\t\tembedded.WithProfilePort(strconv.Itoa(runtime.DefaultProfilePort+portOffset*3)),\n\t\t\t)...,\n\t\t)).\n\t\tStep(fmt.Sprintf(\"publish messages to existingTopic: %s\", existingTopic), publishMessages(metadata, sidecarName1, existingTopic, consumerGroup1)).\n\t\tStep(\"wait\", flow.Sleep(30*time.Second)).\n\t\tStep(\"verify if app1 has recevied messages published to newly created topic\", assertMessages(10*time.Second, consumerGroup1)).\n\t\tRun()\n}", "func groomQueues(queues *Queues) (err kv.Error) {\n\tfor qName, qDetails := range *queues {\n\t\t// If we have enough runners drop the queue as it needs nothing done to it\n\t\tif len(qDetails.NodeGroup) == 0 || qDetails.Running >= qDetails.Ready+qDetails.NotVisible {\n\t\t\tif logger.IsTrace() {\n\t\t\t\tlogger.Trace(\"queue already handled\", \"queue\", qName, \"stack\", stack.Trace().TrimRuntime())\n\t\t\t}\n\t\t\tdelete(*queues, qName)\n\t\t}\n\t}\n\treturn nil\n}", "func BenchmarkEndToEndMultipleQueues(b *testing.B) {\n\t// number of tasks to create for each queue\n\tconst (\n\t\thighCount = 20000\n\t\tdefaultCount = 20000\n\t\tlowCount = 20000\n\t)\n\tfor n := 0; n < b.N; n++ {\n\t\tb.StopTimer() // begin setup\n\t\tsetup(b)\n\t\tredis := &RedisClientOpt{\n\t\t\tAddr: redisAddr,\n\t\t\tDB: redisDB,\n\t\t}\n\t\tclient := NewClient(redis)\n\t\tbg := NewBackground(redis, &Config{\n\t\t\tConcurrency: 10,\n\t\t\tQueues: map[string]int{\n\t\t\t\t\"high\": 6,\n\t\t\t\t\"default\": 3,\n\t\t\t\t\"low\": 1,\n\t\t\t},\n\t\t})\n\t\t// Create a bunch of tasks\n\t\tfor i := 0; i < highCount; i++ {\n\t\t\tt := NewTask(fmt.Sprintf(\"task%d\", i), map[string]interface{}{\"data\": i})\n\t\t\tif err := client.Enqueue(t, Queue(\"high\")); err != nil {\n\t\t\t\tb.Fatalf(\"could not enqueue a task: %v\", err)\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < defaultCount; i++ {\n\t\t\tt := NewTask(fmt.Sprintf(\"task%d\", i), map[string]interface{}{\"data\": i})\n\t\t\tif err := client.Enqueue(t); err != nil {\n\t\t\t\tb.Fatalf(\"could not enqueue a task: %v\", err)\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < lowCount; i++ {\n\t\t\tt := NewTask(fmt.Sprintf(\"task%d\", i), map[string]interface{}{\"data\": i})\n\t\t\tif err := client.Enqueue(t, Queue(\"low\")); err != nil {\n\t\t\t\tb.Fatalf(\"could not enqueue a task: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(highCount + defaultCount + lowCount)\n\t\thandler := func(ctx context.Context, t *Task) error {\n\t\t\twg.Done()\n\t\t\treturn nil\n\t\t}\n\t\tb.StartTimer() // end setup\n\n\t\tbg.start(HandlerFunc(handler))\n\t\twg.Wait()\n\n\t\tb.StopTimer() // begin teardown\n\t\tbg.stop()\n\t\tb.StartTimer() // end teardown\n\t}\n}", "func (q *SQSQueue) Queue(ctx context.Context, h Headers, b Body) error {\n\t_, span := trace.StartSpan(ctx, \"sqs/Queue\")\n\tdefer span.End()\n\n\tbody, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdelay := aws.Int64(0)\n\tattributes := make(map[string]*sqs.MessageAttributeValue)\n\n\tfor k, v := range h {\n\t\tattributes[k] = &sqs.MessageAttributeValue{\n\t\t\tDataType: aws.String(\"String\"),\n\t\t\tStringValue: aws.String(v),\n\t\t}\n\t}\n\n\tmsg := &sqs.SendMessageInput{\n\t\tDelaySeconds: delay,\n\t\tMessageAttributes: attributes,\n\t\tMessageBody: aws.String(string(body)),\n\t\tQueueUrl: aws.String(q.name),\n\t}\n\n\t_, err = q.svc.SendMessage(msg)\n\treturn err\n}", "func NewQueue(qname string, taskId string) (*Queue, error) {\n q := &Queue{}\n q.StdoutChan = make(chan []byte, QUEUE_SIZE)\n q.StderrChan = make(chan []byte, QUEUE_SIZE)\n q.exitChan = make(chan string)\n q.finishChan = make(chan bool)\n\n s, err := aws.NewSqs(qname, taskId)\n q.awsSqs = s\n\n return q, err\n}", "func TestUnmarshalSQSARN(t *testing.T) {\n\trootPath, err := newTestConfig(globalMinioDefaultRegion)\n\tif err != nil {\n\t\tt.Fatalf(\"unable initialize config file, %s\", err)\n\t}\n\tdefer os.RemoveAll(rootPath)\n\n\ttestCases := []struct {\n\t\tqueueARN string\n\t\tType string\n\t}{\n\t\t// Valid webhook queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:webhook\",\n\t\t\tType: \"webhook\",\n\t\t},\n\t\t// Valid redis queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:redis\",\n\t\t\tType: \"redis\",\n\t\t},\n\t\t// Valid elasticsearch queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:elasticsearch\",\n\t\t\tType: \"elasticsearch\",\n\t\t},\n\t\t// Valid amqp queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:amqp\",\n\t\t\tType: \"amqp\",\n\t\t},\n\t\t// Valid mqtt queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:mqtt\",\n\t\t\tType: \"mqtt\",\n\t\t},\n\t\t// Invalid empty queue arn.\n\t\t{\n\t\t\tqueueARN: \"\",\n\t\t\tType: \"\",\n\t\t},\n\t\t// Partial queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:\",\n\t\t\tType: \"\",\n\t\t},\n\t\t// Invalid queue service value.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:*\",\n\t\t\tType: \"\",\n\t\t},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tmSqs := unmarshalSqsARN(testCase.queueARN)\n\t\tif testCase.Type != mSqs.Type {\n\t\t\tt.Errorf(\"Test %d: Expected \\\"%s\\\", got \\\"%s\\\"\", i+1, testCase.Type, mSqs.Type)\n\t\t}\n\t}\n\n\t// Test when the server region is set.\n\trootPath, err = newTestConfig(\"us-east-1\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable initialize config file, %s\", err)\n\t}\n\tdefer os.RemoveAll(rootPath)\n\n\ttestCases = []struct {\n\t\tqueueARN string\n\t\tType string\n\t}{\n\t\t// Incorrect region in ARN returns empty mSqs.Type\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-west-1:1:webhook\",\n\t\t\tType: \"\",\n\t\t},\n\t\t// Correct regionin ARN returns valid mSqs.Type\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:webhook\",\n\t\t\tType: \"webhook\",\n\t\t},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tmSqs := unmarshalSqsARN(testCase.queueARN)\n\t\tif testCase.Type != mSqs.Type {\n\t\t\tt.Errorf(\"Test %d: Expected \\\"%s\\\", got \\\"%s\\\"\", i+1, testCase.Type, mSqs.Type)\n\t\t}\n\t}\n}", "func (mr *MockSQSAPIMockRecorder) ListQueues(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListQueues\", reflect.TypeOf((*MockSQSAPI)(nil).ListQueues), arg0)\n}", "func (b *backend) Queues(ctx context.Context, qq *entroq.QueuesQuery) (map[string]int, error) {\n\tdefer un(lock(b))\n\n\tqs := make(map[string]int)\n\tfor q, items := range b.heaps {\n\t\tif len(qq.MatchPrefix) != 0 || len(qq.MatchExact) != 0 {\n\t\t\tif !matchesPrefix(q, qq.MatchPrefix...) && !matchesExact(q, qq.MatchExact...) {\n\t\t\t\t// no match\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tqs[q] = items.Len()\n\t\tif qq.Limit > 0 && len(qs) >= qq.Limit {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn qs, nil\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue_Config) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue_Config\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetQueues(c *gin.Context) {\n\t//TODO: create a while both back and front until value is != nil\n\tsize := len(queue)\n\tlog.Printf(\"squeue: %v\", queue)\n\tif size == 0 {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"msg\": \"queue don't have any item!\",\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"queues\": queue,\n\t})\n\tlog.Printf(\"equeue: %v\", queue)\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue_Config) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue_Config\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ooc *MockOpenoltClient) RemoveTrafficQueues(ctx context.Context, in *tech_profile.TrafficQueues, opts ...grpc.CallOption) (*openolt.Empty, error) {\n\treturn &openolt.Empty{}, nil\n}", "func (s *Storage) Run() {\n\tfor _, q := range s.queues {\n\t\tgo q.Run()\n\t}\n}", "func EnsureQueue(ctx context.Context, cli sqsiface.SQSAPI) (string /*arn*/, error) {\n\tsrc := commonv1alpha1.ReconcilableFromContext(ctx)\n\ttypedSrc := src.(*v1alpha1.AWSS3Source)\n\n\tstatus := &typedSrc.Status\n\n\tif dest := typedSrc.Spec.Destination; dest != nil {\n\t\tif userProvidedQueue := dest.SQS; userProvidedQueue != nil {\n\t\t\tstatus.QueueARN = &userProvidedQueue.QueueARN\n\t\t\treturn userProvidedQueue.QueueARN.String(), nil\n\t\t}\n\t}\n\n\tqueueName := queueName(typedSrc)\n\n\tqueueURL, err := sqs.QueueURL(cli, queueName)\n\tswitch {\n\tcase isNotFound(err):\n\t\tqueueURL, err = sqs.CreateQueue(cli, queueName, queueTags(typedSrc))\n\t\tif err != nil {\n\t\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Unable to create SQS queue\")\n\t\t\treturn \"\", fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedQueue,\n\t\t\t\t\"Error creating SQS queue for event notifications: %s\", toErrMsg(err)))\n\t\t}\n\t\tevent.Normal(ctx, ReasonQueueCreated, \"Created SQS queue %q\", queueURL)\n\n\tcase isAWSError(err):\n\t\t// All documented API errors require some user intervention and\n\t\t// are not to be retried.\n\t\t// https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Request to SQS API got rejected\")\n\t\treturn \"\", controller.NewPermanentError(reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Failed to synchronize SQS queue: %s\", toErrMsg(err)))\n\n\tcase err != nil:\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Cannot synchronize SQS queue\")\n\t\treturn \"\", fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Failed to determine URL of SQS queue: %s\", toErrMsg(err)))\n\t}\n\n\tgetAttrs := []string{awssqs.QueueAttributeNameQueueArn, awssqs.QueueAttributeNamePolicy}\n\tqueueAttrs, err := sqs.QueueAttributes(cli, queueURL, getAttrs)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getting attributes of SQS queue: %w\", err)\n\t}\n\n\tqueueARN := queueAttrs[awssqs.QueueAttributeNameQueueArn]\n\n\tqueueARNStruct, err := arnStrToARN(queueARN)\n\tif err != nil {\n\t\treturn queueARN, fmt.Errorf(\"converting ARN string to structured ARN: %w\", err)\n\t}\n\n\t// it is essential that we propagate the queue's ARN here,\n\t// otherwise BuildAdapter() won't be able to configure the SQS\n\t// adapter properly\n\tstatus.QueueARN = queueARNStruct\n\n\tcurrentPol := unmarshalQueuePolicy(queueAttrs[awssqs.QueueAttributeNamePolicy])\n\tdesiredPol := makeQueuePolicy(queueARN, typedSrc)\n\n\tif err := syncQueuePolicy(cli, queueURL, currentPol, desiredPol); err != nil {\n\t\tstatus.MarkNotSubscribed(v1alpha1.AWSS3ReasonAPIError, \"Cannot synchronize SQS queue\")\n\t\treturn queueARN, fmt.Errorf(\"%w\", reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedSubscribe,\n\t\t\t\"Error synchronizing policy of SQS queue: %s\", toErrMsg(err)))\n\t}\n\n\treturn queueARN, nil\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue_Config) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue_Config\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func fakeMessageQueue() []message {\n\treturn []message{\n\t\tmessage{Type: \"REGULAR\", Text: \"Golang\"}, // will invoke regularConsumer\n\t\tmessage{Type: \"REVERSE\", Text: \"Golang\"}, // will invoke reverseConsumer\n\t\tmessage{Type: \"ANY\", Text: \"Golang\"}, // will throw error because there is no consumer\n\t}\n}", "func QueueStats(ctx context.Context, t *testing.T, client *entroq.EntroQ, qPrefix string) {\n\tnothingClaimedQueue := path.Join(qPrefix, \"queue-1\")\n\tpartiallyClaimedQueue := path.Join(qPrefix, \"queue-2\")\n\n\tif _, _, err := client.Modify(ctx,\n\t\tentroq.InsertingInto(nothingClaimedQueue),\n\t\tentroq.InsertingInto(nothingClaimedQueue),\n\t\tentroq.InsertingInto(partiallyClaimedQueue),\n\t\tentroq.InsertingInto(partiallyClaimedQueue),\n\t\tentroq.InsertingInto(partiallyClaimedQueue),\n\t); err != nil {\n\t\tt.Fatalf(\"Insert into queues: %v\", err)\n\t}\n\n\t// Now claim something.\n\tif _, err := client.Claim(ctx, entroq.From(partiallyClaimedQueue)); err != nil {\n\t\tt.Fatalf(\"Couldn't claim: %v\", err)\n\t}\n\n\tgot, err := client.QueueStats(ctx, entroq.MatchPrefix(qPrefix))\n\tif err != nil {\n\t\tt.Fatalf(\"Queue stats error: %v\", err)\n\t}\n\n\twant := map[string]*entroq.QueueStat{\n\t\tnothingClaimedQueue: {\n\t\t\tName: nothingClaimedQueue,\n\t\t\tSize: 2,\n\t\t\tClaimed: 0,\n\t\t\tAvailable: 2,\n\t\t\tMaxClaims: 0,\n\t\t},\n\t\tpartiallyClaimedQueue: {\n\t\t\tName: partiallyClaimedQueue,\n\t\t\tSize: 3,\n\t\t\tClaimed: 1,\n\t\t\tAvailable: 2,\n\t\t\tMaxClaims: 1,\n\t\t},\n\t}\n\n\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\tt.Fatalf(\"QueueStats (-want +got):\\n%v\", diff)\n\t}\n}", "func LoadSimpleQueue(ctx context.Context, metaStorage storage.Storage, subscriberStorage storage.Storage,\n\tmarkerBlockDataStorage map[string]storage.Storage,\n\tidGenerator *mft.G) (q *SimpleQueue, err *mft.Error) {\n\tif idGenerator == nil {\n\t\tidGenerator = &mft.G{}\n\t}\n\n\tq = &SimpleQueue{\n\t\tMetaStorage: metaStorage,\n\t\tSubscriberStorage: subscriberStorage,\n\t\tMarkerBlockDataStorage: markerBlockDataStorage,\n\t\tBlocks: make([]*SimpleQueueBlock, 0),\n\t\tIDGenerator: idGenerator,\n\n\t\tSaveBlocks: make(map[int64]*SimpleQueueBlock),\n\n\t\tSubscribers: &SimpleQueueSubscribers{\n\t\t\tSubscribersInfo: make(map[string]*SimpleQueueSubscriberInfo),\n\t\t\tReplicaSubscribers: make(map[string]struct{}),\n\t\t},\n\t}\n\n\tbody, err := metaStorage.Get(ctx, MetaDataFileName)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ter0 := json.Unmarshal(body, q)\n\tif er0 != nil {\n\t\treturn nil, GenerateErrorE(10030000, er0)\n\t}\n\n\tq.SaveRv = idGenerator.RvGetPart()\n\tq.ChangesRv = q.SaveRv\n\n\tfor i := 0; i < len(q.Blocks); i++ {\n\t\tq.Blocks[i].IsUnload = true\n\t\tq.Blocks[i].SaveRv = q.SaveRv\n\t\tq.Blocks[i].ChangesRv = q.SaveRv\n\t}\n\n\tq.Subscribers.SaveRv = q.SaveRv\n\tq.Subscribers.ChangesRv = q.SaveRv\n\n\tif q.SubscriberStorage != nil {\n\t\tok, err := q.SubscriberStorage.Exists(ctx, SubscribersFileName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif ok {\n\t\t\tbodyS, err := q.SubscriberStorage.Get(ctx, SubscribersFileName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\ter1 := json.Unmarshal(bodyS, q.Subscribers)\n\t\t\tif er1 != nil {\n\t\t\t\treturn nil, GenerateErrorE(10030001, er1)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn q, nil\n}", "func SetQueueSettings(ctx *context.Context) {\n\tqid := ctx.ParamsInt64(\"qid\")\n\tmq := queue.GetManager().GetManagedQueue(qid)\n\tif mq == nil {\n\t\tctx.Status(http.StatusNotFound)\n\t\treturn\n\t}\n\tif _, ok := mq.Managed.(queue.ManagedPool); !ok {\n\t\tctx.Flash.Error(ctx.Tr(\"admin.monitor.queue.pool.none\"))\n\t\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n\t\treturn\n\t}\n\n\tmaxNumberStr := ctx.FormString(\"max-number\")\n\tnumberStr := ctx.FormString(\"number\")\n\ttimeoutStr := ctx.FormString(\"timeout\")\n\n\tvar err error\n\tvar maxNumber, number int\n\tvar timeout time.Duration\n\tif len(maxNumberStr) > 0 {\n\t\tmaxNumber, err = strconv.Atoi(maxNumberStr)\n\t\tif err != nil {\n\t\t\tctx.Flash.Error(ctx.Tr(\"admin.monitor.queue.settings.maxnumberworkers.error\"))\n\t\t\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n\t\t\treturn\n\t\t}\n\t\tif maxNumber < -1 {\n\t\t\tmaxNumber = -1\n\t\t}\n\t} else {\n\t\tmaxNumber = mq.MaxNumberOfWorkers()\n\t}\n\n\tif len(numberStr) > 0 {\n\t\tnumber, err = strconv.Atoi(numberStr)\n\t\tif err != nil || number < 0 {\n\t\t\tctx.Flash.Error(ctx.Tr(\"admin.monitor.queue.settings.numberworkers.error\"))\n\t\t\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tnumber = mq.BoostWorkers()\n\t}\n\n\tif len(timeoutStr) > 0 {\n\t\ttimeout, err = time.ParseDuration(timeoutStr)\n\t\tif err != nil {\n\t\t\tctx.Flash.Error(ctx.Tr(\"admin.monitor.queue.settings.timeout.error\"))\n\t\t\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n\t\t\treturn\n\t\t}\n\t} else {\n\t\ttimeout = mq.BoostTimeout()\n\t}\n\n\tmq.SetPoolSettings(maxNumber, number, timeout)\n\tctx.Flash.Success(ctx.Tr(\"admin.monitor.queue.settings.changed\"))\n\tctx.Redirect(setting.AppSubURL + \"/admin/monitor/queue/\" + strconv.FormatInt(qid, 10))\n}", "func QueueMatch(ctx context.Context, t *testing.T, client *entroq.EntroQ, qPrefix string) {\n\tqueue1 := path.Join(qPrefix, \"queue-1\")\n\tqueue2 := path.Join(qPrefix, \"queue-2\")\n\tqueue3 := path.Join(qPrefix, \"queue-3\")\n\tquirkyQueue := path.Join(qPrefix, \"quirky=queue\")\n\n\twantQueues := map[string]int{\n\t\tqueue1: 1,\n\t\tqueue2: 2,\n\t\tqueue3: 3,\n\t\tquirkyQueue: 1,\n\t}\n\n\t// Add tasks so that queues have a certain number of things in them, as above.\n\tvar toInsert []entroq.ModifyArg\n\tfor q, n := range wantQueues {\n\t\tfor i := 0; i < n; i++ {\n\t\t\ttoInsert = append(toInsert, entroq.InsertingInto(q))\n\t\t}\n\t}\n\tinserted, _, err := client.Modify(ctx, toInsert...)\n\tif err != nil {\n\t\tt.Fatalf(\"in QueueMatch - inserting empty tasks: %v\", err)\n\t}\n\n\t// Check that we got everything inserted.\n\tif want, got := len(inserted), len(toInsert); want != got {\n\t\tt.Fatalf(\"in QueueMatch - want %d inserted, got %d\", want, got)\n\t}\n\n\t// Check that we can get exact numbers for all of the above using MatchExact.\n\tfor q, n := range wantQueues {\n\t\tqs, err := client.Queues(ctx, entroq.MatchExact(q))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"QueueMatch single - getting queue: %v\", err)\n\t\t}\n\t\tif len(qs) != 1 {\n\t\t\tt.Errorf(\"QueueMatch single - expected 1 entry, got %d\", len(qs))\n\t\t}\n\t\tif want, got := n, qs[q]; want != got {\n\t\t\tt.Errorf(\"QueueMatch single - expected %d values in queue %q, got %d\", want, q, got)\n\t\t}\n\t}\n\n\t// Check that passing multiple exact matches works properly.\n\tmultiExactCases := []struct {\n\t\tq1 string\n\t\tq2 string\n\t}{\n\t\t{queue1, queue2},\n\t\t{queue1, queue3},\n\t\t{quirkyQueue, queue2},\n\t\t{\"bogus\", queue3},\n\t}\n\n\tfor _, c := range multiExactCases {\n\t\tqs, err := client.Queues(ctx, entroq.MatchExact(c.q1), entroq.MatchExact(c.q2))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"QueueMatch multi - getting multiple queues: %v\", err)\n\t\t}\n\t\tif len(qs) > 2 {\n\t\t\tt.Errorf(\"QueueMatch multi - expected no more than 2 entries, got %d\", len(qs))\n\t\t}\n\t\twant1, want2 := wantQueues[c.q1], wantQueues[c.q2]\n\t\tif got1, got2 := qs[c.q1], qs[c.q2]; want1 != got1 || want2 != got2 {\n\t\t\tt.Errorf(\"QueueMatch multi - wanted %q:%d, %q:%d, got %q:%d, %q:%d\", c.q1, want1, c.q2, want2, c.q1, got1, c.q2, got2)\n\t\t}\n\t}\n\n\t// Check prefix matching.\n\tprefixCases := []struct {\n\t\tprefix string\n\t\tqn int\n\t\tn int\n\t}{\n\t\t{path.Join(qPrefix, \"queue-\"), 3, 6},\n\t\t{path.Join(qPrefix, \"qu\"), 4, 7},\n\t\t{path.Join(qPrefix, \"qui\"), 1, 1},\n\t}\n\n\tfor _, c := range prefixCases {\n\t\tqs, err := client.Queues(ctx, entroq.MatchPrefix(c.prefix))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"QueueMatch prefix - queues error: %v\", err)\n\t\t}\n\t\tif want, got := c.qn, len(qs); want != got {\n\t\t\tt.Errorf(\"QueueMatch prefix - want %d queues, got %d\", want, got)\n\t\t}\n\t\ttot := 0\n\t\tfor _, n := range qs {\n\t\t\ttot += n\n\t\t}\n\t\tif want, got := c.n, tot; want != got {\n\t\t\tt.Errorf(\"QueueMatch prefix - want %d total items, got %d\", want, got)\n\t\t}\n\t}\n}", "func TestSQSQueue_PutMessages_Success2(t *testing.T) {\n\tmsgCount = 0\n\tmockedQueue, assertStubs := newMockQueue(func(client *mockSQS) {\n\t\tclient.On(\"SendMessageBatch\", mock.Anything).Times(2)\n\t\t// FIXME - id of messages are generated uuid so we can't expect the value\n\t})\n\n\terr := mockedQueue.PutMessages(make([]string, 15))\n\n\tassert.Nil(t, err)\n\tassert.Equal(t, msgCount, 15)\n\tassertStubs(t)\n}", "func setupQueue(client *redis.Client) error {\n\t// ping the queue\n\terr := pingQueue(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Test_Queue_Two(t *testing.T) {\n\tq := NewQueue()\n\n\tq.Push(\"Foo\")\n\tq.Push(\"Bar\")\n\n\t//Size should now be 2\n\tif q.Size() != 2 {\n\t\tt.Error(\"Size != 2\")\n\t} else {\n\t\tt.Log(\"Two: Size == 2 test passed\")\n\t}\n\n\tpop, err := q.Pop()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t//We should now get Foo back when we Pop\n\tif pop != \"Foo\" {\n\t\tt.Error(\"Two: Pop() did not pass\")\n\t} else {\n\t\tt.Log(\"Two: Foo Passed\")\n\t}\n\n\t//Size should now be 1\n\tif q.Size() != 1 {\n\t\tt.Error(\"Size != 1\")\n\t} else {\n\t\tt.Log(\"Two: Size == 1 test passed\")\n\t}\n\n\t//Pop another from the queue\n\tpop, err = q.Pop()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t//We should now get bar back when we Pop\n\tif pop != \"Bar\" {\n\t\tt.Error(\"Two: Pop() did not pass\")\n\t} else {\n\t\tt.Log(\"Two: Bar Passed\")\n\t}\n\n\t//Size should now be 1\n\tif q.Size() != 0 {\n\t\tt.Error(\"Size != 0\")\n\t} else {\n\t\tt.Log(\"Two: Size == 0 test passed\")\n\t}\n}", "func SNSSQSExistingQueueNonexistingTopic(t *testing.T) {\n\tconsumerGroup1 := watcher.NewUnordered()\n\n\t// Set the partition key on all messages so they are written to the same partition. This allows for checking of ordered messages.\n\tmetadata := map[string]string{\n\t\tmessageKey: partition0,\n\t}\n\n\t// subscriber of the given topic\n\tsubscriberApplication := func(appID string, topicName string, messagesWatcher *watcher.Watcher) app.SetupFn {\n\t\treturn func(ctx flow.Context, s common.Service) error {\n\t\t\t// Simulate periodic errors.\n\t\t\tsim := simulate.PeriodicError(ctx, 100)\n\t\t\t// Setup the /orders event handler.\n\t\t\treturn multierr.Combine(\n\t\t\t\ts.AddTopicEventHandler(&common.Subscription{\n\t\t\t\t\tPubsubName: pubsubName,\n\t\t\t\t\tTopic: topicName,\n\t\t\t\t\tRoute: \"/orders\",\n\t\t\t\t}, func(_ context.Context, e *common.TopicEvent) (retry bool, err error) {\n\t\t\t\t\tif err := sim(); err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\n\t\t\t\t\t// Track/Observe the data of the event.\n\t\t\t\t\tmessagesWatcher.Observe(e.Data)\n\t\t\t\t\tctx.Logf(\"Message Received appID: %s,pubsub: %s, topic: %s, id: %s, data: %s\", appID, e.PubsubName, e.Topic, e.ID, e.Data)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t}\n\n\tpublishMessages := func(metadata map[string]string, sidecarName string, topicName string, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// prepare the messages\n\t\t\tmessages := make([]string, numMessages)\n\t\t\tfor i := range messages {\n\t\t\t\tmessages[i] = fmt.Sprintf(\"partitionKey: %s, message for topic: %s, index: %03d, uniqueId: %s\", metadata[messageKey], topicName, i, uuid.New().String())\n\t\t\t}\n\n\t\t\t// add the messages as expectations to the watchers\n\t\t\tfor _, messageWatcher := range messageWatchers {\n\t\t\t\tmessageWatcher.ExpectStrings(messages...)\n\t\t\t}\n\n\t\t\t// get the sidecar (dapr) client\n\t\t\tclient := sidecar.GetClient(ctx, sidecarName)\n\n\t\t\t// publish messages\n\t\t\tctx.Logf(\"Publishing messages. sidecarName: %s, topicName: %s\", sidecarName, topicName)\n\n\t\t\tvar publishOptions dapr.PublishEventOption\n\n\t\t\tif metadata != nil {\n\t\t\t\tpublishOptions = dapr.PublishEventWithMetadata(metadata)\n\t\t\t}\n\n\t\t\tfor _, message := range messages {\n\t\t\t\tctx.Logf(\"Publishing: %q\", message)\n\t\t\t\tvar err error\n\n\t\t\t\tif publishOptions != nil {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message, publishOptions)\n\t\t\t\t} else {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message)\n\t\t\t\t}\n\t\t\t\trequire.NoError(ctx, err, \"SNSSQSExistingQueueNonexistingTopic - error publishing message\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tassertMessages := func(timeout time.Duration, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// assert for messages\n\t\t\tfor _, m := range messageWatchers {\n\t\t\t\tif !m.Assert(ctx, 25*timeout) {\n\t\t\t\t\tctx.Errorf(\"SNSSQSExistingQueueNonexistingTopic - message assertion failed for watcher: %#v\\n\", m)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tflow.New(t, \"SNSSQS certification - Existing Queue None Existing Topic\").\n\n\t\t// Run subscriberApplication app1\n\t\tStep(app.Run(appID1, fmt.Sprintf(\":%d\", appPort+portOffset*3),\n\t\t\tsubscriberApplication(appID1, topicToBeCreated, consumerGroup1))).\n\n\t\t// Run the Dapr sidecar with ConsumerID \"PUBSUB_AWS_SNSSQS_QUEUE_3\"\n\t\tStep(sidecar.Run(sidecarName1,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/existing_queue\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort+portOffset*3)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort+portOffset*3)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort+portOffset*3)),\n\t\t\t\tembedded.WithProfilePort(strconv.Itoa(runtime.DefaultProfilePort+portOffset*3)),\n\t\t\t)...,\n\t\t)).\n\t\tStep(fmt.Sprintf(\"publish messages to topicToBeCreated: %s\", topicToBeCreated), publishMessages(metadata, sidecarName1, topicToBeCreated, consumerGroup1)).\n\t\tStep(\"wait\", flow.Sleep(30*time.Second)).\n\t\tStep(\"verify if app1 has recevied messages published to newly created topic\", assertMessages(10*time.Second, consumerGroup1)).\n\t\tRun()\n}", "func TestQueueBasics(t *testing.T) {\n\tnTasks := uint(20)\n\tnThreads := uint(2)\n\tnRun := uint64(0)\n\n\tq := Create(nThreads, nTasks)\n\tfor i := uint(0); i < nTasks; i++ {\n\t\tq.Enqueue(newWorker(&nRun))\n\t}\n\n\t// If <nTasks results are returned, this will deadlock.\n\tfor i := uint(0); i < nTasks; i++ {\n\t\tr := <-q.Results\n\t\tif r != correctResult {\n\t\t\tt.Error(\"Got incorrect result from test function:\", r)\n\t\t}\n\t}\n\n\ttime.Sleep(3 * delay) // Give leftover workers time to complete, but there shouldn't be any.\n\n\tif len(q.Results) != 0 {\n\t\tt.Error(\"More results that expected from tasks.\")\n\t}\n\tif uint(nRun) != nTasks {\n\t\tt.Errorf(\"Unexpected number of tasks completed: expected %d; found %d.\", nTasks, nRun)\n\t}\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Queues) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_Queues\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ValidateQueues(db *storm.DB, config Settings.FullClientSettings, tclient *torrent.Client) {\n\ttorrentQueues := Storage.FetchQueues(db)\n\tfor len(torrentQueues.ActiveTorrents) > config.MaxActiveTorrents {\n\t\tremoveTorrent := torrentQueues.ActiveTorrents[:1]\n\t\tfor _, singleTorrent := range tclient.Torrents() {\n\t\t\tif singleTorrent.InfoHash().String() == removeTorrent[0] {\n\t\t\t\tsingleTorrentFromStorage := Storage.FetchTorrentFromStorage(db, removeTorrent[0])\n\t\t\t\tRemoveTorrentFromActive(&singleTorrentFromStorage, singleTorrent, db)\n\t\t\t}\n\t\t}\n\t}\n\ttorrentQueues = Storage.FetchQueues(db)\n\tfor _, singleTorrent := range tclient.Torrents() {\n\t\tsingleTorrentFromStorage := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())\n\t\tif singleTorrentFromStorage.TorrentStatus == \"Stopped\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, queuedTorrent := range torrentQueues.QueuedTorrents { //If we have a queued torrent that is missing data, and an active torrent that is seeding, then prioritize the missing data one\n\t\t\tif singleTorrent.InfoHash().String() == queuedTorrent {\n\t\t\t\tif singleTorrent.BytesMissing() > 0 {\n\t\t\t\t\tfor _, activeTorrent := range torrentQueues.ActiveTorrents {\n\t\t\t\t\t\tfor _, singleActiveTorrent := range tclient.Torrents() {\n\t\t\t\t\t\t\tif activeTorrent == singleActiveTorrent.InfoHash().String() {\n\t\t\t\t\t\t\t\tif singleActiveTorrent.Seeding() == true {\n\t\t\t\t\t\t\t\t\tsingleActiveTFS := Storage.FetchTorrentFromStorage(db, activeTorrent)\n\t\t\t\t\t\t\t\t\tLogger.WithFields(logrus.Fields{\"TorrentName\": singleActiveTFS.TorrentName}).Info(\"Seeding, Removing from active to add queued\")\n\t\t\t\t\t\t\t\t\tRemoveTorrentFromActive(&singleActiveTFS, singleActiveTorrent, db)\n\t\t\t\t\t\t\t\t\tsingleQueuedTFS := Storage.FetchTorrentFromStorage(db, queuedTorrent)\n\t\t\t\t\t\t\t\t\tLogger.WithFields(logrus.Fields{\"TorrentName\": singleQueuedTFS.TorrentName}).Info(\"Adding torrent to the queue, not active\")\n\t\t\t\t\t\t\t\t\tAddTorrentToActive(&singleQueuedTFS, singleTorrent, db)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func TestPostgresReplicationEventQueue_DequeueMultiple(t *testing.T) {\n\tt.Parallel()\n\tdb := testdb.New(t)\n\tctx := testhelper.Context(t)\n\n\tqueue := PostgresReplicationEventQueue{db.DB}\n\n\teventType1 := ReplicationEvent{\n\t\tJob: ReplicationJob{\n\t\t\tChange: UpdateRepo,\n\t\t\tRelativePath: \"/project/path-1\",\n\t\t\tTargetNodeStorage: \"gitaly-1\",\n\t\t\tSourceNodeStorage: \"gitaly-0\",\n\t\t\tVirtualStorage: \"praefect\",\n\t\t\tParams: nil,\n\t\t},\n\t}\n\n\teventType2 := ReplicationEvent{\n\t\tJob: ReplicationJob{\n\t\t\tChange: DeleteRepo,\n\t\t\tRelativePath: \"/project/path-1\",\n\t\t\tTargetNodeStorage: \"gitaly-1\",\n\t\t\tSourceNodeStorage: \"\",\n\t\t\tVirtualStorage: \"praefect\",\n\t\t\tParams: nil,\n\t\t},\n\t}\n\n\teventType3 := ReplicationEvent{\n\t\tJob: ReplicationJob{\n\t\t\tChange: RenameRepo,\n\t\t\tRelativePath: \"/project/path-2\",\n\t\t\tTargetNodeStorage: \"gitaly-1\",\n\t\t\tSourceNodeStorage: \"gitaly-0\",\n\t\t\tVirtualStorage: \"praefect\",\n\t\t\tParams: Params{\"RelativePath\": \"/project/path-2-renamed\"},\n\t\t},\n\t}\n\n\teventType4 := ReplicationEvent{\n\t\tJob: ReplicationJob{\n\t\t\tChange: UpdateRepo,\n\t\t\tRelativePath: \"/project/path-1\",\n\t\t\tTargetNodeStorage: \"gitaly-1\",\n\t\t\tSourceNodeStorage: \"gitaly-0\",\n\t\t\tVirtualStorage: \"backup\",\n\t\t},\n\t}\n\n\t// events to fill in the queue\n\tevents := []ReplicationEvent{eventType1, eventType1, eventType2, eventType1, eventType3, eventType4}\n\tfor i := range events {\n\t\tvar err error\n\t\tevents[i], err = queue.Enqueue(ctx, events[i])\n\t\trequire.NoError(t, err, \"failed to fill in event queue\")\n\t}\n\n\t// first request to deque\n\texpectedEvents1 := []ReplicationEvent{events[0], events[2], events[4]}\n\texpectedJobLocks1 := []JobLockRow{\n\t\t{JobID: events[0].ID, LockID: \"praefect|gitaly-1|/project/path-1\"},\n\t\t{JobID: events[2].ID, LockID: \"praefect|gitaly-1|/project/path-1\"},\n\t\t{JobID: events[4].ID, LockID: \"praefect|gitaly-1|/project/path-2\"},\n\t}\n\n\t// we expect only first two types of events by limiting count to 3\n\tdequeuedEvents1, err := queue.Dequeue(ctx, \"praefect\", \"gitaly-1\", 3)\n\trequire.NoError(t, err)\n\trequire.Len(t, dequeuedEvents1, len(expectedEvents1))\n\tfor i := range dequeuedEvents1 {\n\t\tdequeuedEvents1[i].UpdatedAt = nil // it is not possible to determine update_at value as it is generated on UPDATE in database\n\t\texpectedEvents1[i].State = JobStateInProgress\n\t\texpectedEvents1[i].Attempt--\n\t}\n\trequire.Equal(t, expectedEvents1, dequeuedEvents1)\n\n\trequireLocks(t, ctx, db, []LockRow{\n\t\t// there is only one single lock for all fetched events because of their 'repo' and 'target' combination\n\t\t{ID: \"praefect|gitaly-1|/project/path-1\", Acquired: true},\n\t\t{ID: \"praefect|gitaly-1|/project/path-2\", Acquired: true},\n\t\t{ID: \"backup|gitaly-1|/project/path-1\", Acquired: false},\n\t})\n\trequireJobLocks(t, ctx, db, expectedJobLocks1)\n\n\t// second request to deque\n\t// there must be only last event fetched from the queue\n\texpectedEvents2 := []ReplicationEvent{events[5]}\n\texpectedEvents2[0].State = JobStateInProgress\n\texpectedEvents2[0].Attempt = 2\n\n\texpectedJobLocks2 := []JobLockRow{{JobID: 6, LockID: \"backup|gitaly-1|/project/path-1\"}}\n\n\tdequeuedEvents2, err := queue.Dequeue(ctx, \"backup\", \"gitaly-1\", 100500)\n\trequire.NoError(t, err)\n\trequire.Len(t, dequeuedEvents2, 1, \"only one event must be fetched from the queue\")\n\n\tdequeuedEvents2[0].UpdatedAt = nil // it is not possible to determine update_at value as it is generated on UPDATE in database\n\trequire.Equal(t, expectedEvents2, dequeuedEvents2)\n\n\trequireLocks(t, ctx, db, []LockRow{\n\t\t{ID: \"praefect|gitaly-1|/project/path-1\", Acquired: true},\n\t\t{ID: \"praefect|gitaly-1|/project/path-2\", Acquired: true},\n\t\t{ID: \"backup|gitaly-1|/project/path-1\", Acquired: true},\n\t})\n\trequireJobLocks(t, ctx, db, append(expectedJobLocks1, expectedJobLocks2...))\n}", "func SetupQueueSession() *sqs.SQS {\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(\"us-east-1\"),\n\t\tCredentials: credentials.NewSharedCredentials(\"\", \"test-config\"),\n\t})\n\n\tif err != nil {\n\t\tfmt.Println(\"error\", err)\n\t}\n\n\tsvc := sqs.New(sess)\n\n\treturn svc //, resultURL.QueueUrl\n\n}", "func (i *Inspector) Queues() ([]string, error) {\n\treturn i.rdb.AllQueues()\n}", "func InitQueue(conn *amqp.Connection) {\n\t// create channel\n\tch, err := conn.Channel()\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to create channel %+v\", err)\n\t}\n\n\t// ===========================\n\t// work queue\n\t// ===========================\n\tconfig := rabbitmq.ConfigQueue{\n\t\tName: \"work.queue\",\n\t\tBind: rabbitmq.ConfigQueueBind{\n\t\t\tRoutingKey: \"work.routing.#\",\n\t\t\tExchangeName: \"work.exchange\",\n\t\t},\n\t}\n\t_, err = rabbitmq.QueueDeclare(config, ch)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to create queue %+v\", err)\n\t}\n\n\t// bind q with exchange\n\terr = rabbitmq.QueueBind(config, ch)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to binding queue %+v\", err)\n\t}\n\n\t// ===========================\n\t// delay queue\n\t// ===========================\n\targsDelayQueue := make(amqp.Table)\n\targsDelayQueue[\"x-dead-letter-exchange\"] = \"work.exchange\"\n\targsDelayQueue[\"x-dead-letter-routing-key\"] = \"work.routing.delay\"\n\targsDelayQueue[\"x-message-ttl\"] = 5000\n\tconfig = rabbitmq.ConfigQueue{\n\t\tName: \"delay.queue\",\n\t\tBind: rabbitmq.ConfigQueueBind{\n\t\t\tRoutingKey: \"delay.routing\",\n\t\t\tExchangeName: \"delay.exchange\",\n\t\t},\n\t\tArgs: argsDelayQueue,\n\t}\n\t_, err = rabbitmq.QueueDeclare(config, ch)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to create queue %+v\", err)\n\t}\n\n\t// bind q with exchange\n\terr = rabbitmq.QueueBind(config, ch)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to binding queue %+v\", err)\n\t}\n}", "func (s QueueSetSpy) Queues() map[DeploymentID]*R11nQueue {\n\tres := s.Called()\n\treturn res.Get(0).(map[DeploymentID]*R11nQueue)\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Output_Queues_Queue\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func EnsureNoQueue(ctx context.Context, cli sqsiface.SQSAPI) error {\n\tsrc := commonv1alpha1.ReconcilableFromContext(ctx)\n\ttypedSrc := src.(*v1alpha1.AWSS3Source)\n\n\tif dest := typedSrc.Spec.Destination; dest != nil {\n\t\tif userProvidedQueue := dest.SQS; userProvidedQueue != nil {\n\t\t\t// do not delete queues managed by the user\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tqueueURL, err := sqs.QueueURL(cli, queueName(typedSrc))\n\tswitch {\n\tcase isNotFound(err):\n\t\tevent.Warn(ctx, ReasonUnsubscribed, \"Queue not found, skipping deletion\")\n\t\treturn nil\n\tcase isDenied(err):\n\t\t// it is unlikely that we recover from auth errors in the\n\t\t// finalizer, so we simply record a warning event and return\n\t\tevent.Warn(ctx, ReasonFailedUnsubscribe,\n\t\t\t\"Authorization error getting SQS queue. Ignoring: %s\", toErrMsg(err))\n\t\treturn nil\n\tcase err != nil:\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Failed to determine URL of SQS queue: %s\", toErrMsg(err))\n\t}\n\n\towns, err := assertOwnership(cli, queueURL, typedSrc)\n\tif err != nil {\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Failed to verify owner of SQS queue: %s\", toErrMsg(err))\n\t}\n\n\tif !owns {\n\t\tevent.Warn(ctx, ReasonUnsubscribed, \"Queue %q is not owned by this source instance, \"+\n\t\t\t\"skipping deletion\", queueURL)\n\t\treturn nil\n\t}\n\n\terr = sqs.DeleteQueue(cli, queueURL)\n\tswitch {\n\tcase isDenied(err):\n\t\t// it is unlikely that we recover from auth errors in the\n\t\t// finalizer, so we simply record a warning event and return\n\t\tevent.Warn(ctx, ReasonFailedUnsubscribe,\n\t\t\t\"Authorization error deleting SQS queue. Ignoring: %s\", toErrMsg(err))\n\t\treturn nil\n\tcase err != nil:\n\t\treturn reconciler.NewEvent(corev1.EventTypeWarning, ReasonFailedUnsubscribe,\n\t\t\t\"Error deleting SQS queue: %s\", toErrMsg(err))\n\t}\n\n\tevent.Normal(ctx, ReasonQueueDeleted, \"Deleted SQS queue %q\", queueURL)\n\n\treturn nil\n}", "func (m *MockSQSAPI) ListQueuesWithContext(arg0 context.Context, arg1 *sqs.ListQueuesInput, arg2 ...request.Option) (*sqs.ListQueuesOutput, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ListQueuesWithContext\", varargs...)\n\tret0, _ := ret[0].(*sqs.ListQueuesOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (memif *Memif) initQueues() error {\n\t// Get Rx/Tx queues count.\n\tdetails, err := memif.GetDetails()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(logger.Fields{\n\t\t\"ifName\": memif.IfName,\n\t\t\"Rx-count\": len(details.RxQueues),\n\t\t\"Tx-count\": len(details.TxQueues),\n\t}).Debug(\"Initializing Rx/Tx queues.\")\n\n\t// Initialize interrupt channels.\n\tvar i int\n\tfor i = 0; i < len(details.RxQueues); i++ {\n\t\tqueueIntCh := make(chan struct{}, 1)\n\t\tmemif.queueIntCh = append(memif.queueIntCh, queueIntCh)\n\t}\n\n\t// Initialize Rx/Tx packet buffers.\n\tfor i = 0; i < len(details.RxQueues); i++ {\n\t\tmemif.rxQueueBufs = append(memif.rxQueueBufs, CPacketBuffers{})\n\t\tif !memif.IsMaster {\n\t\t\terrCode := C.memif_refill_queue(memif.cHandle, C.uint16_t(i), C.uint16_t(memif.ringSize-1), 0)\n\t\t\terr = getMemifError(int(errCode))\n\t\t\tif err != nil {\n\t\t\t\tlog.Warn(err.Error())\n\t\t\t}\n\t\t}\n\t}\n\tfor i = 0; i < len(details.TxQueues); i++ {\n\t\tmemif.txQueueBufs = append(memif.txQueueBufs, CPacketBuffers{})\n\t}\n\n\treturn nil\n}", "func RunRegisterWorkQueuesForSingleFixture(file string, t *testing.T) {\n\tvar fixtureSteps []FixtureStep\n\tbyteValue := ReadFile(file, t)\n\n\terr := json.Unmarshal([]byte(byteValue), &fixtureSteps)\n\tt.WithFields(testing.Fields{\n\t\t\"raw_json\": string(byteValue),\n\t}).MustNil(err, \"error decoding fixture steps\")\n\n\tCheckSteps(fixtureSteps, t)\n\n\tfor idx, step := range fixtureSteps {\n\t\tworkQueues = append(workQueues, QueueItem{\n\t\t\tfixtureFileName: file,\n\t\t\tidx: idx,\n\t\t\tstepID: step.ID,\n\t\t\tstatus: NotStarted,\n\t\t})\n\t}\n}", "func SQSQueueName(name string) func(*SQS) {\n\treturn func(s *SQS) {\n\t\ts.name = name\n\t}\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_Queues_Queue\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func SNSSQSFIFOMessages(t *testing.T) {\n\tconsumerGroup1 := watcher.NewOrdered()\n\n\t// prepare the messages\n\tmaxFifoMessages := 20\n\tfifoMessages := make([]string, maxFifoMessages)\n\tfor i := 0; i < maxFifoMessages; i++ {\n\t\tfifoMessages[i] = fmt.Sprintf(\"m%d\", i+1)\n\t}\n\tconsumerGroup1.ExpectStrings(fifoMessages...)\n\n\t// There are multiple publishers so the following\n\t// generator will supply messages to each one in order\n\tmsgCh := make(chan string)\n\tgo func(mc chan string) {\n\t\tfor _, m := range fifoMessages {\n\t\t\tmc <- m\n\t\t}\n\t\tclose(mc)\n\t}(msgCh)\n\n\tdoNothingApp := func(appID string, topicName string, messagesWatcher *watcher.Watcher) app.SetupFn {\n\t\treturn func(ctx flow.Context, s common.Service) error {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsubscriberApplication := func(appID string, topicName string, messagesWatcher *watcher.Watcher) app.SetupFn {\n\t\treturn func(ctx flow.Context, s common.Service) error {\n\t\t\treturn multierr.Combine(\n\t\t\t\ts.AddTopicEventHandler(&common.Subscription{\n\t\t\t\t\tPubsubName: pubsubName,\n\t\t\t\t\tTopic: topicName,\n\t\t\t\t\tRoute: \"/orders\",\n\t\t\t\t}, func(_ context.Context, e *common.TopicEvent) (retry bool, err error) {\n\t\t\t\t\tctx.Logf(\"SNSSQSFIFOMessages.subscriberApplication: Message Received appID: %s,pubsub: %s, topic: %s, id: %s, data: %#v\", appID, e.PubsubName, e.Topic, e.ID, e.Data)\n\t\t\t\t\tmessagesWatcher.Observe(e.Data)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t}\n\n\tpublishMessages := func(metadata map[string]string, sidecarName string, topicName string, mw *watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\n\t\t\t// get the sidecar (dapr) client\n\t\t\tclient := sidecar.GetClient(ctx, sidecarName)\n\n\t\t\t// publish messages\n\t\t\tctx.Logf(\"SNSSQSFIFOMessages Publishing messages. sidecarName: %s, topicName: %s\", sidecarName, topicName)\n\n\t\t\tvar publishOptions dapr.PublishEventOption\n\n\t\t\tif metadata != nil {\n\t\t\t\tpublishOptions = dapr.PublishEventWithMetadata(metadata)\n\t\t\t}\n\n\t\t\tfor message := range msgCh {\n\t\t\t\tctx.Logf(\"SNSSQSFIFOMessages Publishing: sidecarName: %s, topicName: %s - %q\", sidecarName, topicName, message)\n\t\t\t\tvar err error\n\n\t\t\t\tif publishOptions != nil {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message, publishOptions)\n\t\t\t\t} else {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message)\n\t\t\t\t}\n\t\t\t\trequire.NoError(ctx, err, \"SNSSQSFIFOMessages - error publishing message\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\tassertMessages := func(timeout time.Duration, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// assert for messages\n\t\t\tfor _, m := range messageWatchers {\n\t\t\t\tif !m.Assert(ctx, 10*timeout) {\n\t\t\t\t\tctx.Errorf(\"SNSSQSFIFOMessages - message assertion failed for watcher: %#v\\n\", m)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tpub1 := \"publisher1\"\n\tsc1 := pub1 + \"_sidecar\"\n\tpub2 := \"publisher2\"\n\tsc2 := pub2 + \"_sidecar\"\n\tsub := \"subscriber\"\n\tsubsc := sub + \"_sidecar\"\n\n\tflow.New(t, \"SNSSQSFIFOMessages Verify FIFO with multiple publishers and single subscriber receiving messages in order\").\n\n\t\t// Subscriber\n\t\tStep(app.Run(sub, fmt.Sprintf(\":%d\", appPort),\n\t\t\tsubscriberApplication(sub, fifoTopic, consumerGroup1))).\n\t\tStep(sidecar.Run(subsc,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/fifo\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort)),\n\t\t\t)...,\n\t\t)).\n\t\tStep(\"wait\", flow.Sleep(5*time.Second)).\n\n\t\t// Publisher 1\n\t\tStep(app.Run(pub1, fmt.Sprintf(\":%d\", appPort+portOffset+2),\n\t\t\tdoNothingApp(pub1, fifoTopic, consumerGroup1))).\n\t\tStep(sidecar.Run(sc1,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/fifo\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort+portOffset+2)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort+portOffset+2)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort+portOffset+2)),\n\t\t\t\tembedded.WithProfilePort(strconv.Itoa(runtime.DefaultProfilePort+portOffset+2)),\n\t\t\t)...,\n\t\t)).\n\t\tStep(\"publish messages to topic ==> \"+fifoTopic, publishMessages(nil, sc1, fifoTopic, consumerGroup1)).\n\n\t\t// Publisher 2\n\t\tStep(app.Run(pub2, fmt.Sprintf(\":%d\", appPort+portOffset+4),\n\t\t\tdoNothingApp(pub2, fifoTopic, consumerGroup1))).\n\t\tStep(sidecar.Run(sc2,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/fifo\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort+portOffset+4)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort+portOffset+4)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort+portOffset+4)),\n\t\t\t\tembedded.WithProfilePort(strconv.Itoa(runtime.DefaultProfilePort+portOffset+4)),\n\t\t\t)...,\n\t\t)).\n\t\tStep(\"publish messages to topic ==> \"+fifoTopic, publishMessages(nil, sc2, fifoTopic, consumerGroup1)).\n\t\tStep(\"wait\", flow.Sleep(10*time.Second)).\n\t\tStep(\"verify if recevied ordered messages published to active topic\", assertMessages(1*time.Second, consumerGroup1)).\n\t\tStep(\"reset\", flow.Reset(consumerGroup1)).\n\t\tRun()\n\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Output_Queues) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Output_Queues\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *sqsQueuePolicyLister) SqsQueuePolicies(namespace string) SqsQueuePolicyNamespaceLister {\n\treturn sqsQueuePolicyNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func setupValidQueueNames() {\n\tfor _, jType := range models.ValidJobTypes {\n\t\tvar jt = string(jType)\n\t\tvalidQueues[jt] = true\n\t\tvalidQueueList = append(validQueueList, jt)\n\t}\n}", "func (t *OpenconfigQos_Qos_Queues) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Queues\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func EmbedQueue(q *SongQueue, index, beforeIndex, afterIndex int) *dream.Embed {\n\treturn EmbedQueueFilter(q, index, beforeIndex, afterIndex, func(q *SongQueue, s *Song) bool { return true })\n}", "func listQueues(ENV string) []string {\n \t// Using the SDK's default configuration, loading additional config\n\t// and credentials values from the environment variables, shared\n\t// credentials, and shared configuration files\n\n\tsess, err := session.NewSession(&aws.Config{\n\t Region: aws.String(\"us-east-1\")},\n\t)\n\n // Create a SQS service client.\n svc := sqs.New(sess)\n\n\t//have to create a session object first\n\toutput, err := svc.ListQueues(&sqs.ListQueuesInput{\n\t QueueNamePrefix: aws.String(ENV),\n })\n\tif err != nil { panic(err) }\n\n\tqueues := output.QueueUrls\n\tfinal_queues := []string{}\n\n\tfor _, i := range queues {\n\t fmt.Println(string(*i))\n\t final_queues = append(final_queues, *i)\n }\n\treturn final_queues\n}", "func (s *API) ListQueues(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"ListQueues\")\n\n\tqueueNamePrefix := req.FormValue(\"QueueNamePrefix\")\n\tvar queues []string\n\tfor k, v := range s.sqs.queues {\n\t\tif strings.HasPrefix(k, queueNamePrefix) {\n\t\t\tqueues = append(queues, v.url)\n\t\t}\n\t}\n\n\tresponse := ListQueuesResponse{\n\t\tResult: ListQueuesResult{queues},\n\t\tMetaData: ResponseMetaData{\"00000000-0000-0000-0000-000000000000\"},\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/xml\")\n\tenc := xml.NewEncoder(w)\n\tenc.Indent(\" \", \" \")\n\tif err := enc.Encode(response); err != nil {\n\t\tlog.Errorf(\"error: %s\", err)\n\t}\n}", "func populateTestQueue(t *testing.T, messagesToPublish int) {\n\tconn, err := amqp.Dial(TEST_AMQP_URI)\n\tif err != nil {\n\t\tt.Fatalf(\"Dial: %s\", err)\n\t}\n\tdefer conn.Close()\n\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\tt.Fatalf(\"Channel: %s\", err)\n\t}\n\n\t_, err = channel.QueueDeclare(TEST_QUEUE_NAME, true, false, false, false, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"QueueDeclare: %s\", err)\n\t}\n\n\t_, err = channel.QueuePurge(TEST_QUEUE_NAME, false)\n\tif err != nil {\n\t\tt.Fatalf(\"QueuePurge: %s\", err)\n\t}\n\n\tfor i := 0; i < messagesToPublish; i++ {\n\t\terr = channel.Publish(\"\", TEST_QUEUE_NAME, false, false, makeAmqpMessage(i))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Publish: %s\", err)\n\t\t}\n\t}\n}", "func (c *queueInformerConfig) validateQueue() (err error) {\n\tswitch config := c; {\n\tcase config.provider == nil:\n\t\terr = newInvalidConfigError(\"nil metrics provider\")\n\tcase config.logger == nil:\n\t\terr = newInvalidConfigError(\"nil logger\")\n\tcase config.queue == nil:\n\t\terr = newInvalidConfigError(\"nil queue\")\n\tcase config.keyFunc == nil:\n\t\terr = newInvalidConfigError(\"nil key function\")\n\tcase config.syncer == nil:\n\t\terr = newInvalidConfigError(\"nil syncer\")\n\t}\n\n\treturn\n}", "func NewQueue(ctx context.Context, queueID string, db *sql.DB, conf QueueConfig) (*Queue, error) {\n\tq := &Queue{ID: queueID}\n\tq.repo = repo.NewRepository(db)\n\tq.PollRate = 100 * time.Millisecond // Default\n\tq.queueSize = 10000 // Default\n\tq.retries = 3 // Default\n\tq.IsMultiQueue = conf.IsMultiQueue\n\tq.baseDelay = 3 * time.Second // Default\n\n\tif conf.PollingRate > 0 {\n\t\tq.PollRate = conf.PollingRate\n\t}\n\tif conf.Qsize > 0 {\n\t\tq.queueSize = conf.Qsize\n\t}\n\tif conf.BaseDelay > 0 {\n\t\tq.baseDelay = conf.BaseDelay\n\t}\n\tif conf.Retries >= 0 {\n\t\tq.retries = conf.Retries\n\t}\n\t// Multilevel Queue/channel created\n\ttemp := mlQueue{}\n\ttemp.notifier = make([]chan JobChan, 1)\n\ttemp.notifier[0] = make(chan JobChan, q.queueSize)\n\ttemp.total = 1\n\tq.mq = temp\n\n\tm := make(map[string][]worker.Worker)\n\tq.workers = m\n\tvar wg sync.WaitGroup\n\tq.wg = &wg\n\n\t// resume stopped jobs\n\terr := q.ResumePendingJobs(ctx)\n\tif err != nil {\n\t\tlogger.Log.Error(\"Unable to resume jobs from bucket: %s\", zap.Error(err))\n\t\t// Don't fail out, this isn't really fatal. But maybe it should be?\n\t}\n\treturn q, nil\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues_Queue\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewQueue(args []func(http.ResponseWriter, *http.Request) (http.ResponseWriter, *http.Request)) *Queue {\n\tq := &Queue{}\n\tfor _, f := range args {\n\t\tq.list = append(q.list, f)\n\t}\n\treturn q\n}", "func (s *Store) CreateQueue(name string, overriddenSettings ...QueueSetting) (QueueMeta, QueueSettings, error) {\n\tif !isValidQueueName(name) {\n\t\treturn QueueMeta{}, QueueSettings{}, ErrInvalidQueueName\n\t}\n\n\tmeta := QueueMeta{Name: name, Created: time.Now()}\n\tsettings := defaultQueueSettings()\n\n\tfor _, setting := range overriddenSettings {\n\t\tif err := setting(&settings); err != nil {\n\t\t\treturn QueueMeta{}, QueueSettings{}, err\n\t\t}\n\t}\n\n\treturn meta, settings, s.db.Update(func(tx *bolt.Tx) error {\n\t\tqueues := tx.Bucket([]byte(\"Queues\"))\n\n\t\tbucket, err := queues.CreateBucket([]byte(name))\n\t\tif err != nil {\n\t\t\tif err == bolt.ErrBucketExists {\n\t\t\t\treturn ErrQueueExists\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\t// Meta\n\n\t\tmetaBucket, err := bucket.CreateBucketIfNotExists([]byte(\"Meta\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = metaBucket.Put([]byte(\"Name\"), []byte(name)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = metaBucket.Put([]byte(\"Created\"), encodeTime(meta.Created)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Settings\n\n\t\tsettingsBucket, err := bucket.CreateBucketIfNotExists([]byte(\"Settings\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = settingsBucket.Put([]byte(\"LeaseDuration\"), encodeInt(settings.LeaseDuration)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = settingsBucket.Put([]byte(\"MessageRetentionPeriod\"), encodeInt(settings.MessageRetentionPeriod)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = settingsBucket.Put([]byte(\"DelaySeconds\"), encodeInt(settings.DelaySeconds)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Message Buckets\n\n\t\tmessages, err := bucket.CreateBucketIfNotExists([]byte(\"Messages\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := messages.CreateBucketIfNotExists([]byte(\"Visible\")); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := messages.CreateBucketIfNotExists([]byte(\"Leased\")); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := messages.CreateBucketIfNotExists([]byte(\"Delayed\")); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func NewSQS(options ...func(*SQS)) (*SQS, error) {\n\ts, err := initSQS(options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoint, err := s.sqsEndpoint(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error during queue find\")\n\t}\n\tif endpoint == \"\" {\n\t\treturn nil, errors.New(\"queue not found\")\n\t}\n\ts.endpoint = endpoint\n\n\treturn s, nil\n}", "func (clusterInfo ClusterInfo) CreateQueues(queues []rh.QueueInfo) error {\n\trmqc, err := rh.NewClient(clusterInfo.AdminURL(), clusterInfo.UserName, clusterInfo.Password)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, queue := range queues {\n\t\tlog.Printf(\"Creating queue %v\", queue.Name)\n\t\t_, err = rmqc.DeclareQueue(clusterInfo.Vhost, queue.Name, rh.QueueSettings{Durable: queue.Durable, AutoDelete: queue.AutoDelete, Arguments: queue.Arguments})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (s *SQSServer) ListenAndServe(queues ...string) error {\n\tif len(queues) == 0 {\n\t\treturn fmt.Errorf(\"Must specify at least one SQS queue to poll\")\n\t}\n\tpollctx, pollcancel := context.WithCancel(context.Background())\n\ttaskctx, taskcancel := context.WithCancel(context.Background())\n\ts.stopPolling = pollcancel\n\ts.stopTasks = taskcancel\n\tqconfs := make([]QueueConf, len(queues))\n\tfor i := range queues {\n\t\tqconfs[i].Name = queues[i]\n\t\tqconfs[i].Region = s.defaultRegion\n\t\tqconfs[i].ReadBatch = defaultReadBatchSize\n\t\tqconfs[i].Metrics = func(MetricType, float64, int) {}\n\t}\n\n\treturn s.pollQueues(pollctx, taskctx, qconfs)\n}", "func demo_queue() {\n fmt.Print(\"\\n---QUEUE Logic---\\n\\n\")\n q := queue.Queue{}\n\n for i := 0; i <= 5; i++ {\n q.Enqueue(i)\n }\n fmt.Print(\"---Queue Before Dequeue---\\n\")\n q.PrintAll()\n dequeued := q.Dequeue()\n fmt.Printf(\"Dequeued Value: %v\\n\", dequeued)\n fmt.Print(\"---Queue After Dequeue---\\n\")\n q.PrintAll()\n}", "func (gores *Gores) Queues() []string {\n\tqueues := make([]string, 0)\n\n\tconn := gores.pool.Get()\n\tdefer conn.Close()\n\n\tdata, _ := conn.Do(\"SMEMBERS\", watchedQueues)\n\tfor _, q := range data.([]interface{}) {\n\t\tqueues = append(queues, string(q.([]byte)))\n\t}\n\n\treturn queues\n}", "func (b *backend) QueueStats(ctx context.Context, qq *entroq.QueuesQuery) (map[string]*entroq.QueueStat, error) {\n\tresp, err := pb.NewEntroQClient(b.conn).QueueStats(ctx, &pb.QueuesRequest{\n\t\tMatchPrefix: qq.MatchPrefix,\n\t\tMatchExact: qq.MatchExact,\n\t\tLimit: int32(qq.Limit),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get queue stats over gRPC: %w\", err)\n\t}\n\tqs := make(map[string]*entroq.QueueStat)\n\tfor _, q := range resp.Queues {\n\t\tqs[q.Name] = &entroq.QueueStat{\n\t\t\tName: q.Name,\n\t\t\tSize: int(q.NumTasks),\n\t\t\tClaimed: int(q.NumClaimed),\n\t\t\tAvailable: int(q.NumAvailable),\n\t\t\tMaxClaims: int(q.MaxClaims),\n\t\t}\n\t}\n\treturn qs, nil\n}", "func (q *Queen) Run() {\n\n\tlog.L.Debugf(\"Obtaining a run lock for %v\", q.config.ID)\n\n\t//wait for the lock\n\tq.runMutex.Lock()\n\tq.State = running\n\n\tdefer func() {\n\t\tq.runMutex.Unlock()\n\t\tq.LastRun = time.Now()\n\t}()\n\n\tlog.L.Infof(\"Starting run of %v.\", q.config.ID)\n\n\t//before we get the info from the store, we need to have the caterpillar\n\tcat, err := caterpillar.GetCaterpillar(q.config.Type)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get the caterpillar %v.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.State = errorwaiting\n\t\tq.LastError = err.Error()\n\t\treturn\n\t}\n\n\t//Register the info struct so it'll come back with an assertable type in the interface that was written.\n\tcat.RegisterGobStructs()\n\n\t//get the information from the store\n\tinfo, err := store.GetInfo(q.config.ID)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get information for caterpillar %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\tlog.L.Debugf(\"State before run: %v\", info)\n\n\t//get the feeder, from that we can get the number of events.\n\tfeed, err := feeder.GetFeeder(q.config, info.LastEventTime)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get feeder for %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tcount, err := feed.GetCount()\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't get event count from feeder for %v from info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\t//Run the caterpillar - this should block until the cateprillar is done chewing through the data.\n\tstate, err := cat.Run(q.config.ID, count, info, q.nydusChannel, q.config, feed.StartFeeding)\n\tif err != nil {\n\t\tlog.L.Error(err.Addf(\"There was an error running caterpillar %v: %v\", q.config.ID, err.Error()))\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tlog.L.Debugf(\"State after run; %v\", state)\n\n\terr = store.PutInfo(q.config.ID, state)\n\tif err != nil {\n\t\tlog.L.Errorf(err.Addf(\"Couldn't store information for caterpillar %v to info store. Returning.\", q.config.ID).Error())\n\t\tlog.L.Debugf(\"%s\", err.Stack)\n\t\tq.LastError = err.Error()\n\t\tq.State = errorwaiting\n\t\treturn\n\t}\n\n\tq.LastError = \"\"\n\tq.State = donewaiting\n\n}", "func DeclareQueues(ch *amqp.Channel, queueName string) (amqp.Queue, amqp.Queue) {\n\treturn declareQueue(ch, queueName), declareResponseQueue(ch, queueName)\n}", "func (dc *DentistCreate) AddQueueIDs(ids ...int) *DentistCreate {\n\tdc.mutation.AddQueueIDs(ids...)\n\treturn dc\n}", "func (m SQSMonitor) receiveQueueMessages(qURL string) ([]*sqs.Message, error) {\n\tresult, err := m.SQS.ReceiveMessage(&sqs.ReceiveMessageInput{\n\t\tAttributeNames: []*string{\n\t\t\taws.String(sqs.MessageSystemAttributeNameSentTimestamp),\n\t\t},\n\t\tMessageAttributeNames: []*string{\n\t\t\taws.String(sqs.QueueAttributeNameAll),\n\t\t},\n\t\tQueueUrl: &qURL,\n\t\tMaxNumberOfMessages: aws.Int64(10),\n\t\tVisibilityTimeout: aws.Int64(20), // 20 seconds\n\t\tWaitTimeSeconds: aws.Int64(20), // Max long polling\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Messages, nil\n}", "func NewSQS(ctx context.Context, opts map[string]interface{}) (s *SQS, err error) {\n\t// Recover from wrong type assertions\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}()\n\n\ts = &SQS{}\n\n\t// Prepare ops\n\tvar ok bool\n\n\t// Set each option with the correct type\n\tif s.QueueURL, ok = opts[queueURLOpt].(string); !ok {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is required\", queueURLOpt)\n\t}\n\n\tif s.QueueURL == \"\" {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is required\", queueURLOpt)\n\t}\n\n\tif s.QueueProperty, ok = opts[queuePropertyOpt].(string); !ok {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is required\", queuePropertyOpt)\n\t}\n\n\tif s.QueueProperty == \"\" {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is required\", queuePropertyOpt)\n\t}\n\n\t// Check queue property correct\n\tvar valid bool\n\tswitch s.QueueProperty {\n\tcase\n\t\tsqs.QueueAttributeNameApproximateNumberOfMessages,\n\t\tsqs.QueueAttributeNameApproximateNumberOfMessagesNotVisible,\n\t\tsqs.QueueAttributeNameApproximateNumberOfMessagesDelayed:\n\t\tvalid = true\n\t}\n\n\tif !valid {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is wrong\", queuePropertyOpt)\n\t}\n\n\tregion, ok := opts[awsRegionOpt].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is required\", awsRegionOpt)\n\t}\n\n\tif region == \"\" {\n\t\treturn nil, fmt.Errorf(\"%s configuration opt is required\", awsRegionOpt)\n\t}\n\n\t// Create AWS session\n\tss := session.New(&aws.Config{Region: aws.String(region)})\n\tif ss == nil {\n\t\treturn nil, fmt.Errorf(\"error creating aws session\")\n\t}\n\n\t// Create AWS SQS service client\n\tc := sqs.New(ss)\n\ts.session = ss\n\ts.client = c\n\n\t// Logger\n\tasName, ok := ctx.Value(\"autoscaler\").(string)\n\tif !ok {\n\t\tasName = \"unknown\"\n\t}\n\ts.log = log.WithFields(log.Fields{\n\t\t\"autoscaler\": asName,\n\t\t\"kind\": \"gatherer\",\n\t\t\"name\": sqsRegName,\n\t})\n\n\treturn\n}", "func DefaultQueue(queue string) func(*Config) error {\n\treturn func(c *Config) error {\n\t\tc.DefaultQueue = queue\n\t\treturn nil\n\t}\n}", "func (o TopicRuleSqsOutput) QueueUrl() pulumi.StringOutput {\n\treturn o.ApplyT(func(v TopicRuleSqs) string { return v.QueueUrl }).(pulumi.StringOutput)\n}", "func GenerateQueueConfigurations(config *v1beta1.NotificationConfiguration) []types.QueueConfiguration {\n\t// NOTE(muvaf): We skip prealloc because the behavior of AWS SDK differs when\n\t// the array is 0 element vs nil.\n\tvar configurations []types.QueueConfiguration // nolint:prealloc\n\tfor _, v := range config.QueueConfigurations {\n\t\tconf := types.QueueConfiguration{\n\t\t\tId: v.ID,\n\t\t\tQueueArn: v.QueueArn,\n\t\t}\n\t\tif v.Events != nil {\n\t\t\tconf.Events = copyEvents(v.Events)\n\t\t}\n\t\tif v.Filter != nil {\n\t\t\tconf.Filter = generateFilter(v.Filter)\n\t\t}\n\t\tconfigurations = append(configurations, conf)\n\t}\n\treturn configurations\n}", "func newQueueService(c *orgbot.Config) (*queueService, error) {\n\tsess, err := cmd.NewAWSSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &queueService{\n\t\tconfig: c,\n\t\tsqsClient: sqs.New(sess),\n\t}, nil\n\n}", "func (t *OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigQos_Qos_Interfaces_Interface_Input_VirtualOutputQueues_VoqInterface_Queues\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c QueuesAuthorizationRuleClient) preparerForQueuesListAuthorizationRules(ctx context.Context, id QueueId) (*http.Request, error) {\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": defaultApiVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsContentType(\"application/json; charset=utf-8\"),\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(c.baseUri),\n\t\tautorest.WithPath(fmt.Sprintf(\"%s/authorizationRules\", id.ID())),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (c *restClient) ListQueues(ctx context.Context, req *cloudtaskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator {\n\tit := &QueueIterator{}\n\treq = proto.Clone(req).(*cloudtaskspb.ListQueuesRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*cloudtaskspb.Queue, string, error) {\n\t\tresp := &cloudtaskspb.ListQueuesResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v2beta3/%v/queues\", req.GetParent())\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tif req.GetFilter() != \"\" {\n\t\t\tparams.Add(\"filter\", fmt.Sprintf(\"%v\", req.GetFilter()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\t\tif req.GetReadMask() != nil {\n\t\t\treadMask, err := protojson.Marshal(req.GetReadMask())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t\tparams.Add(\"readMask\", string(readMask[1:len(readMask)-1]))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetQueues(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func SNSSQSBasic(t *testing.T) {\n\n\tconsumerGroup1 := watcher.NewUnordered()\n\tconsumerGroup2 := watcher.NewUnordered()\n\n\t// subscriber of the given topic\n\tsubscriberApplication := func(appID string, topicName string, messagesWatcher *watcher.Watcher) app.SetupFn {\n\t\treturn func(ctx flow.Context, s common.Service) error {\n\t\t\t// Simulate periodic errors.\n\t\t\tsim := simulate.PeriodicError(ctx, 100)\n\t\t\t// Setup the /orders event handler.\n\t\t\treturn multierr.Combine(\n\t\t\t\ts.AddTopicEventHandler(&common.Subscription{\n\t\t\t\t\tPubsubName: pubsubName,\n\t\t\t\t\tTopic: topicName,\n\t\t\t\t\tRoute: \"/orders\",\n\t\t\t\t}, func(_ context.Context, e *common.TopicEvent) (retry bool, err error) {\n\t\t\t\t\tif err := sim(); err != nil {\n\t\t\t\t\t\treturn true, err\n\t\t\t\t\t}\n\n\t\t\t\t\t// Track/Observe the data of the event.\n\t\t\t\t\tmessagesWatcher.Observe(e.Data)\n\t\t\t\t\tctx.Logf(\"Message Received appID: %s,pubsub: %s, topic: %s, id: %s, data: %s\", appID, e.PubsubName, e.Topic, e.ID, e.Data)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t}\n\n\tpublishMessages := func(metadata map[string]string, sidecarName string, topicName string, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// prepare the messages\n\t\t\tmessages := make([]string, numMessages)\n\t\t\tfor i := range messages {\n\t\t\t\tmessages[i] = fmt.Sprintf(\"partitionKey: %s, message for topic: %s, index: %03d, uniqueId: %s\", metadata[messageKey], topicName, i, uuid.New().String())\n\t\t\t}\n\n\t\t\t// add the messages as expectations to the watchers\n\t\t\tfor _, messageWatcher := range messageWatchers {\n\t\t\t\tmessageWatcher.ExpectStrings(messages...)\n\t\t\t}\n\n\t\t\t// get the sidecar (dapr) client\n\t\t\tclient := sidecar.GetClient(ctx, sidecarName)\n\n\t\t\t// publish messages\n\t\t\tctx.Logf(\"Publishing messages. sidecarName: %s, topicName: %s\", sidecarName, topicName)\n\n\t\t\tvar publishOptions dapr.PublishEventOption\n\n\t\t\tif metadata != nil {\n\t\t\t\tpublishOptions = dapr.PublishEventWithMetadata(metadata)\n\t\t\t}\n\n\t\t\tfor _, message := range messages {\n\t\t\t\tctx.Logf(\"Publishing: %q\", message)\n\t\t\t\tvar err error\n\n\t\t\t\tif publishOptions != nil {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message, publishOptions)\n\t\t\t\t} else {\n\t\t\t\t\terr = client.PublishEvent(ctx, pubsubName, topicName, message)\n\t\t\t\t}\n\t\t\t\trequire.NoError(ctx, err, \"SNSSQSBasic - error publishing message\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tassertMessages := func(timeout time.Duration, messageWatchers ...*watcher.Watcher) flow.Runnable {\n\t\treturn func(ctx flow.Context) error {\n\t\t\t// assert for messages\n\t\t\tfor _, m := range messageWatchers {\n\t\t\t\tif !m.Assert(ctx, 25*timeout) {\n\t\t\t\t\tctx.Errorf(\"SNSSQSBasic - message assertion failed for watcher: %#v\\n\", m)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tflow.New(t, \"SNSSQS Verify with single publisher / single subscriber\").\n\n\t\t// Run subscriberApplication app1\n\t\tStep(app.Run(appID1, fmt.Sprintf(\":%d\", appPort),\n\t\t\tsubscriberApplication(appID1, topicActiveName, consumerGroup1))).\n\n\t\t// Run the Dapr sidecar with ConsumerID \"PUBSUB_AWS_SNSSQS_QUEUE_1\"\n\t\tStep(sidecar.Run(sidecarName1,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/consumer_one\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort)),\n\t\t\t)...,\n\t\t)).\n\n\t\t// Run subscriberApplication app2\n\t\tStep(app.Run(appID2, fmt.Sprintf(\":%d\", appPort+portOffset),\n\t\t\tsubscriberApplication(appID2, topicActiveName, consumerGroup2))).\n\n\t\t// Run the Dapr sidecar with ConsumerID \"PUBSUB_AWS_SNSSQS_QUEUE_2\"\n\t\tStep(sidecar.Run(sidecarName2,\n\t\t\tappend(componentRuntimeOptions(),\n\t\t\t\tembedded.WithComponentsPath(\"./components/consumer_two\"),\n\t\t\t\tembedded.WithAppProtocol(protocol.HTTPProtocol, strconv.Itoa(appPort+portOffset)),\n\t\t\t\tembedded.WithDaprGRPCPort(strconv.Itoa(runtime.DefaultDaprAPIGRPCPort+portOffset)),\n\t\t\t\tembedded.WithDaprHTTPPort(strconv.Itoa(runtime.DefaultDaprHTTPPort+portOffset)),\n\t\t\t\tembedded.WithProfilePort(strconv.Itoa(runtime.DefaultProfilePort+portOffset)),\n\t\t\t)...,\n\t\t)).\n\t\tStep(\"publish messages to active topic ==> \"+topicActiveName, publishMessages(nil, sidecarName1, topicActiveName, consumerGroup1, consumerGroup2)).\n\t\tStep(\"publish messages to passive topic ==> \"+topicPassiveName, publishMessages(nil, sidecarName1, topicPassiveName)).\n\t\tStep(\"verify if app1 has recevied messages published to active topic\", assertMessages(10*time.Second, consumerGroup1)).\n\t\tStep(\"verify if app2 has recevied messages published to passive topic\", assertMessages(10*time.Second, consumerGroup2)).\n\t\tStep(\"reset\", flow.Reset(consumerGroup1, consumerGroup2)).\n\t\tRun()\n}", "func QueueFactory(queueFactory EventQueueFactory) Option {\n\treturn func(env Environment) {\n\t\te := env.(*environment)\n\t\tif queueFactory == nil {\n\t\t\tqueueFactory = makeLocalEventQueueFactory(10)\n\t\t}\n\t\te.queueFactory = queueFactory\n\t}\n}", "func (s *SQSLocalstack) setup() {\n\tregion := flag.String(\"r\", \"us-east-1\", \"The region of localstack. Default: us-east-1\")\n\tqueue := flag.String(\"q\", \"\", \"The name of the queue\")\n\ttimeout := flag.Int(\"t\", 5, \"How long, in seconds, that the message is hidden from others\")\n\tlocalstackURL := flag.String(\"u\", \"http://localhost:4566\", \"The Localstack url. Default : http://localhost:4566\")\n\tflag.Parse()\n\n\tif *queue == \"\" {\n\t\tfmt.Println(\"You must supply the name of a queue (-q QUEUE)\")\n\t\treturn\n\t}\n\n\tif *timeout < 0 {\n\t\t*timeout = 0\n\t}\n\n\tif *timeout > 12*60*60 {\n\t\t*timeout = 12 * 60 * 60\n\t}\n\ts.region = *region\n\ts.queueName = *queue\n\ts.timeoutSeconds = *timeout\n\ts.localstackURL = *localstackURL\n}", "func GetStats(args *Args, format string) string {\n\tcfg := config.GetConfig(args.ConfigFile)\n\t// init statistic for record\n\tstatistic.InitStatistic(cfg.Statistic)\n\n\tallQueueStatistic := []*statistic.QueueStatistic{}\n\n\tfor _, cc := range cfg.Redis {\n\t\tfor _, queueConfig := range cc.Queues {\n\t\t\ts := &statistic.QueueStatistic{\n\t\t\t\tQueueName: queueConfig.QueueName,\n\t\t\t\tSourceType: \"Redis\",\n\t\t\t\tIsEnabled: queueConfig.IsEnabled,\n\t\t\t}\n\n\t\t\tqi := &redis.QueueInstance{\n\t\t\t\tSource: cc.Config,\n\t\t\t\tQueue: queueConfig,\n\t\t\t}\n\n\t\t\tif queueConfig.IsDelayQueue {\n\t\t\t\ts.Normal, _ = qi.DelayLength(queueConfig.QueueName)\n\t\t\t} else {\n\t\t\t\ts.Normal, _ = qi.Length(queueConfig.QueueName)\n\t\t\t}\n\n\t\t\tif len(queueConfig.DelayOnFailure) > 0 {\n\t\t\t\tqueueName := fmt.Sprintf(\"%s:delayed\", queueConfig.QueueName)\n\t\t\t\ts.Delayed, _ = qi.DelayLength(queueName)\n\t\t\t}\n\n\t\t\ts.Success, _ = statistic.GetCounter(fmt.Sprintf(\"%s:success\", queueConfig.QueueName))\n\t\t\ts.Failure, _ = statistic.GetCounter(fmt.Sprintf(\"%s:failure\", queueConfig.QueueName))\n\n\t\t\ts.Total = s.Normal + s.Delayed + s.Success + s.Failure\n\n\t\t\tallQueueStatistic = append(allQueueStatistic, s)\n\t\t}\n\t}\n\n\tfor _, cc := range cfg.RabbitMQ {\n\t\tfor _, queueConfig := range cc.Queues {\n\t\t\ts := &statistic.QueueStatistic{\n\t\t\t\tQueueName: queueConfig.QueueName,\n\t\t\t\tSourceType: \"RabbitMQ\",\n\t\t\t\tIsEnabled: queueConfig.IsEnabled,\n\t\t\t}\n\n\t\t\t// qi := &rabbitmq.QueueInstance{\n\t\t\t// \tSource: cc.Config,\n\t\t\t// \tQueue: queueConfig,\n\t\t\t// }\n\t\t\t// todo get queue length\n\n\t\t\ts.Normal = 0\n\t\t\ts.Delayed = 0\n\n\t\t\ts.Success, _ = statistic.GetCounter(fmt.Sprintf(\"%s:success\", queueConfig.QueueName))\n\t\t\ts.Failure, _ = statistic.GetCounter(fmt.Sprintf(\"%s:failure\", queueConfig.QueueName))\n\n\t\t\ts.Total = s.Normal + s.Delayed + s.Success + s.Failure\n\n\t\t\tallQueueStatistic = append(allQueueStatistic, s)\n\t\t}\n\t}\n\n\tif \"json\" == format {\n\t\toutput, err := json.Marshal(allQueueStatistic)\n\n\t\tif nil != err {\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn string(output)\n\t}\n\n\toutput := fmt.Sprintf(\"%s %s statistics information\\n\\n\", constant.APPNAME, constant.APPVERSION)\n\tfor _, s := range allQueueStatistic {\n\t\tstatus := \"disable\"\n\t\tif s.IsEnabled {\n\t\t\tstatus = \"enable\"\n\t\t}\n\t\toutput += fmt.Sprintf(\" > Type: %-8s Status: %-8s Name: %s\\n%10d Total\\n%10d Normal\\n%10d Delayed\\n%10d Success\\n%10d Failure\\n\\n\", s.SourceType, status, s.QueueName, s.Total, s.Normal, s.Delayed, s.Success, s.Failure)\n\t}\n\n\tif \"html\" == format {\n\t\tstrings.Replace(output, \"\\n\", \"<br />\", -1)\n\t}\n\n\treturn output\n}", "func TestQueueARN(t *testing.T) {\n\trootPath, err := newTestConfig(globalMinioDefaultRegion)\n\tif err != nil {\n\t\tt.Fatalf(\"unable initialize config file, %s\", err)\n\t}\n\tdefer os.RemoveAll(rootPath)\n\n\ttestCases := []struct {\n\t\tqueueARN string\n\t\terrCode APIErrorCode\n\t}{\n\n\t\t// Valid webhook queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:webhook\",\n\t\t\terrCode: ErrNone,\n\t\t},\n\t\t// Valid redis queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:redis\",\n\t\t\terrCode: ErrNone,\n\t\t},\n\t\t// Valid elasticsearch queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:elasticsearch\",\n\t\t\terrCode: ErrNone,\n\t\t},\n\t\t// Valid amqp queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:amqp\",\n\t\t\terrCode: ErrNone,\n\t\t},\n\t\t// Invalid empty queue arn.\n\t\t{\n\t\t\tqueueARN: \"\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t\t// Invalid notification service type.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sns:us-east-1:1:listen\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t\t// Invalid queue name empty in queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t\t// Invalid queue id empty in queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1::redis\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t\t// Invalid queue id and queue name empty in queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1::\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t\t// Missing queue id and separator missing at the end in queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:amqp\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t\t// Missing queue id and empty string at the end in queue arn.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:\",\n\t\t\terrCode: ErrARNNotification,\n\t\t},\n\t}\n\n\t// Validate all tests for queue arn.\n\tfor i, testCase := range testCases {\n\t\terrCode := checkQueueARN(testCase.queueARN)\n\t\tif testCase.errCode != errCode {\n\t\t\tt.Errorf(\"Test %d: Expected \\\"%d\\\", got \\\"%d\\\"\", i+1, testCase.errCode, errCode)\n\t\t}\n\t}\n\n\t// Test when server region is set.\n\trootPath, err = newTestConfig(\"us-east-1\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable initialize config file, %s\", err)\n\t}\n\tdefer os.RemoveAll(rootPath)\n\n\ttestCases = []struct {\n\t\tqueueARN string\n\t\terrCode APIErrorCode\n\t}{\n\t\t// Incorrect region should produce error.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-west-1:1:webhook\",\n\t\t\terrCode: ErrRegionNotification,\n\t\t},\n\t\t// Correct region should not produce error.\n\t\t{\n\t\t\tqueueARN: \"arn:minio:sqs:us-east-1:1:webhook\",\n\t\t\terrCode: ErrNone,\n\t\t},\n\t}\n\n\t// Validate all tests for queue arn.\n\tfor i, testCase := range testCases {\n\t\terrCode := checkQueueARN(testCase.queueARN)\n\t\tif testCase.errCode != errCode {\n\t\t\tt.Errorf(\"Test %d: Expected \\\"%d\\\", got \\\"%d\\\"\", i+1, testCase.errCode, errCode)\n\t\t}\n\t}\n}", "func TestCommandQueueEnclosedWrite(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tcq := NewCommandQueue(true)\n\n\tspans1 := []roachpb.Span{\n\t\tmkSpan(\"a\", \"\"),\n\t}\n\tspans2 := []roachpb.Span{\n\t\tmkSpan(\"a\", \"b\"),\n\t}\n\tspansCandidate := []roachpb.Span{\n\t\tmkSpan(\"a\", \"\"),\n\t}\n\n\t// Add command 1.\n\tcmd1 := cq.add(false, makeTS(3, 0), nil, spans1)\n\n\t// Add command 2.\n\tpre := cq.getPrereqs(true, makeTS(2, 0), spans2)\n\tif expPre := []*cmd(nil); !reflect.DeepEqual(expPre, pre) {\n\t\tt.Errorf(\"expected prereq commands %+v; got %+v\", expPre, pre)\n\t}\n\tcmd2 := cq.add(true, makeTS(2, 0), nil, spans2)\n\n\t// Add command 3.\n\tpre = cq.getPrereqs(false, makeTS(1, 0), spansCandidate)\n\tif expPre := []*cmd{cmd2, cmd1}; !reflect.DeepEqual(expPre, pre) {\n\t\tt.Errorf(\"expected prereq commands %+v; got %+v\", expPre, pre)\n\t}\n}", "func QueueBind(config ConfigQueue, ch *amqp.Channel) error {\n\tlog.Println(\"config: %+v\", config.Bind)\n\n\tif err := ch.QueueBind(\n\t\tconfig.Name,\n\t\tconfig.Bind.RoutingKey,\n\t\tconfig.Bind.ExchangeName,\n\t\tconfig.NoWait,\n\t\tnil,\n\t); err != nil {\n\t\treturn errors.New(\"[QueueBind]: unable to queue bind\" + err.Error())\n\t}\n\n\treturn nil\n}", "func (dc *DentistCreate) AddQueue(q ...*Queue) *DentistCreate {\n\tids := make([]int, len(q))\n\tfor i := range q {\n\t\tids[i] = q[i].ID\n\t}\n\treturn dc.AddQueueIDs(ids...)\n}", "func Bench(cfg Cfg) Results {\n\t// Synchronization variables for benchEnqueuer and benchDequeuer.\n\tbegin := make(chan struct{})\n\tvar wg sync.WaitGroup\n\n\t// Begin all enqueuers.\n\tenqDiv, enqRem := cfg.Messages/cfg.Enqueuers, cfg.Messages%cfg.Enqueuers\n\tenqTimings := make([]*[]int64, 0, cfg.Enqueuers)\n\tfor i := 0; i < cfg.Enqueuers; i++ {\n\t\tenqueues := enqDiv\n\t\tif enqRem > 0 {\n\t\t\tenqueues++\n\t\t\tenqRem--\n\t\t}\n\t\tbencher := &benchEnqueuer{\n\t\t\tenqImpl: cfg.Impl,\n\t\t\tenqueues: enqueues,\n\t\t\tenqTimings: make([]int64, 0, cfg.Messages),\n\t\t}\n\t\tenqTimings = append(enqTimings, &bencher.enqTimings)\n\t\twg.Add(1)\n\t\tgo bencher.run(begin, &wg)\n\t}\n\n\t// Begin all dequeuers.\n\tdeqDiv, deqRem := cfg.Messages/cfg.Dequeuers, cfg.Messages%cfg.Dequeuers\n\ttimings := make([]*[]int64, 0, cfg.Dequeuers)\n\tdeqTimings := make([]*[]int64, 0, cfg.Dequeuers)\n\tfor i := 0; i < cfg.Dequeuers; i++ {\n\t\tdequeues := deqDiv\n\t\tif deqRem > 0 {\n\t\t\tdequeues++\n\t\t\tdeqRem--\n\t\t}\n\t\tbencher := &benchDequeuer{\n\t\t\tdeqImpl: cfg.Impl,\n\t\t\tdequeues: dequeues,\n\t\t\ttimings: make([]int64, 0, cfg.Messages),\n\t\t\tdeqTimings: make([]int64, 0, cfg.Messages),\n\t\t}\n\t\ttimings = append(timings, &bencher.timings)\n\t\tdeqTimings = append(deqTimings, &bencher.deqTimings)\n\t\twg.Add(1)\n\t\tgo bencher.run(begin, &wg)\n\t}\n\n\tstart := etime.Now()\n\t// Start all enqueuers and dequeuers.\n\tclose(begin)\n\t// Wait for all to finish.\n\twg.Wait()\n\tend := etime.Now()\n\ttotal := end - start - nowOverhead\n\n\tb := Results{\n\t\tGOMAXPROCS: runtime.GOMAXPROCS(0),\n\t\tEnqueuers: cfg.Enqueuers,\n\t\tDequeuers: cfg.Dequeuers,\n\t\tEnqueueTimings: make([][]int64, 0, len(enqTimings)),\n\t\tDequeueTimings: make([][]int64, 0, len(deqTimings)),\n\t\tThroughputTimings: make([][]int64, 0, len(timings)),\n\t\tTotalTiming: total,\n\t}\n\n\tfor _, timingPtr := range enqTimings {\n\t\ttiming := *timingPtr\n\t\tb.EnqueueTimings = append(b.EnqueueTimings, timing)\n\t}\n\tfor _, timingPtr := range deqTimings {\n\t\ttiming := *timingPtr\n\t\tb.DequeueTimings = append(b.DequeueTimings, timing)\n\t}\n\tfor _, timingPtr := range timings {\n\t\ttiming := *timingPtr\n\t\tb.ThroughputTimings = append(b.ThroughputTimings, timing)\n\t}\n\treturn b\n}", "func SetupRMQ(cfg *configs.Configuration) *Conn {\n\trmqURL := configs.RMQURL(configs.BuildRMQConfig(cfg))\n\n\tconn, err := amqp.Dial(rmqURL)\n\thandleError(err, \"Can't connect to AMQP\")\n\n\tamqpChannel, err := conn.Channel()\n\thandleError(err, \"Can't create a amqpChannel\")\n\n\t// income queue with web pages\n\tbuildChannel(amqpChannel, cfg.RMQ.ExchangeIn, cfg.RMQ.ExchangeTypeIn, cfg.RMQ.QueueIn, cfg.RMQ.RoutingKeyIn, cfg.RMQ.Concurrency)\n\t// outcome queue to send parse result\n\t//(amqpChannel, cfg.RMQ.ExchangeOut, cfg.RMQ.ExchangeTypeOut, cfg.RMQ.QueueOut, cfg.RMQ.RoutingKeyOut, cfg.RMQ.Concurrency)\n\n\treturn &Conn{\n\t\tChannel: amqpChannel,\n\t\tProcessors: make(map[string][]chan string),\n\t\tCfg: cfg,\n\t}\n}", "func ListenToRunsQueue(callback func(amqp.Delivery)) {\n\tfor run := range runsDelivery {\n\t\tgo callback(run)\n\t}\n}", "func Tests(t *testing.T, ctor func() Queue) {\n\tq := ctor()\n\tcaps := Detect(q)\n\tif !caps.Any(CapQueue) {\n\t\tt.Fatal(\"does not implement any of queue interfaces\")\n\t}\n\tt.Helper()\n\n\t// TODO: add system noise when shaking\n\n\tif caps.Has(CapBlockSPSC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"b/SPSC\", func(t *testing.T) { t.Helper(); testSPSC(t, caps, ctor) })\n\t\t}\n\t}\n\tif caps.Has(CapBlockMPSC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"b/MPSC\", func(t *testing.T) { t.Helper(); testMPSC(t, caps, ctor) })\n\t\t}\n\t}\n\tif caps.Has(CapBlockSPMC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"b/SPMC\", func(t *testing.T) { t.Helper(); testSPMC(t, caps, ctor) })\n\t\t}\n\t}\n\tif caps.Has(CapBlockMPMC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"b/MPMC\", func(t *testing.T) { t.Helper(); testMPMC(t, caps, ctor) })\n\t\t}\n\t}\n\n\tif caps.Has(CapNonblockSPSC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"n/SPSC\", func(t *testing.T) { t.Helper(); testNonblockSPSC(t, caps, ctor) })\n\t\t}\n\t}\n\tif caps.Has(CapNonblockMPSC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"n/MPSC\", func(t *testing.T) { t.Helper(); testNonblockMPSC(t, caps, ctor) })\n\t\t}\n\t}\n\tif caps.Has(CapNonblockSPMC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"n/SPMC\", func(t *testing.T) { t.Helper(); testNonblockSPMC(t, caps, ctor) })\n\t\t}\n\t}\n\tif caps.Has(CapNonblockMPMC) {\n\t\tfor i := 0; i < *shake; i++ {\n\t\t\tt.Run(\"n/MPMC\", func(t *testing.T) { t.Helper(); testNonblockMPMC(t, caps, ctor) })\n\t\t}\n\t}\n}" ]
[ "0.61222285", "0.60373265", "0.5991201", "0.598443", "0.5974285", "0.5967612", "0.578413", "0.57465136", "0.56890184", "0.56563723", "0.5654841", "0.56327754", "0.5617098", "0.5601202", "0.55928594", "0.5576123", "0.5474809", "0.5413749", "0.5391861", "0.5387072", "0.5382978", "0.5365794", "0.5335292", "0.5253436", "0.5228771", "0.5190459", "0.5174059", "0.5166773", "0.51503587", "0.5135856", "0.5125359", "0.5124773", "0.5119884", "0.5112332", "0.51056045", "0.510051", "0.5092595", "0.50899225", "0.5085051", "0.5070838", "0.5064589", "0.5059571", "0.5050732", "0.5041927", "0.50374264", "0.5035182", "0.5034629", "0.50287205", "0.50217855", "0.5020368", "0.5018781", "0.501325", "0.5012915", "0.5006617", "0.4993222", "0.4988574", "0.49857542", "0.4984242", "0.4983698", "0.49726516", "0.49707034", "0.49634385", "0.49597892", "0.4947964", "0.4946033", "0.49440765", "0.49223405", "0.49027327", "0.48978934", "0.48959443", "0.48934874", "0.48840755", "0.4882584", "0.4877064", "0.48749772", "0.48748994", "0.48699796", "0.48694235", "0.4869047", "0.48603055", "0.4858683", "0.48526382", "0.48371273", "0.4834444", "0.48341662", "0.48335332", "0.48217282", "0.48094055", "0.4803416", "0.47912544", "0.47778046", "0.4772596", "0.47693786", "0.47597727", "0.47597274", "0.475529", "0.4735877", "0.47357544", "0.472948", "0.4728967" ]
0.65749663
0
newJobRunner returns a new job runner with the provided agent configuration.
func newJobRunner(cfg config.Config, back backend.Backend, updater jobrunner.CheckStateUpdater, logger log.Logger) (*jobrunner.Runner, error) { // Build the aborted checks component that will be used to know if a check // has been aborted or not before starting to execute it. var ( err error abortedChecks jobrunner.AbortedChecks ) if cfg.Stream.QueryEndpoint == "" { logger.Infof("stream query_endpoint is empty, the agent will not check for aborted checks") abortedChecks = &aborted.None{} } else { re := retryer.NewRetryer(cfg.Stream.Retries, cfg.Stream.RetryInterval, logger) abortedChecks, err = aborted.New(logger, cfg.Stream.QueryEndpoint, re) if err != nil { return nil, fmt.Errorf("create aborted checks: %w", err) } } // Build job runner. runnerCfg := jobrunner.RunnerConfig{ MaxTokens: cfg.Agent.ConcurrentJobs, DefaultTimeout: cfg.Agent.Timeout, MaxProcessMessageTimes: cfg.Agent.MaxProcessMessageTimes, } jrunner := jobrunner.New(logger, back, updater, abortedChecks, runnerCfg) return jrunner, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewRunner() *Runner {\n\treturn &Runner{\n\t\tl: logrus.WithField(\"component\", \"jobs-runner\"),\n\t\tjobs: make(chan Job, jobsBufferSize),\n\t\tjobsCancel: make(map[string]context.CancelFunc),\n\t\tmessages: make(chan *channel.AgentResponse),\n\t}\n}", "func newJobRunner(logger *persist.Logger, ant *Ant, siadirectory string, existingWalletSeed string) (*JobRunner, error) {\n\tjr := &JobRunner{\n\t\tstaticLogger: logger,\n\t\tstaticAntsSyncWG: ant.staticAntsSyncWG,\n\t\tstaticAnt: ant,\n\t\tstaticClient: ant.StaticClient,\n\t\tstaticDataDir: ant.Config.DataDir,\n\t}\n\n\t// Get the wallet\n\twg, err := jr.staticClient.WalletGet()\n\tif err != nil {\n\t\treturn nil, errors.AddContext(err, \"can't get wallet info\")\n\t}\n\tif wg.Unlocked && existingWalletSeed == \"\" {\n\t\t// Set the wallet seed in the jobrunner and return. This case happens\n\t\t// when newJobRunner() is called multiple times (by purpose or by\n\t\t// mistake) on the ant.\n\t\twsg, err := jr.staticClient.WalletSeedsGet()\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, \"can't get wallet seeds\")\n\t\t}\n\t\tjr.StaticWalletSeed = wsg.PrimarySeed\n\t\treturn jr, nil\n\t}\n\n\t// Init the wallet when needed and save seed\n\tvar checkSeed bool\n\tif existingWalletSeed == \"\" && !wg.Encrypted {\n\t\t// No wallet seed was specified and wallet is encrypted. Initialize a\n\t\t// new wallet.\n\t\tjr.staticLogger.Debugf(\"%v: init wallet\", jr.staticDataDir)\n\t\twalletParams, err := jr.staticClient.WalletInitPost(\"\", false)\n\t\tif err != nil {\n\t\t\ter := errors.AddContext(err, \"can't init wallet\")\n\t\t\tjr.staticLogger.Errorf(\"%v: %v\", jr.staticDataDir, er)\n\t\t\treturn nil, er\n\t\t}\n\t\tjr.StaticWalletSeed = walletParams.PrimarySeed\n\t} else if existingWalletSeed == \"\" && wg.Encrypted {\n\t\t// Nothing to do. Not sure if or when this case can happen.\n\t} else if existingWalletSeed != \"\" && !wg.Encrypted {\n\t\t// A wallet seed was specified, but wallet is not encrypted. Initialize\n\t\t// the wallet with the existing seed.\n\t\tjr.staticLogger.Debugf(\"%v: init wallet using existing seed\", jr.staticDataDir)\n\t\terr := jr.staticClient.WalletInitSeedPost(existingWalletSeed, \"\", false)\n\t\tif err != nil {\n\t\t\ter := errors.AddContext(err, \"can't init wallet using existing seed\")\n\t\t\tjr.staticLogger.Errorf(\"%v: %v\", jr.staticDataDir, er)\n\t\t\treturn nil, er\n\t\t}\n\t\tjr.StaticWalletSeed = existingWalletSeed\n\t} else if existingWalletSeed != \"\" && wg.Encrypted {\n\t\t// A wallet seed was specified, wallet is encrypted. Just save seed.\n\t\t// Executed e.g. during siad upgrade with job runner re-creation.\n\t\tcheckSeed = true\n\t\tjr.staticLogger.Debugf(\"%v: use existing initialized wallet\", jr.staticDataDir)\n\t\tjr.StaticWalletSeed = existingWalletSeed\n\t}\n\n\t// Unlock the wallet\n\terr = jr.staticClient.WalletUnlockPost(jr.StaticWalletSeed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Check that actual seed equals existingWalletSeed.\n\tif checkSeed {\n\t\twsg, err := jr.staticClient.WalletSeedsGet()\n\t\tif err != nil {\n\t\t\treturn nil, errors.AddContext(err, \"can't get wallet seeds\")\n\t\t}\n\t\tif wsg.PrimarySeed != existingWalletSeed {\n\t\t\treturn nil, errors.New(\"wallet primary seed doesn't equal expected existing seed\")\n\t\t}\n\t}\n\n\treturn jr, nil\n}", "func NewRunner(ctx *pulumi.Context,\n\tname string, args *RunnerArgs, opts ...pulumi.ResourceOption) (*Runner, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.RegistrationToken == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'RegistrationToken'\")\n\t}\n\tif args.RegistrationToken != nil {\n\t\targs.RegistrationToken = pulumi.ToSecret(args.RegistrationToken).(pulumi.StringInput)\n\t}\n\tsecrets := pulumi.AdditionalSecretOutputs([]string{\n\t\t\"authenticationToken\",\n\t\t\"registrationToken\",\n\t})\n\topts = append(opts, secrets)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Runner\n\terr := ctx.RegisterResource(\"gitlab:index/runner:Runner\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (j *JobRunner) NewRenterJob() RenterJob {\n\treturn RenterJob{\n\t\tstaticLogger: j.staticLogger,\n\t\tstaticJR: j,\n\t}\n}", "func CreateJobRunner(kube Clients) JobRunner {\n\treturn &jobRunner{\n\t\tkube: kube,\n\t}\n}", "func NewRunner(view ui.ViewInterface, proxy proxy.ProxyInterface, project *config.Project) *Runner {\n\treturn &Runner{\n\t\tproxy: proxy,\n\t\tprojectName: project.Name,\n\t\tapplications: project.Applications,\n\t\tcmds: make(map[string]*exec.Cmd, 0),\n\t\tview: view,\n\t}\n}", "func NewRunner(config *Config, client Client, server Server) *Runner {\n\treturn &Runner{\n\t\tconfig: config,\n\t\tclient: client,\n\t\tserver: server,\n\t}\n}", "func NewRunner(\n\tcheckInterval time.Duration,\n\temissionInterval time.Duration,\n\ttimeoutInterval time.Duration,\n\tlogger lager.Logger,\n\tchecker Checker,\n\texecutorClient executor.Client,\n\tmetronClient loggingclient.IngressClient,\n\tclock clock.Clock,\n) *Runner {\n\treturn &Runner{\n\t\tcheckInterval: checkInterval,\n\t\temissionInterval: emissionInterval,\n\t\ttimeoutInterval: timeoutInterval,\n\t\tlogger: logger.Session(\"garden-healthcheck\"),\n\t\tchecker: checker,\n\t\texecutorClient: executorClient,\n\t\tmetronClient: metronClient,\n\t\tclock: clock,\n\t\thealthy: false,\n\t\tfailures: 0,\n\t}\n}", "func NewRunner(executor Executor, rep reporter.Reporter) *Runner {\n\treturn &Runner{\n\t\texecutor: executor,\n\t\treporter: rep,\n\t}\n}", "func recreateJobRunner(j *JobRunner) (*JobRunner, error) {\n\t// Create new job runner\n\tnewJR, err := newJobRunner(j.staticLogger, j.staticAnt, j.staticDataDir, j.StaticWalletSeed)\n\tif err != nil {\n\t\treturn &JobRunner{}, errors.AddContext(err, \"couldn't create an updated job runner\")\n\t}\n\n\treturn newJR, nil\n}", "func (pfs *Supervisor) NewRunner(t *testing.T, m Matrix) *Runner {\n\tif Flags.PrintMatrix {\n\t\tmatrix := m.scenarios()\n\t\tfor _, m := range matrix {\n\t\t\tfmt.Printf(\"%s/%s\\n\", t.Name(), m)\n\t\t}\n\t\tt.Skip(\"Just printing test matrix (-ls-matrix flag set)\")\n\t}\n\tt.Helper()\n\tt.Parallel()\n\tpf := &Runner{\n\t\tt: t,\n\t\tmatrix: m,\n\t\ttestNames: map[string]struct{}{},\n\t\ttestNamesPassed: map[string]struct{}{},\n\t\ttestNamesSkipped: map[string]struct{}{},\n\t\ttestNamesFailed: map[string]struct{}{},\n\t\tparent: pfs,\n\t}\n\tpfs.mu.Lock()\n\tdefer pfs.mu.Unlock()\n\tpfs.fixtures[t.Name()] = pf\n\treturn pf\n}", "func NewRunner(client ucare.Client, customStorage string) *Runner {\n\treturn &Runner{\n\t\tFile: file.NewService(client),\n\t\tGroup: group.NewService(client),\n\t\tUpload: upload.NewService(client),\n\t\tConversion: conversion.NewService(client),\n\t\tWebhook: webhook.NewService(client),\n\t\tProject: project.NewService(client),\n\t\tArtifacts: Artifacts{\n\t\t\tCustomStorage: customStorage,\n\t\t},\n\t}\n}", "func NewRunner(env []string) *Runner {\n\treturn &Runner{\n\t\tenv: env,\n\t}\n}", "func NewRunner(manager *PM, command *core.Command, factory process.ProcessFactory, hooks ...RunnerHook) Runner {\n\tstatsInterval := command.StatsInterval\n\n\tif statsInterval < 30 {\n\t\tstatsInterval = 30\n\t}\n\n\trunner := &runnerImpl{\n\t\tmanager: manager,\n\t\tcommand: command,\n\t\tfactory: factory,\n\t\tkill: make(chan int),\n\t\thooks: hooks,\n\n\t\tstatsd: stats.NewStatsd(\n\t\t\tcommand.ID,\n\t\t\ttime.Duration(statsInterval)*time.Second,\n\t\t\tmanager.statsFlushCallback),\n\t}\n\n\trunner.wg.Add(1)\n\treturn runner\n}", "func newRestoreRunner(restore *backupv1alpha1.Restore, common service.CommonObjects, observer *observe.Observer) *restoreRunner {\n\treturn &restoreRunner{\n\t\trestore: restore,\n\t\tCommonObjects: common,\n\t\tconfig: newConfig(),\n\t\tobserver: observer,\n\t}\n}", "func NewRunner(config *config.Config, once bool) (*Runner, error) {\n\t// var repos repository.Repo\n\tlogger := log.WithField(\"caller\", \"runner\")\n\n\t// Create repos from configuration\n\trepos, err := repository.LoadRepos(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Cannot load repositories from configuration: %s\", err)\n\t}\n\tvar reposI = make([]repository.Repo, len(repos))\n\tfor index, repo := range repos {\n\t\treposI[index] = repo\n\t}\n\t// Create watcher to watch for repo changes\n\twatcher := watch.New(reposI, config.HookSvr, once)\n\n\t// Create the handler\n\thandler, err := kv.New(config.Consul)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trunner := &Runner{\n\t\tlogger: logger,\n\t\tErrCh: make(chan error),\n\t\tRcvDoneCh: make(chan struct{}, 1),\n\t\tSndDoneCh: make(chan struct{}, 1),\n\t\tonce: once,\n\t\tkvHandler: handler,\n\t\twatcher: watcher,\n\t}\n\n\treturn runner, nil\n}", "func newAgent(conf config.Agent) (*agent, error) {\n\t// Check that the agent's processor type is supported\n\tif _, ok := availableProcessorsFactory[conf.Type]; !ok {\n\t\treturn nil, fmt.Errorf(\"Processor %s not found\", conf.Type)\n\t}\n\n\t// Create a new Processor processor\n\tproc := availableProcessorsFactory[conf.Type]()\n\tif proc == nil {\n\t\treturn nil, fmt.Errorf(\"Can not start processor %s\", conf.Type)\n\t}\n\n\ta := &agent{\n\t\tpacketChan: make(chan *event, conf.Buffer),\n\t\toutputs: map[int][]chan *event{},\n\t\tprocessor: proc,\n\t\tDone: make(chan bool),\n\t\tconf: conf,\n\t}\n\n\t// Configure the agent (and its processor)\n\tif err := a.configure(&conf); err != nil {\n\t\treturn nil, fmt.Errorf(\"Can not configure agent %s : %s\", conf.Type, err)\n\t}\n\n\treturn a, nil\n}", "func NewRunner(dir string, logger *Logger, options Options) Runner {\n\tif !options.FirecrackerOptions.Enabled {\n\t\treturn &dockerRunner{dir: dir, logger: logger, options: options}\n\t}\n\n\treturn &firecrackerRunner{name: options.ExecutorName, dir: dir, logger: logger, options: options}\n}", "func NewAgent(ctx context.Context, cancel context.CancelFunc, id string, storage check.Storage, l *logrus.Entry, cfg config.Config) (agent.Agent, error) {\n\taddr, err := getAgentAddr(cfg.API.Port, cfg.API.IName)\n\tif err != nil {\n\t\treturn &Agent{}, err\n\t}\n\n\terr = setKubectlConfig(cfg.Runtime.Kubernetes)\n\tif err != nil {\n\t\treturn &Agent{}, err\n\t}\n\n\treturn &Agent{\n\t\tid: id,\n\t\taddr: addr,\n\t\tstatus: agent.StatusNew,\n\t\tctx: ctx,\n\t\tlog: l,\n\t\tcancel: cancel,\n\t\tstorage: storage,\n\t\tconfig: cfg,\n\t\tmutex: sync.RWMutex{},\n\t}, nil\n}", "func NewRunner() Runner {\n\treturn execRunner{}\n}", "func New(config *Config, logger log.Logger) (*Agent, error) {\n\n\tconfig = DefaultConfig().Merge(config)\n\n\tif logger == nil {\n\t\treturn nil, errors.New(\"missing logger\")\n\t}\n\n\ta := &Agent{\n\t\tconfig: config,\n\t\tlogger: logger.WithName(\"agent\"),\n\t\tshutdownCh: make(chan struct{}),\n\t}\n\n\t// Setup Seashell client\n\tif err := a.setupClient(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a, nil\n}", "func NewRunner(getter Getter) *Runner {\n\treturn &Runner{getter: getter}\n}", "func NewJob(jobtype string, args ...interface{}) *Job {\n\treturn &Job{\n\t\tType: jobtype,\n\t\tQueue: \"default\",\n\t\tArgs: args,\n\t\tJid: RandomJid(),\n\t\tCreatedAt: time.Now().UTC().Format(time.RFC3339Nano),\n\t\tRetry: 25,\n\t}\n}", "func New(t *testing.T, name string, arg ...string) *Runner {\n\treturn &Runner{t, name, arg}\n}", "func NewJob(ctx *pulumi.Context,\n\tname string, args *JobArgs, opts ...pulumi.ResourceOption) (*Job, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.RoleArn == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'RoleArn'\")\n\t}\n\tif args.Type == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Type'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Job\n\terr := ctx.RegisterResource(\"aws-native:databrew:Job\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewJob() *Job {\n\treturn &Job{}\n}", "func (d *Dispatcher) NewJob() *JobBuilder {\n\treturn &JobBuilder{Submitter: d}\n}", "func NewRunner(c client.Client) *ClientPipelineRunner {\n\treturn &ClientPipelineRunner{client: c, objectMeta: objectMetaCreator}\n}", "func NewJob() *Job {\n\treturn &Job{\n\t\tVars: make(map[string]string),\n\t\tModules: make(map[string]string),\n\t}\n}", "func NewRunner(be func() Backend, host string, userf, passf string) *Runner {\n\treturn &Runner{\n\t\tbe: be,\n\t\thost: host,\n\t\tuserf: userf,\n\t\tpassf: passf,\n\t\tsessions: make(chan error),\n\t\tpwdOver: make(chan struct{}),\n\t\tbroken: makeBroken(),\n\t\tlogins: gen.NewLogins(),\n\t\tagents: gen.NewAgents(),\n\t\tpool: newPool(),\n\t}\n}", "func NewRunner(build libjavabuildpack.Build, maven Maven) Runner {\n\treturn Runner{\n\t\tbuild.Application,\n\t\tbuild.Logger,\n\t\tmaven.Executable(),\n\t}\n}", "func NewAgent(config *config.Config) (*Agent, error) {\n\trunningPlugins := make(map[string]interface{}) // map uuid:plugin\n\n\ta := &Agent{\n\t\tConfig: config,\n\t\trunningPlugins: runningPlugins,\n\t\tic: 0,\n\t\toc: 0,\n\t\tpluginLock: new(sync.Mutex),\n\t\ticLock: new(sync.Mutex),\n\t\tocLock: new(sync.Mutex),\n\t}\n\treturn a, nil\n}", "func NewRunner() *Runner {\n\tr := &Runner{}\n\tr.generator = romanumeral.NewRomanNumeralGenerator()\n\n\treturn r\n}", "func New(cfg Config, logger log.Logger) (*Agent, error) {\n\treturn newAgent(cfg, logger, defaultInstanceFactory)\n}", "func NewRunner(pubClientFactory func() publisher.Client, mod *Wrapper) Runner {\n\treturn &runner{\n\t\tdone: make(chan struct{}),\n\t\tmod: mod,\n\t\tclient: pubClientFactory(),\n\t}\n}", "func NewRunner(reader io.Reader, comp Component) (Runner, error) {\n\tr := &runner{\n\t\tcomp: comp,\n\t}\n\trecvComp, ok := comp.(ReceiveComponent)\n\tif ok {\n\t\tr.recvComp = recvComp\n\t}\n\tsendComp, ok := comp.(SendComponent)\n\tif ok {\n\t\tr.sendComp = sendComp\n\t}\n\terr := r.load(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}", "func TestNewJobRunner(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\n\t// Create testing config\n\tdataDir := test.TestDir(t.Name())\n\tconfig, err := newTestingSiadConfig(dataDir)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create logger\n\tlogger := test.NewTestLogger(t, dataDir)\n\tdefer func() {\n\t\tif err := logger.Close(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t// Create siad process\n\tsiad, err := newSiad(logger, config)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer stopSiad(logger, config.DataDir, config.APIAddr, config.APIPassword, siad.Process)\n\n\t// Create ant client\n\tclient, err := newClient(config.APIAddr, config.APIPassword)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create ant\n\tant := &Ant{\n\t\tstaticAntsSyncWG: &sync.WaitGroup{},\n\t\tstaticLogger: logger,\n\t\tStaticClient: client,\n\t}\n\n\t// Create jobRunnner on same APIAddr as the siad process\n\tj, err := newJobRunner(logger, ant, config.DataDir, \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := j.Stop(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n}", "func NewRunner(wfClientset wfclientset.Interface) *Runner {\n\treturn &Runner{wfClientset: wfClientset}\n}", "func NewJob(name string, f func() (bool, error)) *Job {\n\treturn &Job{Name: name, F: f}\n}", "func NewWorker(ctx context.Context, queueName, amqpURL string, connBackOff backoff.BackOff, autoAck bool, callback workerFunc) (context.CancelFunc, error) {\n\tagentCtx, agentCancel := context.WithCancel(ctx)\n\tlogger := loglib.GetLogger(agentCtx).\n\t\tWithField(\"queue\", queueName).\n\t\tWithField(\"pid\", strconv.Itoa(os.Getpid()))\n\ta := &agent{\n\t\tamqpURL: amqpURL,\n\t\tqueueName: queueName,\n\t\tctx: agentCtx,\n\t\tctxCancel: agentCancel,\n\t\tlogger: logger,\n\t\tconnBackOff: connBackOff,\n\n\t\t// everything above here is identical to NewPublisher\n\t\tworkerFunc: recoverWorkerFunc(logger, callback),\n\t\tautoAck: autoAck,\n\t}\n\treturn a.Stop, a.connect()\n}", "func newJob(job Runnable, priority int) JobEntry {\n\treturn &pt{\n\t\tpriority: priority,\n\t\tjob: job,\n\t\tlock: &sync.Mutex{},\n\t}\n}", "func newWorker(\n\tid int,\n\tlogger *log.Entry,\n\tjobs <-chan *job,\n\tresults chan<- *jobResult,\n\tscheduler *scheduler,\n\toptions *Options,\n) (*worker, error) {\n\treturn &worker{\n\t\tid: id,\n\t\tlogger: logger,\n\n\t\tjobs: jobs,\n\t\tresults: results,\n\n\t\tscheduler: scheduler,\n\t\toptions: options,\n\t}, nil\n}", "func New() *Runner {\n\treturn &Runner{\n\t\tmanager: endly.New(),\n\t\tEvents: NewEventTags(),\n\t\tRenderer: NewRenderer(os.Stdout, 120),\n\t\tgroup: &MessageGroup{},\n\t\txUnitSummary: xunit.NewTestsuite(),\n\t\tStyle: NewStyle(),\n\t}\n}", "func NewRunner(out, errOut io.Writer, ansibleDir string, runDir string) (Runner, error) {\n\t// Ansible depends on python 2.7 being installed and on the path as \"python\".\n\t// Validate that it is available\n\tif _, err := exec.LookPath(\"python\"); err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not find 'python' in the PATH. Ensure that python 2.7 is installed and in the path as 'python'.\")\n\t}\n\n\tppath, err := getPythonPath()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &runner{\n\t\tout: out,\n\t\terrOut: errOut,\n\t\tpythonPath: ppath,\n\t\tansibleDir: ansibleDir,\n\t\trunDir: runDir,\n\t}, nil\n}", "func NewWorkloadAgent() *cobra.Command {\n\to := spoke.NewWorkloadAgentOptions()\n\tcmd := controllercmd.\n\t\tNewControllerCommandConfig(\"work-agent\", version.Get(), o.RunWorkloadAgent).\n\t\tNewCommand()\n\tcmd.Use = \"agent\"\n\tcmd.Short = \"Start the Cluster Registration Agent\"\n\n\to.AddFlags(cmd)\n\treturn cmd\n}", "func NewRunner(sources []string, count int, languagesYml string, autoPull bool, log *logrus.Logger) (*Runner, error) {\n\tvar langs *Languages\n\n\tif languagesYml == \"\" {\n\t\tlanguagesYml = DefaultLanguagesYml\n\t}\n\n\tif _, err := os.Stat(languagesYml); err != nil && autoPull {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"url\": DefaultLanguagesYmlURL,\n\t\t\t\"dest\": languagesYml,\n\t\t}).Info(\"downloading\")\n\n\t\terr = PullLanguagesYml(DefaultLanguagesYmlURL, languagesYml)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif _, err := os.Stat(languagesYml); err == nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"languages\": languagesYml,\n\t\t}).Info(\"loading\")\n\n\t\tlangs, err = LoadLanguages(languagesYml)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &Runner{\n\t\tSources: sources,\n\t\tCount: count,\n\t\tFrobs: DefaultFrobs,\n\t\tLanguages: langs,\n\n\t\tlog: log,\n\t}, nil\n}", "func NewAgent(config *Config) *Agent {\n\tagent := &Agent{\n\t\tconfig: config,\n\t\tbackendSelector: &RandomBackendSelector{Backends: config.BackendURLs},\n\t\thandler: handler.NewMessageHandler(),\n\t\tinProgress: make(map[string]*types.CheckConfig),\n\t\tinProgressMu: &sync.Mutex{},\n\t\tstopping: make(chan struct{}),\n\t\tstopped: make(chan struct{}),\n\t\tsendq: make(chan *transport.Message, 10),\n\t\twg: &sync.WaitGroup{},\n\t}\n\n\tagent.handler.AddHandler(types.CheckRequestType, agent.handleCheck)\n\tagent.assetManager = assetmanager.New(config.CacheDir, agent.getAgentEntity())\n\n\treturn agent\n}", "func NewJob(ctx *pulumi.Context,\n\tname string, args *JobArgs, opts ...pulumi.ResourceOption) (*Job, error) {\n\tif args == nil {\n\t\targs = &JobArgs{}\n\t}\n\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"location\",\n\t\t\"project\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Job\n\terr := ctx.RegisterResource(\"google-native:dataflow/v1b3:Job\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewJob(rule *config.Rule, process *stage.Process, window *batch.Window, group *batch.Group) (*Job, error) {\n\tjob := &Job{\n\t\tStatus: shared.StatusOK,\n\t\tRule: rule,\n\t\tProcess: process,\n\t\tWindow: window,\n\t\tGroup: group,\n\t}\n\n\tdest := rule.Dest.Clone()\n\tvar err error\n\tvar URIs []string\n\tif window != nil {\n\t\tURIs = window.URIs\n\t} else {\n\t\tURIs = []string{process.Source.URL}\n\t}\n\tif len(process.Params) == 0 {\n\t\tprocess.Params = make(map[string]interface{})\n\t}\n\tif group != nil {\n\t\tprocess.Params[shared.GroupID] = group.ID()\n\t\tprocess.GroupURL = group.URL\n\t}\n\texpander := process.Expander(URIs)\n\n\tprocess.DestTable = expander.ExpandAsText(process.DestTable)\n\tprocess.DoneProcessURL = expander.ExpandAsText(process.DoneProcessURL)\n\tprocess.FailedURL = expander.ExpandAsText(process.FailedURL)\n\tprocess.ProcessURL = expander.ExpandAsText(process.ProcessURL)\n\n\tprocess.Params[shared.EventIDKey] = process.EventID\n\tsource := process.Source\n\tif window != nil {\n\t\tsource = window.Source\n\t}\n\tif source == nil {\n\t\tsource = &stage.Source{Time: time.Now()}\n\t}\n\tif _, ok := process.Params[shared.DateKey]; !ok {\n\t\tprocess.Params[shared.DateKey] = source.Time.Format(shared.DateSuffixLayout)\n\t}\n\tif _, ok := process.Params[shared.HourKey]; !ok {\n\t\tprocess.Params[shared.HourKey] = source.Time.Format(\"03\")\n\t}\n\tjob.Load, err = dest.NewJobConfigurationLoad(process.Source, URIs...)\n\treturn job, err\n}", "func NewJob() *Job {\n\tj := &Job{\n\t\tch: make(chan bool),\n\t\twaitGroup: &sync.WaitGroup{},\n\t}\n\treturn j\n}", "func NewJob(fn func() error, opts ...JobOption) Job {\n\tvar o jobOptions\n\to = defaultJobOptions\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tif o.externalTrigger {\n\t\treturn &job{\n\t\t\tfn: fn,\n\t\t}\n\t}\n\n\treturn &cronJob{\n\t\tfn: fn,\n\t\tschedule: o.schedule,\n\t\tcron: o.cron,\n\t}\n}", "func NewJob() helmify.Processor {\n\treturn &job{}\n}", "func NewFromConfig(cfg *Config) *JobManager {\n\treturn New().WithHeartbeatInterval(cfg.GetHeartbeatInterval())\n}", "func newRunner(output string, err error) *MockRunner {\n\tm := &MockRunner{}\n\tm.On(\"Run\", mock.Anything).Return([]byte(output), err)\n\treturn m\n}", "func NewJobReconciler(ctx context.Context, config *config.Config, mgr manager.Manager, podLogGetter PodLogGetter) (reconcile.Reconciler, error) {\n\tversionedSecretStore := versionedsecretstore.NewVersionedSecretStore(mgr.GetClient())\n\n\treturn &ReconcileJob{\n\t\tctx: ctx,\n\t\tconfig: config,\n\t\tclient: mgr.GetClient(),\n\t\tpodLogGetter: podLogGetter,\n\t\tscheme: mgr.GetScheme(),\n\t\tversionedSecretStore: versionedSecretStore,\n\t}, nil\n}", "func (r *resolver) newNode(j *spec.Node, jobArgs map[string]interface{}) (*Node, error) {\n\t// Make a copy of the jobArgs before this node gets created and potentially\n\t// adds additional keys to the jobArgs. A shallow copy is sufficient because\n\t// args values should never change.\n\toriginalArgs := map[string]interface{}{}\n\tfor k, v := range jobArgs {\n\t\toriginalArgs[k] = v\n\t}\n\n\t// Make the name of this node unique within the request by assigning it an id.\n\tid, err := r.idGen.UID()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error making id for '%s %s' job: %s\", *j.NodeType, j.Name, err)\n\t}\n\n\t// Create the job\n\trj, err := r.jobFactory.Make(job.NewIdWithRequestId(*j.NodeType, j.Name, id, r.request.Id))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error making '%s %s' job: %s\", *j.NodeType, j.Name, err)\n\t}\n\n\tif err := rj.Create(jobArgs); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error creating '%s %s' job: %s\", *j.NodeType, j.Name, err)\n\t}\n\n\tbytes, err := rj.Serialize()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error serializing '%s %s' job: %s\", *j.NodeType, j.Name, err)\n\t}\n\n\treturn &Node{\n\t\tName: j.Name,\n\t\tId: id,\n\t\tSpec: j, // on the next refactor, we shouldn't need to set this ourselves\n\t\tJobBytes: bytes,\n\t\tArgs: originalArgs, // Args is the jobArgs map that this node was created with\n\t\tRetry: j.Retry,\n\t\tRetryWait: j.RetryWait,\n\t}, nil\n}", "func NewJob(server Server, command string) *Job {\n\tjob := &Job{}\n\tjob.server = server\n\tjob.command = command\n\tjob.hostConfig = config.forServer(server)\n\tjob.getAgent()\n\tgo job.run()\n\treturn job\n}", "func NewJob(brigadeSVC brigade.Interface, logger log.Logger) subcollector {\n\treturn &job{\n\t\tbrigadeSVC: brigadeSVC,\n\t\tlogger: logger,\n\n\t\tjobInfoDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, jobSubSystem, \"info\"),\n\t\t\t\"Brigade job information.\",\n\t\t\t[]string{\"id\", \"build_id\", \"name\", \"image\"}, nil,\n\t\t),\n\t\tjobStatusDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, jobSubSystem, \"status\"),\n\t\t\t\"Brigade job status.\",\n\t\t\t[]string{\"id\", \"status\"}, nil,\n\t\t),\n\t\tjobDurationDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, jobSubSystem, \"duration_seconds\"),\n\t\t\t\"Brigade job duration in seconds.\",\n\t\t\t[]string{\"id\"}, nil,\n\t\t),\n\t\tjobCreationDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, jobSubSystem, \"create_time_seconds\"),\n\t\t\t\"Brigade job creation time in unix timestamp.\",\n\t\t\t[]string{\"id\"}, nil,\n\t\t),\n\t\tjobStartDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, jobSubSystem, \"start_time_seconds\"),\n\t\t\t\"Brigade job start time in unix timestamp.\",\n\t\t\t[]string{\"id\"}, nil,\n\t\t),\n\t}\n}", "func NewAgent(conf *AgentConfig) (*Agent, error) {\n\tagent := new(Agent)\n\tagent.conf = conf\n\n\t// connection\n\tconn, err := net.DialTimeout(\"tcp4\", agent.conf.Upstream, agent.conf.ConnTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tagent.conn = conn\n\tagent.enc = json.NewEncoder(agent.conn)\n\tagent.dec = json.NewDecoder(agent.conn)\n\n\t// init fields\n\tagent.alias = strings.Split(conf.Username, \".\")[1] + \":\" + conf.Password\n\tagent.notification = make(chan *Request, 10)\n\tagent.respNotification = map[uint64](chan *Response){}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tagent.cancel = cancel\n\tagent.selfDestroyTimer = time.AfterFunc(conf.AgentTimeout, agent.Destroy)\n\n\tgo agent.loop(ctx)\n\tif err := agent.handshake(); err != nil {\n\t\tagent.Destroy()\n\t\treturn nil, err\n\t}\n\treturn agent, nil\n}", "func New() *JobManager {\n\tjm := JobManager{\n\t\theartbeatInterval: DefaultHeartbeatInterval,\n\t\tjobs: map[string]*JobMeta{},\n\t\ttasks: map[string]*TaskMeta{},\n\t}\n\tjm.schedulerWorker = async.NewInterval(jm.runDueJobs, DefaultHeartbeatInterval)\n\tjm.killHangingTasksWorker = async.NewInterval(jm.killHangingTasks, DefaultHeartbeatInterval)\n\treturn &jm\n}", "func New(config *Config) functions.Runner {\n\treturn &impl{*config}\n}", "func NewPluginRunner(plugin interface{}, opts ...RunnerOption) *cobra.Command {\n\tk := &PluginRunner{\n\t\tplugin: plugin,\n\t\tconfig: func(*cobra.Command, []string) ([]byte, error) { return nil, nil },\n\t\tgenerate: func() (resmap.ResMap, error) { return resmap.New(), nil },\n\t\ttransform: func(resmap.ResMap) error { return nil },\n\t\tprint: asYaml,\n\t}\n\n\t// Setup the command run stages\n\tk.cmd = &cobra.Command{\n\t\tPreRunE: k.preRun,\n\t\tRunE: k.run,\n\t\tPostRunE: k.postRun,\n\t}\n\n\t// Establish generate and transform functions\n\tif p, ok := plugin.(resmap.Generator); ok {\n\t\tk.generate = p.Generate\n\t}\n\tif p, ok := plugin.(resmap.Transformer); ok {\n\t\tk.generate = k.newResMapFromStdin\n\t\tk.transform = p.Transform\n\t}\n\n\t// Apply the runner options\n\tfor _, opt := range opts {\n\t\topt(k)\n\t}\n\n\treturn k.cmd\n}", "func newSinkRunner(pipeID string, s phono.Sink) (*sinkRunner, error) {\n\tfn, err := s.Sink(pipeID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := sinkRunner{\n\t\tfn: fn,\n\t\tSink: s,\n\t\thooks: bindHooks(s),\n\t}\n\treturn &r, nil\n}", "func NewRunner(methods MethodMap) *Runner {\n\treturn &Runner{methods}\n}", "func New(coordinateStore storage.CoordinateStore, sourceCoords storage.Coords,\n\tradius, maxParallelJobs, numberOfPoints int) *Runner {\n\treturn &Runner{coordinateStore: coordinateStore,\n\t\thaversine: haversine.New(radius),\n\t\tsemaphore: make(chan struct{}, maxParallelJobs),\n\t\tsourceCoords: sourceCoords,\n\t\tcoordsList: make([]CoordsWithDistance, 0),\n\t\tnumberOfPoints: numberOfPoints,\n\t}\n}", "func NewJob() Job {\n\tjobConfig := aurora.NewJobConfiguration()\n\ttaskConfig := aurora.NewTaskConfig()\n\tjobKey := aurora.NewJobKey()\n\n\t// Job Config\n\tjobConfig.Key = jobKey\n\tjobConfig.TaskConfig = taskConfig\n\n\t// Task Config\n\ttaskConfig.Job = jobKey\n\ttaskConfig.Container = aurora.NewContainer()\n\ttaskConfig.Container.Mesos = aurora.NewMesosContainer()\n\n\t// Resources\n\tnumCpus := aurora.NewResource()\n\tramMb := aurora.NewResource()\n\tdiskMb := aurora.NewResource()\n\n\tresources := map[resourceType]*aurora.Resource{CPU: numCpus, RAM: ramMb, DISK: diskMb}\n\ttaskConfig.Resources = []*aurora.Resource{numCpus, ramMb, diskMb}\n\n\tnumCpus.NumCpus = new(float64)\n\tramMb.RamMb = new(int64)\n\tdiskMb.DiskMb = new(int64)\n\n\treturn &AuroraJob{\n\t\tjobConfig: jobConfig,\n\t\tresources: resources,\n\t\tmetadata: make(map[string]*aurora.Metadata),\n\t\tconstraints: make(map[string]*aurora.Constraint),\n\t\tportCount: 0,\n\t}\n}", "func NewRunnerAPI() runnerAPI {\n\treturn runnerAPI{}\n}", "func newJobJob(dbJob *models.Job) (j *JobJob, err error) {\n\tj = &JobJob{Job: NewJob(dbJob)}\n\tj.TargetJob, err = models.FindJob(dbJob.ObjectID)\n\tif err != nil {\n\t\treturn j, err\n\t}\n\tif j.TargetJob == nil {\n\t\treturn j, fmt.Errorf(\"job id %d does not exist\", dbJob.ObjectID)\n\t}\n\treturn j, err\n}", "func New() *Agent {\n\treturn &Agent{\n\t\tReporter: newReporter(),\n\t\tWarmUp: config.WarmupEnabled,\n\t\tTimeoutMargin: config.TimeoutMargin,\n\t\tPlugins: []plugin.Plugin{},\n\t}\n}", "func newAITrainingJobs(c *ElasticdeeplearningV1Client, namespace string) *aITrainingJobs {\n\treturn &aITrainingJobs{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func NewJob() *Job {\n\treturn &Job{\n\t\tID: uuid.New().String(),\n\t\tPriority: PriorityNormal,\n\t\tTimestamp: time.Now(),\n\t\tContentType: ContentTypeMsgpack,\n\t}\n}", "func NewJobManager(arm weles.ArtifactManager, yap weles.Parser, bor boruta.Requests,\n\tborutaRefreshPeriod time.Duration, djm weles.DryadJobManager) weles.JobManager {\n\n\tjs := NewJobsController()\n\tpa := NewParser(js, arm, yap)\n\tdo := NewDownloader(js, arm)\n\tbo := NewBoruter(js, bor, borutaRefreshPeriod)\n\tdr := NewDryader(js, djm)\n\n\treturn NewController(js, pa, do, bo, dr)\n}", "func NewAgent(skipPrechecks bool, hostAnnotations map[string]string) (*Agent, error) {\n\tredisAddr := viper.GetString(\"redis\")\n\tif redisAddr == \"\" {\n\t\treturn nil, errors.New(\"The redis address cannot be empty\")\n\t}\n\n\trH, rP := utils.GetHostPort(redisAddr)\n\tredisAddr = fmt.Sprintf(\"%s:%d\", rH, rP)\n\n\tmanagerAddr := viper.GetString(\"manager\")\n\tif managerAddr == \"\" {\n\t\treturn nil, errors.New(\"The manager address cannot be empty\")\n\t}\n\n\tclient, err := redis.NewClient(redisAddr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not create redis client: %v\", err)\n\t}\n\n\texecutorServer, err := NewExecutor(managerAddr, client, skipPrechecks, hostAnnotations)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpPort := fmt.Sprintf(\":%d\", pkg.HTTPPortWindow+rP)\n\thttpServer, err := NewHTTPServer(httpPort, map[string]string{\n\t\t\"module\": \"agent\",\n\t\t\"redisAddr\": redisAddr,\n\t\t\"managerAddr\": managerAddr,\n\t\t\"hostAnnotations\": fmt.Sprintf(\"%v\", hostAnnotations),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Agent{\n\t\tclient: client,\n\t\thttpServer: httpServer,\n\t\texecutor: executorServer,\n\t}, nil\n}", "func New(runner, tracker, hosted string) *Runner {\n\tn := &Runner{\n\t\ttcl: client.New(tracker, http.DefaultClient, client.JsonCodec),\n\t\tbase: hosted,\n\t\trunner: runner,\n\t\trpc: gorpc.NewServer(),\n\t\trq: rpc.NewRunnerQueue(),\n\t\tresp: make(chan rpc.Output),\n\t}\n\n\t//register the run service in the rpc\n\tif err := n.rpc.RegisterService(n.rq, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\t//register the pinger\n\tif err := n.rpc.RegisterService(pinger.Pinger{}, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\t//register ourselves in the rpc\n\tif err := n.rpc.RegisterService(n, \"\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\t//register the codec\n\tn.rpc.RegisterCodec(json.NewCodec(), \"application/json\")\n\n\t//start processing\n\tgo n.run()\n\n\treturn n\n}", "func newJobQueue(ctx context.Context, consumerCount, length int) *jobQueue {\n\teg, selfCtx := errgroup.WithContext(ctx)\n\treturn &jobQueue{\n\t\tctx: selfCtx,\n\t\tmsgq: make(chan *restoreSchemaJob, length),\n\t\tconsumerCount: consumerCount,\n\t\teg: eg,\n\t}\n}", "func New(config Config) (*Worker, error) {\n\tw := &Worker{hasLimits: config.Limits != nil, jobs: map[string]map[string]*Job{}}\n\t// Only use limited runner when resource limits are set\n\tif w.hasLimits {\n\t\tvar err error\n\t\tif w.runner, err = newLimitedRunner(config.Limits); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"creating limited runner: %w\", err)\n\t\t}\n\t} else {\n\t\tw.runner = newRunner()\n\t}\n\treturn w, nil\n}", "func NewCommandRunner(args []string) *CommandRunner {\n\tcr := &CommandRunner{}\n\n\tcr.args = os.Args[1:]\n\tcr.runChan = make(chan bool)\n\tcr.killChan = make(chan bool)\n\n\treturn cr\n}", "func NewJob(id string, check CheckFunc, task TaskFunc) *Job {\n\treturn &Job{id, check, task}\n}", "func NewJob(receipts []uuid.UUID, sendTime time.Time) *Job {\n\treturn &Job{\n\t\tID: uuid.NewUUID(),\n\t\tSendTime: sendTime,\n\t\tSendStatus: READY,\n\t\tReceipts: receipts,\n\t}\n}", "func JobLogsFactory(ui cli.Ui) cli.CommandFactory {\n\tcmd := &JobLogs{}\n\tcmd.command = createCommand(ui, cmd.Execute, cmd.Description, cmd.Usage, cmd, nil, flags.None, \"nerd job logs\")\n\treturn func() (cli.Command, error) {\n\t\treturn cmd, nil\n\t}\n}", "func NewJob(object dbus.BusObject) *Job {\n\treturn &Job{object}\n}", "func NewJob(interval time.Duration) *Job {\n\treturn &Job{\n\t\tinterval: interval,\n\t\tfuncs: make(map[string]interface{}),\n\t\tfparams: make(map[string][]interface{}),\n\t\ttags: []string{},\n\t}\n}", "func NewJobRepository(ctxIn context.Context, credentialsProvider secret.SecretProvider) (JobRepository, error) {\n ctx, span := trace.StartSpan(ctxIn, \"NewJobRepository\")\n defer span.End()\n\n storageService, err := service.NewStorageService(ctx, credentialsProvider)\n if err != nil {\n return nil, err\n }\n return &defaultJobRepository{storageService: storageService}, nil\n}", "func NewAgent(config *config.Config) (*Agent, error) {\n\ta := &Agent{\n\t\tConfig: config,\n\t}\n\n\tif !a.Config.Agent.OmitHostname {\n\t\tif a.Config.Agent.Hostname == \"\" {\n\t\t\thostname, err := os.Hostname()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\ta.Config.Agent.Hostname = hostname\n\t\t}\n\n\t\tconfig.Tags[\"host\"] = a.Config.Agent.Hostname\n\t}\n\n\treturn a, nil\n}", "func NewJob(name string, schedule string, ) *Job {\n\tthis := Job{}\n\tthis.Name = name\n\tthis.Schedule = schedule\n\treturn &this\n}", "func NewAgent(c *AgentConfig, env *envv1.Env) (*Agent, error) {\n\tif c == nil {\n\t\tc = DefaultAgentConfig\n\t}\n\tif c.Base == nil {\n\t\tc.Base = DefaultAgentConfig.Base\n\t}\n\tif env == nil {\n\t\treturn nil, fmt.Errorf(\"environment cannot be nil\")\n\t}\n\tif c.Epsilon == nil {\n\t\tc.Epsilon = common.DefaultDecaySchedule()\n\t}\n\tpolicy, err := MakePolicy(\"online\", c.PolicyConfig, c.Base, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.PolicyConfig.Track = false\n\ttargetPolicy, err := MakePolicy(\"target\", c.PolicyConfig, c.Base, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tepsilon := c.Base.Tracker.TrackValue(\"epsilon\", c.Epsilon.Initial())\n\treturn &Agent{\n\t\tBase: c.Base,\n\t\tHyperparameters: c.Hyperparameters,\n\t\tmemory: NewMemory(c.MemorySize),\n\t\tPolicy: policy,\n\t\tTargetPolicy: targetPolicy,\n\t\tEpsilon: c.Epsilon,\n\t\tepsilon: epsilon.(*track.TrackedScalarValue),\n\t\tenv: env,\n\t\tupdateTargetSteps: c.UpdateTargetEpisodes,\n\t\tbatchSize: c.PolicyConfig.BatchSize,\n\t\tsuccessfulReward: c.SuccessfulReward,\n\t}, nil\n}", "func NewFromEnv() *JobManager {\n\treturn NewFromConfig(NewConfigFromEnv())\n}", "func NewProblemRunner(factory ProblemFactory) *ProblemRunner {\n\treturn &ProblemRunner{factory, nil, nil}\n}", "func newScheduledJobs(c *BatchClient, namespace string) *scheduledJobs {\n\treturn &scheduledJobs{c, namespace}\n}", "func NewRunner(cli *DockerClient, problemDir, fileName, ft string, timeLimit time.Duration) (*Runner, error) {\n\tdef := languageDefs[ft]\n\n\ttestCtr := &Container{\n\t\tDocker: cli,\n\t\tImage: def.Image,\n\t\tCmd: []string{\"sleep\", \"1000000000000\"},\n\t\tWorkingDir: \"/mnt\",\n\t\tOut: os.Stdout,\n\t\tReadOnly: true,\n\t}\n\n\tif err := testCtr.BindDir(problemDir, \"/mnt\", true); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := testCtr.Run(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Runner{\n\t\tproblemDir: problemDir,\n\t\tfileName: fileName,\n\t\tcontainer: testCtr,\n\t\ttimeLimit: timeLimit,\n\t\tft: ft,\n\t}, nil\n}", "func New(cfg *Config, db *store.DB) *Runner {\n\treporter := &Reporter{\n\t\tdb: db,\n\t}\n\treconciler := &Reconciler{\n\t\tdb: db,\n\t\treporter: reporter,\n\t}\n\tsrv := &Server{\n\t\treporter: reporter,\n\t}\n\tsrv.run(cfg.StatusPort)\n\tsyncer := &Syncer{\n\t\tdb: db,\n\t\treporter: reporter,\n\t}\n\treturn &Runner{\n\t\tcfg: cfg,\n\t\tdb: db,\n\t\treconciler: reconciler,\n\t\treporter: reporter,\n\t\tsyncer: syncer,\n\t}\n}", "func (m *MemoryStorage) NewJob(parent context.Context, params JobParams, log *logrus.Entry) (Job, error) {\n\tvar err error\n\t// Validate all the mandatory params are present.\n\tswitch {\n\tcase params.CheckID == \"\":\n\t\terr = errors.New(\"check job missing check ID\")\n\tcase params.Target == \"\":\n\t\terr = errors.New(\"check job missing image\")\n\tcase params.Timeout <= 0:\n\t\terr = errors.New(\"check job missing timeout\")\n\t}\n\n\tif err != nil {\n\t\treturn Job{}, err\n\t}\n\n\tjob := Job{\n\t\tJobParams: JobParams{\n\t\t\tScanID: params.ScanID,\n\t\t\tScanStartTime: params.ScanStartTime,\n\t\t\tCheckID: params.CheckID,\n\t\t\tTarget: params.Target,\n\t\t\tOptions: params.Options,\n\t\t\tRequiredVars: params.RequiredVars,\n\t\t\tImage: params.Image,\n\t\t\tTimeout: params.Timeout,\n\t\t},\n\t\tlog: log,\n\t}\n\n\tjob.Ctx, job.Cancel = context.WithCancel(parent)\n\n\terr = m.Add(job)\n\tif err != nil {\n\t\treturn Job{}, UnableToAddJobError{err}\n\t}\n\treturn job, nil\n}", "func NewMockRunner(ctrl *gomock.Controller) *MockRunner {\n\tmock := &MockRunner{ctrl: ctrl}\n\tmock.recorder = &MockRunnerMockRecorder{mock}\n\treturn mock\n}", "func NewMockRunner(ctrl *gomock.Controller) *MockRunner {\n\tmock := &MockRunner{ctrl: ctrl}\n\tmock.recorder = &MockRunnerMockRecorder{mock}\n\treturn mock\n}", "func NewAgent(csrConfig CSRConfig, kubeconfigFile string) (*CertAgent, error) {\n\tcontent, err := ioutil.ReadFile(kubeconfigFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading file %s: %v\", kubeconfigFile, err)\n\t}\n\tkubeconfig, err := clientcmd.Load(content)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading config from bytes: %v\", err)\n\t}\n\tconfig, err := clientcmd.NewDefaultClientConfig(*kubeconfig, &clientcmd.ConfigOverrides{}).ClientConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating client config: %v\", err)\n\t}\n\n\tclient, err := certificatesclient.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating client: %v\", err)\n\t}\n\n\treturn &CertAgent{\n\t\tclient: client.CertificateSigningRequests(),\n\t\tconfig: csrConfig,\n\t}, nil\n}", "func NewJobClient(c config) *JobClient {\n\treturn &JobClient{config: c}\n}", "func NewJob(intervel uint64) *Job {\n\treturn &Job{\n\t\tintervel, 0,\n\t\t\"\",\n\t\tJOB_UNIT_TYPE_UNKNOWN,\n\t\t\"\",\n\t\ttime.Unix(0, 0),\n\t\ttime.Unix(0, 0), 0,\n\t\tmake(map[string]interface{}),\n\t\tmake(map[string]([]interface{})),\n\t}\n}", "func NewJobRepo() JobRepo {\n\treturn JobRepo{}\n}", "func NewAgent() *cobra.Command {\n\tvar opts struct {\n\t\tAgentID string\n\t\tTinkServerAddr string\n\t}\n\n\t// TODO(chrisdoherty4) Handle signals\n\tcmd := cobra.Command{\n\t\tUse: \"tink-agent\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tzl, err := zap.NewProduction()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"init logger: %w\", err)\n\t\t\t}\n\t\t\tlogger := zapr.NewLogger(zl)\n\n\t\t\trntime, err := runtime.NewDocker()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"create runtime: %w\", err)\n\t\t\t}\n\n\t\t\tconn, err := grpc.DialContext(cmd.Context(), opts.TinkServerAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"dial tink server: %w\", err)\n\t\t\t}\n\t\t\tdefer conn.Close()\n\t\t\ttrnport := transport.NewGRPC(logger, workflow.NewWorkflowServiceClient(conn))\n\n\t\t\treturn (&agent.Agent{\n\t\t\t\tLog: logger,\n\t\t\t\tID: opts.AgentID,\n\t\t\t\tTransport: trnport,\n\t\t\t\tRuntime: rntime,\n\t\t\t}).Start(cmd.Context())\n\t\t},\n\t}\n\n\tflgs := cmd.Flags()\n\tflgs.StringVar(&opts.AgentID, \"agent-id\", \"\", \"An ID that uniquely identifies the agent instance\")\n\tflgs.StringVar(&opts.TinkServerAddr, \"tink-server-addr\", \"127.0.0.1:42113\", \"Tink server address\")\n\n\treturn &cmd\n}", "func NewRunner(parent string) *Runner {\n\tr := &Runner{}\n\tc := &cobra.Command{\n\t\tUse: \"fix LOCAL_PKG_DIR\",\n\t\tArgs: cobra.ExactArgs(1),\n\t\tShort: docs.FixShort,\n\t\tLong: docs.FixShort + \"\\n\" + docs.FixLong,\n\t\tExample: docs.FixExamples,\n\t\tPreRunE: r.preRunE,\n\t\tRunE: r.runE,\n\t\tSuggestFor: []string{\"upgrade\", \"migrate\"},\n\t}\n\tcmdutil.FixDocs(\"kpt\", parent, c)\n\tc.Flags().BoolVar(&r.Fix.DryRun, \"dry-run\", false,\n\t\t`Dry run emits the actions`)\n\tr.Command = c\n\treturn r\n}" ]
[ "0.7033698", "0.62534994", "0.60575217", "0.5997101", "0.59296507", "0.5779144", "0.57462084", "0.57345396", "0.5700003", "0.5682094", "0.5681728", "0.5668359", "0.56301194", "0.56086624", "0.55953586", "0.55779314", "0.5573774", "0.5547928", "0.5511023", "0.55041426", "0.5493595", "0.5448719", "0.5422388", "0.5406", "0.53861046", "0.5383675", "0.5378998", "0.5376129", "0.53621095", "0.5360486", "0.53522056", "0.5344257", "0.5329159", "0.53258646", "0.5321638", "0.5318544", "0.53112584", "0.5253882", "0.5234477", "0.51769423", "0.51577055", "0.5148782", "0.5141505", "0.51354647", "0.51328754", "0.512745", "0.5126575", "0.5098505", "0.5091832", "0.5084475", "0.5082747", "0.50747466", "0.50737846", "0.50704235", "0.506834", "0.5058879", "0.50540626", "0.5045829", "0.5006087", "0.50049084", "0.4992478", "0.49841505", "0.49838477", "0.4978561", "0.49684158", "0.49595222", "0.49567148", "0.49563858", "0.494712", "0.49403986", "0.490553", "0.49024287", "0.48929203", "0.48886797", "0.48766673", "0.48606303", "0.48568016", "0.48538506", "0.4853593", "0.4850836", "0.4838041", "0.4821698", "0.48079702", "0.4807305", "0.48033088", "0.48013318", "0.48002848", "0.4797637", "0.47906965", "0.4790488", "0.47776717", "0.47741547", "0.47723725", "0.47723725", "0.47710413", "0.47632095", "0.47627965", "0.4755024", "0.475409", "0.4749362" ]
0.7297188
0
run runs the agent.
func run(cfg config.Config, jrunner *jobrunner.Runner, updater api.CheckStateUpdater, jobsQueue queue.Reader, logger log.Logger) error { // Build metrics component. metrics := metrics.NewMetrics(logger, cfg.DataDog, jrunner) // Create a context to orchestrate the shutdown of the // different components. ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Initialize check cancel stream if an endpoint is provided. var ( err error streamDone <-chan error ) if cfg.Stream.Endpoint == "" { logger.Infof("check cancel stream disabled") } else { re := retryer.NewRetryer(cfg.Stream.Retries, cfg.Stream.RetryInterval, logger) // metrics is passed as a stream message processor to // abort checks. stream := stream.New(logger, metrics, re, cfg.Stream.Endpoint) streamDone, err = stream.ListenAndProcess(ctx) if err != nil { return fmt.Errorf("stream start: %w", err) } } // Build stats components that exposes information about the // agent. stats := struct { *jobrunner.Runner queue.Reader }{jrunner, jobsQueue} // Start agent's HTTP API. api := api.New(logger, updater, stats) router := httprouter.New() httpapi.NewREST(logger, api, router) srv := http.Server{Handler: router} httpDone := make(chan error) go func() { var err error if cfg.API.Listener != nil { err = srv.Serve(cfg.API.Listener) } else { srv.Addr = cfg.API.Port err = srv.ListenAndServe() } httpDone <- err close(httpDone) }() // Wait while the agent runs. qrdone := jobsQueue.StartReading(ctx) metricsDone := metrics.StartPolling(ctx) var agentAddr string if cfg.API.Listener != nil { agentAddr = cfg.API.Listener.Addr().String() } else { agentAddr = cfg.API.Port } logger.Infof("agent running on address %s", agentAddr) sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) select { case <-sig: // Signal SQS queue reader to stop reading messages // from the queue. logger.Infof("SIG received, stopping agent") cancel() case err := <-httpDone: logger.Errorf("error running agent: %+v", err) cancel() case err := <-qrdone: cancel() if err != nil { if !errors.Is(err, queue.ErrMaxTimeNoRead) && !errors.Is(err, context.Canceled) { return fmt.Errorf("agent run: %w", err) } } } // Wait for all pending jobs to finish. logger.Infof("waiting for checks to finish") err = <-qrdone if err != nil && !errors.Is(err, context.Canceled) { logger.Errorf("error waiting for checks to finish %+v", err) } // Wait for metrics to stop polling. logger.Debugf("waiting for metrics to stop") <-metricsDone // Stop listening API HTTP requests. logger.Debugf("stop listening API requests") err = srv.Shutdown(context.Background()) if err != nil { return fmt.Errorf("http server shutdown: %w", err) } // Wait for HTTP API to shutdown. err = <-httpDone if err != nil && !errors.Is(err, http.ErrServerClosed) { return fmt.Errorf("http server shutdown wait: %w", err) } // Wait for stream to finish. if streamDone != nil { logger.Debugf("waiting for stream to stop") err = <-streamDone if err != nil && !errors.Is(err, context.Canceled) { return fmt.Errorf("stream stop wait: %w", err) } } logger.Infof("agent finished gracefully") return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func run(ctx context.Context, cfg *config.Config, configFilepath string) {\n\tvar cancel context.CancelFunc\n\tctx, cancel = context.WithCancel(ctx)\n\n\t// Actions runner is currently created inside client.New.\n\t// It should be created separately.\n\t// TODO https://jira.percona.com/browse/PMM-7206\n\n\tsupervisor := supervisor.NewSupervisor(ctx, &cfg.Paths, &cfg.Ports, &cfg.Server)\n\tconnectionChecker := connectionchecker.New(&cfg.Paths)\n\tv := versioner.New(&versioner.RealExecFunctions{})\n\tclient := client.New(cfg, supervisor, connectionChecker, v)\n\tlocalServer := agentlocal.NewServer(cfg, supervisor, client, configFilepath)\n\n\tgo func() {\n\t\t_ = client.Run(ctx)\n\t\tcancel()\n\t}()\n\n\tlocalServer.Run(ctx)\n\tcancel()\n\n\t<-client.Done()\n}", "func runAgent() {\n\tvar err error\n\tgo func() {\n\t\tconfig, err := initializeConfig()\n\t\tif err != nil {\n\t\t\tclosing <- errors.Annotate(err, \"Error when Initialize Config\")\n\t\t\treturn\n\t\t}\n\n\t\tlog.SetOutput(os.Stdout)\n\t\tlogLevel, err := log.ParseLevel(config.GetString(\"agent.loglevel\"))\n\t\tif err != nil {\n\t\t\tlogLevel = log.DebugLevel\n\t\t}\n\t\tlog.SetLevel(logLevel)\n\t\tlog.WithField(\"level\", log.DebugLevel).Info(\"log level\")\n\n\t\terr = core.Run(config, closing)\n\t\tif err != nil {\n\t\t\tclosing <- err\n\t\t\treturn\n\t\t}\n\t\tlog.Info(\"Agent started\")\n\t}()\n\n\terr = <-closing\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error running agent\")\n\t}\n\tlog.Info(\"Closing, Bye !\")\n}", "func (a *Agent) Run() {\n\tagent.RegisterAPIValidator(a.validateAPI)\n\tagent.OnConfigChange(a.onConfigChange)\n\n\tgo a.discoveryLoop()\n\tgo a.publishLoop()\n\n\tselect {\n\tcase <-a.stopAgent:\n\t\tlog.Info(\"Received request to kill agent\")\n\t\ta.stopDiscovery <- true\n\t\ta.stopPublish <- true\n\t\treturn\n\t}\n}", "func (a *RESTAgent) Run(args []string) int {\n\tvar address string\n\tcmdFlags := flag.NewFlagSet(\"agent\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { a.UI.Error(a.Help()) }\n\tcmdFlags.StringVar(&address, \"address\", \"\", \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\t//Check address\n\tif address == \"\" {\n\t\ta.UI.Error(\"Address must be specified\")\n\t\ta.UI.Error(\"\")\n\t\ta.UI.Error(a.Help())\n\t\treturn 1\n\t}\n\n\texitChannel := make(chan int)\n\tsignalChannel := make(chan os.Signal, 1)\n\tsignal.Notify(signalChannel, os.Interrupt)\n\n\tgo func() {\n\t\tfor _ = range signalChannel {\n\t\t\texitChannel <- 0\n\t\t}\n\t}()\n\n\tgo func(addr string, kvs kvstore.KVStore) {\n\t\tagent := agent.NewAgent(addr, kvs)\n\t\tagent.Start()\n\t\texitChannel <- 1\n\t}(address, a.KVStore)\n\n\texitStatus := <-exitChannel\n\tfmt.Printf(\"exiting with status %d\\n\", exitStatus)\n\treturn exitStatus\n}", "func (a *Agent) Run() error {\n\t/*\n\t* Start the agent service\n\t*\n\t* Tasks:\n\t* - Initialize Redis connection\n\t* - Start the http debug server and metrics endpoint\n\t* - Start the executor responsible for ensuring node state\n\t */\n\tvar errChan = make(chan error, 1)\n\n\tgo func(errChan chan error) {\n\t\tlog.Infof(\"Starting http server on %s\", a.httpServer.GetListenAddr())\n\t\terrChan <- a.httpServer.Run()\n\t}(errChan)\n\n\tgo func(errChan chan error) {\n\t\tlog.Info(\"Starting executor\")\n\t\terrChan <- a.executor.Run()\n\t}(errChan)\n\n\treturn <-errChan\n}", "func (or *orchestrator) run() {\n\t// make sure we are orchestrated\n\tif or.mgr == nil {\n\t\tpanic(fmt.Errorf(\"no svc manager set on %s\", or.name()))\n\t}\n\n\t// signal manager we started and go\n\tor.mgr.started(or)\n\tgo or.execute()\n}", "func (a *Agent) Run() (loadtest.Status, error) {\n\tvar status loadtest.Status\n\tresp, err := a.apiPost(a.apiURL+a.id+\"/run\", nil)\n\tif err != nil {\n\t\treturn status, err\n\t}\n\tstatus = *resp.Status\n\treturn status, nil\n}", "func (mgr *manager) run() {\n\tlog(mgr.reportingTo.Name(), \"working\", nil, false)\n\tdefer log(mgr.reportingTo.Name(), \"all done\", nil, false)\n\tstepFn := mgr.step_Accepting\n\tfor {\n\t\tif stepFn == nil {\n\t\t\tbreak\n\t\t}\n\t\tstepFn = stepFn()\n\t}\n}", "func (trd *trxDispatcher) run() {\n\t// make sure we are orchestrated\n\tif trd.mgr == nil {\n\t\tpanic(fmt.Errorf(\"no svc manager set on %s\", trd.name()))\n\t}\n\n\t// start the block observer ticker\n\ttrd.bot = time.NewTicker(trxDispatchBlockUpdateTicker)\n\n\t// signal orchestrator we started and go\n\ttrd.mgr.started(trd)\n\tgo trd.execute()\n}", "func (as *AgentServer) Run() {\n\t//register agent\n\tkillHeartBeaterChan := make(chan bool, 1)\n\tgo client.NewHeartBeater(*as.Option.Host, *as.Option.Port, as.Master).StartAgentHeartBeat(killHeartBeaterChan, func(values url.Values) {\n\t\tresource.AddToValues(values, as.computeResource, as.allocatedResource)\n\t\tvalues.Add(\"dataCenter\", *as.Option.DataCenter)\n\t\tvalues.Add(\"rack\", *as.Option.Rack)\n\t})\n\n\tfor {\n\t\t// Listen for an incoming connection.\n\t\tconn, err := as.listener.Accept()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error accepting: \", err.Error())\n\t\t\tcontinue\n\t\t}\n\t\t// Handle connections in a new goroutine.\n\t\tas.wg.Add(1)\n\t\tgo func() {\n\t\t\tdefer as.wg.Done()\n\t\t\tdefer conn.Close()\n\t\t\tif err = conn.SetDeadline(time.Time{}); err != nil {\n\t\t\t\tfmt.Printf(\"Failed to set timeout: %v\\n\", err)\n\t\t\t}\n\t\t\tif c, ok := conn.(*net.TCPConn); ok {\n\t\t\t\tc.SetKeepAlive(true)\n\t\t\t}\n\t\t\tas.handleRequest(conn)\n\t\t}()\n\t}\n}", "func (monitor *agentMonitor) Run(stopCh <-chan struct{}) {\n\tklog.Info(\"Starting Antrea Agent Monitor\")\n\tagentCRD := monitor.getAgentCRD()\n\tvar err error = nil\n\tfor {\n\t\tif agentCRD == nil {\n\t\t\tagentCRD, err = monitor.createAgentCRD()\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to create agent monitoring CRD %v : %v\", agentCRD, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\tagentCRD, err = monitor.updateAgentCRD(agentCRD)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Failed to update agent monitoring CRD %v : %v\", agentCRD, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ttime.Sleep(60 * time.Second)\n\t}\n\t<-stopCh\n}", "func (a *Agent) Run(ctx context.Context) error {\n\ta.Context = ctx\n\tlog.Printf(\"I! [agent] Config: Interval:%s, Quiet:%#v, Hostname:%#v, \"+\n\t\t\"Flush Interval:%s\",\n\t\ta.Config.Agent.Interval.Duration, a.Config.Agent.Quiet,\n\t\ta.Config.Agent.Hostname, a.Config.Agent.FlushInterval.Duration)\n\n\tlog.Printf(\"D! [agent] Initializing plugins\")\n\terr := a.initPlugins()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstartTime := time.Now()\n\tlog.Printf(\"D! [agent] Connecting outputs\")\n\tnext, ou, err := a.startOutputs(ctx, a.Config.Outputs)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.ou = ou\n\tvar apu []*processorUnit\n\tvar au *aggregatorUnit\n\tif len(a.Config.Aggregators) != 0 {\n\t\taggC := next\n\t\tif len(a.Config.AggProcessors) != 0 {\n\t\t\taggC, apu, err = a.startProcessors(next, a.Config.AggProcessors)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tnext, au, err = a.startAggregators(aggC, next, a.Config.Aggregators)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar pu []*processorUnit\n\tif len(a.Config.Processors) != 0 {\n\t\tnext, pu, err = a.startProcessors(next, a.Config.Processors)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tiu, err := a.startInputs(next, a.Config.Inputs)\n\ta.iu = iu\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := a.runOutputs(ou)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"E! [agent] Error running outputs: %v\", err)\n\t\t}\n\t}()\n\n\tif au != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terr := a.runProcessors(apu)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error running processors: %v\", err)\n\t\t\t}\n\t\t}()\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terr := a.runAggregators(startTime, au)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error running aggregators: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\tif pu != nil {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terr := a.runProcessors(pu)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"E! [agent] Error running processors: %v\", err)\n\t\t\t}\n\t\t}()\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\terr := a.runInputs(ctx, startTime, iu)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"E! [agent] Error running inputs: %v\", err)\n\t\t}\n\t}()\n\n\twg.Wait()\n\n\tlog.Printf(\"D! [agent] Stopped Successfully\")\n\treturn err\n}", "func (a *Agent) Run() (err error) {\n\talog.Info(\"Starting up agent...\")\n\t// start listening for ipc messages\n\t_ = a.notificationHandler.Start()\n\n\tcfg := a.Context.cfg\n\n\tf := a.cpuProfileStart()\n\tif f != nil {\n\t\tdefer a.cpuProfileStop(f)\n\t}\n\n\tgo a.intervalMemoryProfile()\n\n\tif cfg.ConnectEnabled {\n\t\tgo a.connect()\n\t}\n\n\talog.Debug(\"Starting Plugins.\")\n\ta.startPlugins()\n\n\tif err != nil {\n\t\talog.WithError(err).Error(\"failed to start troubleshooting handler\")\n\t}\n\n\tif a.Context.eventSender != nil {\n\t\tif err := a.Context.eventSender.Start(); err != nil {\n\t\t\talog.WithError(err).Error(\"failed to start event sender\")\n\t\t}\n\t}\n\n\tif a.metricsSender != nil {\n\t\tif err := a.metricsSender.Start(); err != nil {\n\t\t\talog.WithError(err).Error(\"failed to start metrics subsystem\")\n\t\t}\n\t}\n\n\t// Timers\n\treapInventoryTimer := time.NewTicker(cfg.FirstReapInterval)\n\tsendInventoryTimer := time.NewTimer(cfg.SendInterval) // Send any deltas every X seconds\n\tdebugTimer := time.Tick(time.Duration(a.Context.Config().DebugLogSec) * time.Second)\n\n\t//Remove send timer\n\tif !a.shouldSendInventory() {\n\t\tsendInventoryTimer.Stop()\n\t\treapInventoryTimer.Stop()\n\t\talog.Info(\"inventory submission disabled\")\n\t}\n\n\t// Timer to engage the process of deleting entities that haven't been reported information during this time\n\tremoveEntitiesPeriod, err := time.ParseDuration(a.Context.Config().RemoveEntitiesPeriod)\n\tif removeEntitiesPeriod <= 0 || err != nil {\n\t\tremoveEntitiesPeriod = defaultRemoveEntitiesPeriod\n\t\terr = nil\n\t}\n\n\tremoveEntitiesTicker := time.NewTicker(removeEntitiesPeriod)\n\treportedEntities := map[string]bool{}\n\n\t// Wait no more than this long for initial inventory reap even if some plugins haven't reported data\n\tinitialReapTimeout := time.NewTimer(config.INITIAL_REAP_MAX_WAIT_SECONDS * time.Second)\n\n\t// keep track of which plugins have phone home\n\tidsReporting := make(map[ids.PluginID]bool)\n\tdistinctPlugins := make(map[ids.PluginID]Plugin)\n\tfor _, p := range a.plugins {\n\t\tdistinctPlugins[p.Id()] = p\n\t}\n\n\t// Register local entity inventory\n\t// This will make the agent submitting unsent deltas from a previous execution (e.g. if an inventory was reaped\n\t// but the agent was restarted before sending it)\n\tif _, ok := a.inventories[a.Context.EntityKey()]; !ok {\n\t\t_ = a.registerEntityInventory(entity.NewFromNameWithoutID(a.Context.EntityKey()))\n\t}\n\n\texit := make(chan struct{})\n\n\tgo func() {\n\t\t<-a.Context.Ctx.Done()\n\n\t\ta.exitGracefully(sendInventoryTimer, reapInventoryTimer, removeEntitiesTicker)\n\n\t\tclose(exit)\n\n\t\t// Should not reach here, just a guard.\n\t\t//<-time.After(service.GracefulExitTimeout)\n\t\t//log.Warn(\"graceful stop time exceeded... forcing stop\")\n\t\t//os.Exit(0)\n\t}()\n\n\t// three states\n\t// -- reading data to write to json\n\t// -- reaping\n\t// -- sending\n\t// ready to consume events\n\tfor {\n\t\tselect {\n\t\tcase <-exit:\n\t\t\treturn nil\n\t\t\t// agent gets notified about active entities\n\t\tcase ent := <-a.Context.activeEntities:\n\t\t\treportedEntities[ent] = true\n\t\t\t// read data from plugin and write json\n\t\tcase data := <-a.Context.ch:\n\t\t\t{\n\t\t\t\tidsReporting[data.Id] = true\n\n\t\t\t\tif data.Id == hostAliasesPluginID {\n\t\t\t\t\t_ = a.updateIDLookupTable(data.Data)\n\t\t\t\t}\n\n\t\t\t\tentityKey := data.Entity.Key.String()\n\t\t\t\tif _, ok := a.inventories[entityKey]; !ok {\n\t\t\t\t\t_ = a.registerEntityInventory(data.Entity)\n\t\t\t\t}\n\n\t\t\t\tif !data.NotApplicable {\n\t\t\t\t\tif err := a.storePluginOutput(data); err != nil {\n\t\t\t\t\t\talog.WithError(err).Error(\"problem storing plugin output\")\n\t\t\t\t\t}\n\t\t\t\t\ta.inventories[entityKey].needsReaping = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-reapInventoryTimer.C:\n\t\t\t{\n\t\t\t\tfor _, inventory := range a.inventories {\n\t\t\t\t\tif !a.inv.readyToReap {\n\t\t\t\t\t\tif len(distinctPlugins) <= len(idsReporting) {\n\t\t\t\t\t\t\talog.Debug(\"Signalling initial reap.\")\n\t\t\t\t\t\t\ta.inv.readyToReap = true\n\t\t\t\t\t\t\tinventory.needsCleanup = true\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpluginIds := make([]ids.PluginID, 0)\n\t\t\t\t\t\t\tfor plgId := range distinctPlugins {\n\t\t\t\t\t\t\t\tif !idsReporting[plgId] {\n\t\t\t\t\t\t\t\t\tpluginIds = append(pluginIds, plgId)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\talog.WithField(\"pluginIds\", pluginIds).Debug(\"Still waiting on plugins.\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif a.inv.readyToReap && inventory.needsReaping {\n\t\t\t\t\t\treapInventoryTimer.Stop()\n\t\t\t\t\t\treapInventoryTimer = time.NewTicker(cfg.ReapInterval)\n\t\t\t\t\t\tinventory.reaper.Reap()\n\t\t\t\t\t\tif inventory.needsCleanup {\n\t\t\t\t\t\t\tinventory.reaper.CleanupOldPlugins(a.oldPlugins)\n\t\t\t\t\t\t\tinventory.needsCleanup = false\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinventory.needsReaping = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-initialReapTimeout.C:\n\t\t\t// If we've waited too long and still not received data from all plugins, we can just send what we have.\n\t\t\tif !a.inv.readyToReap {\n\t\t\t\talog.Debug(\"Maximum initial reap delay exceeded - marking inventory as ready to report.\")\n\t\t\t\ta.inv.readyToReap = true\n\t\t\t\tfor _, inventory := range a.inventories {\n\t\t\t\t\tinventory.needsCleanup = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-sendInventoryTimer.C:\n\t\t\ta.sendInventory(sendInventoryTimer)\n\t\tcase <-debugTimer:\n\t\t\t{\n\t\t\t\tdebugInfo, err := a.debugProvide()\n\t\t\t\tif err != nil {\n\t\t\t\t\talog.WithError(err).Error(\"debug error\")\n\t\t\t\t} else if debugInfo != \"\" {\n\t\t\t\t\talog.Debug(debugInfo)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-removeEntitiesTicker.C:\n\t\t\tpastPeriodReportedEntities := reportedEntities\n\t\t\treportedEntities = map[string]bool{} // reset the set of reporting entities the next period\n\t\t\talog.Debug(\"Triggered periodic removal of outdated entities.\")\n\t\t\ta.removeOutdatedEntities(pastPeriodReportedEntities)\n\t\t}\n\t}\n}", "func (v *Vegeta) Run() error {\n\tvar metrics vegeta.Metrics\n\tfor res := range v.Attacker.Attack(v.Targeter, v.Rate, v.Duration, v.Name) {\n\t\tmetrics.Add(res)\n\t}\n\tmetrics.Close()\n\n\tlogrus.Infof(\"%+v\", metrics)\n\n\treturn nil\n}", "func RunAgent(problem string, agents comm.ConnList, opts *opt.OptionSet) {\n\tt, err := task.NewTaskFromFile(problem)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\\n\", err)\n\t}\n\tserver, dispatcher := comm.CreateTCPComm(t.AgentID, agents)\n\tengine := search.NewEngine(t, server, dispatcher, agents, opts)\n\tengine.Search(time.Second * time.Duration(opts.GetFloat64(\"timeout\")))\n}", "func (agent *Agent) Run() error {\n\tif agent.NewrelicLicense == \"\" {\n\t\treturn errors.New(\"please, pass a valid newrelic license key\")\n\t}\n\n\tvar component newrelic_platform_go.IComponent\n\tcomponent = newrelic_platform_go.NewPluginComponent(agent.NewrelicName, agent.AgentGUID, agent.Verbose)\n\n\t// Add default metrics and tracer.\n\taddRuntimeMericsToComponent(component)\n\tagent.Tracer = newTracer(component)\n\n\t// Check agent flags and add relevant metrics.\n\tif agent.CollectGcStat {\n\t\taddGCMetricsToComponent(component, agent.GCPollInterval)\n\t\tagent.debug(fmt.Sprintf(\"Init GC metrics collection. Poll interval %d seconds.\", agent.GCPollInterval))\n\t}\n\n\tif agent.CollectMemoryStat {\n\t\taddMemoryMericsToComponent(component, agent.MemoryAllocatorPollInterval)\n\t\tagent.debug(fmt.Sprintf(\"Init memory allocator metrics collection. Poll interval %d seconds.\", agent.MemoryAllocatorPollInterval))\n\t}\n\n\tif agent.CollectHTTPStat {\n\t\tagent.initTimer()\n\t\taddHTTPMericsToComponent(component, agent.HTTPTimer)\n\t\tagent.debug(fmt.Sprintf(\"Init HTTP metrics collection.\"))\n\t}\n\n\tfor _, metric := range agent.CustomMetrics {\n\t\tcomponent.AddMetrica(metric)\n\t\tagent.debug(fmt.Sprintf(\"Init %s metric collection.\", metric.GetName()))\n\t}\n\n\tif agent.CollectHTTPStatuses {\n\t\tagent.initStatusCounters()\n\t\tcomponent = &resettableComponent{component, agent.HTTPStatusCounters}\n\t\taddHTTPStatusMetricsToComponent(component, agent.HTTPStatusCounters)\n\t\tagent.debug(fmt.Sprintf(\"Init HTTP status metrics collection.\"))\n\t}\n\n\t// Init newrelic reporting plugin.\n\tagent.plugin = newrelic_platform_go.NewNewrelicPlugin(agent.AgentVersion, agent.NewrelicLicense, agent.NewrelicPollInterval)\n\tagent.plugin.Client = agent.Client\n\tagent.plugin.Verbose = agent.Verbose\n\n\t// Add our metrics component to the plugin.\n\tagent.plugin.AddComponent(component)\n\n\t// Start reporting!\n\tgo agent.plugin.Run()\n\treturn nil\n}", "func run() {\n\tlog.Info(\"Maison is starting...\")\n\n\tbus.Init()\n\n\t// TODO: init stores\n\n\tinitPlugins()\n\n\tlog.Info(\"Maison is started\")\n}", "func run(ctx context.Context) error {\n\t// Create the control channel on which the hub will push client control notyfications to the game\n\tcontrolCh := make(chan *model.ControlNotify)\n\t// Create the game\n\tgame := game.NewGameController(ctx, time.Millisecond*33, controlCh)\n\t// Create the hub\n\thub := core.NewWsHub(ctx, controlCh)\n\t// Create the server\n\tserver := server.NewServer(ctx)\n\n\t// Pass in callback functions the these objects\n\thub.SetRequestFn(game.Request) // the hub can call the game with arbitary client requests (login)\n\thub.SetLogoutFn(game.Logout) // the hub can call the game with when a conn is dropped, to remove the player\n\tgame.SetBroadcastFn(hub.BroadcastGameUpdate) // the game can call the hub to broadcast state update\n\tgame.SetConnStatusFn(hub.ChangeConnStatus) // the game can call the hub to change a connection's status (ingame)\n\tserver.SetConnectFn(hub.Connect) // the server can call the hub to add a new WebSocket connection (new client)\n\n\t// Start the game and the hub\n\tgame.Start()\n\thub.Start()\n\t// Start the server, return any error\n\treturn server.Start()\n}", "func (s *Session) run() (err error) {\n\terr = s.checkTank()\n\tif err != nil {\n\t\treturn\n\t}\n\tif !s.hasName() {\n\t\terr = s.create()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tresp, err := netClient.Get(fmt.Sprintf(\"%v/run?session=%v\", s.Tank.Url, s.Name))\n\tif err != nil {\n\t\terr = fmt.Errorf(\"http.POST failed: %w\", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t_, err = checkResponseCode(*resp)\n\tif err != nil {\n\t\ts.setFailed([]string{err.Error()})\n\t\treturn\n\t}\n\n\tfailed, failures := s.isFailed()\n\tif failed {\n\t\terr = fmt.Errorf(\"starting session %v@%v failed %v\", s.Name, s.Tank.Url, s.Failures)\n\t\ts.setFailed(failures)\n\t}\n\treturn\n}", "func (tfm *trxFlowMonitor) run() {\n\t// make sure we are orchestrated\n\tif tfm.mgr == nil {\n\t\tpanic(fmt.Errorf(\"no svc manager set on %s\", tfm.name()))\n\t}\n\n\t// start go routine for processing\n\ttfm.mgr.started(tfm)\n\tgo tfm.execute()\n}", "func (a *Actor) run() {\n\tif !a.Path.Equals(a.System.Logger.Path()) && a.System.config.Logging.LogLifecycle {\n\t\ta.System.Logger.Log(a.Path.String(), \"starting\")\n\t}\n\n\tfor {\n\t\tenvelope := a.mailbox.Dequeue() // Blocks until message ready\n\n\t\tif !a.Path.Equals(a.System.Logger.Path()) && a.System.config.Logging.LogReceive {\n\t\t\ta.System.Logger.Logf(\"%s <- %#v\", a.name, envelope)\n\t\t}\n\n\t\tswitch envelope.message.body.(type) {\n\t\tcase StopMessage:\n\t\t\ta.stopping()\n\t\t\treturn\n\t\tdefault:\n\t\t\tif a.receiver != nil {\n\t\t\t\tif envelope.message.sender == nil {\n\t\t\t\t\ta.receiver.Receive(envelope.message.body, a.System.DeadLetters, a)\n\t\t\t\t} else {\n\t\t\t\t\ta.receiver.Receive(envelope.message.body, envelope.message.sender, a)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func run(configFile string) error {\n\tcfg, err := LoadConfig(configFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start remote signer (must start before node if running builtin).\n\tif cfg.PrivValServer != \"\" {\n\t\tif err = startSigner(cfg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif cfg.Protocol == \"builtin\" {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n\n\t// Start app server.\n\tswitch cfg.Protocol {\n\tcase \"socket\", \"grpc\":\n\t\terr = startApp(cfg)\n\tcase \"builtin\":\n\t\tif len(cfg.Misbehaviors) == 0 {\n\t\t\tif cfg.Mode == string(e2e.ModeLight) {\n\t\t\t\terr = startLightClient(cfg)\n\t\t\t} else {\n\t\t\t\terr = startNode(cfg)\n\t\t\t}\n\t\t} else {\n\t\t\terr = startMaverick(cfg)\n\t\t}\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid protocol %q\", cfg.Protocol)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Apparently there's no way to wait for the server, so we just sleep\n\tfor {\n\t\ttime.Sleep(1 * time.Hour)\n\t}\n}", "func Run(cfg *config.EdgeMeshAgentConfig) error {\n\ttrace := 1\n\n\tklog.Infof(\"[%d] New informers manager\", trace)\n\tifm, err := informers.NewManager(cfg.KubeAPIConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttrace++\n\n\tklog.Infof(\"[%d] Prepare agent to run\", trace)\n\tif err = prepareRun(cfg, ifm); err != nil {\n\t\treturn err\n\t}\n\ttrace++\n\n\tklog.Infof(\"[%d] Register beehive modules\", trace)\n\tif errs := registerModules(cfg, ifm); len(errs) > 0 {\n\t\treturn fmt.Errorf(util.SpliceErrors(errs))\n\t}\n\ttrace++\n\n\t// As long as either the proxy module or the gateway module is enabled,\n\t// the go-chassis plugins must also be install.\n\tif cfg.Modules.EdgeProxyConfig.Enable || cfg.Modules.EdgeGatewayConfig.Enable {\n\t\tklog.Infof(\"[%d] Install go-chassis plugins\", trace)\n\t\tchassis.Install(cfg.GoChassisConfig, ifm)\n\t\ttrace++\n\t}\n\n\tklog.Infof(\"[%d] Start informers manager\", trace)\n\tifm.Start(wait.NeverStop)\n\ttrace++\n\n\tklog.Infof(\"[%d] Start all modules\", trace)\n\tcore.Run()\n\n\tklog.Infof(\"edgemesh-agent exited\")\n\treturn nil\n}", "func (checker *Checker) Run() {\n\tgo gohcmd.GracefulStop(checker.cancel)\n\n\tduration, _ := time.ParseDuration(\"15s\")\n\tticker := time.NewTicker(duration)\n\tdefer ticker.Stop()\n\n\tlogrus.Infof(\"Started checker agent\")\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tresponse, err := checker.CheckHealth()\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Error checking health: %v\", err)\n\t\t\t\tchecker.RegisterProblem(err)\n\t\t\t} else {\n\t\t\t\tchecker.RegisterResponse(response)\n\t\t\t}\n\n\t\tcase <-checker.ctx.Done():\n\t\t\tlogrus.Info(\"Health checker agent stopped\")\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (a *actorManager) run() error {\n\t// Continually receive messages\n\tfor {\n\t\t// Get next message\n\t\tvar msg actorMessage\n\t\tif err := a.firefox.remote.recv(&msg); err != nil {\n\t\t\tif a.firefox.runCtx.Err() != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\ta.actorsLock.RLock()\n\t\tactor := a.actors[msg.From]\n\t\ta.actorsLock.RUnlock()\n\t\tif actor != nil {\n\t\t\tactor.onMessage(&msg)\n\t\t}\n\t}\n}", "func (m *Manager) Run() {\n\totel.SetTextMapPropagator(propagation.TraceContext{})\n\totel.SetErrorHandler(otelErrHandler(func(err error) {\n\t\tlevel.Error(m.logger).Log(\"msg\", \"OpenTelemetry handler returned an error\", \"err\", err)\n\t}))\n\t<-m.done\n}", "func (e *Engine) Run(ctx context.Context) error {\n\t// load container\n\tif err := e.load(); err != nil {\n\t\treturn err\n\t}\n\t// start status watcher\n\teventChan, errChan := e.initMonitor()\n\tgo e.monitor(eventChan)\n\n\t// start health check\n\tgo e.healthCheck(ctx)\n\n\t// start node heartbeat\n\tgo e.heartbeat(ctx)\n\n\tlog.Info(\"[Engine] Node activated\")\n\n\t// wait for signal\n\tselect {\n\tcase <-ctx.Done():\n\t\tlog.Info(\"[Engine] Agent caught system signal, exiting\")\n\t\treturn nil\n\tcase err := <-errChan:\n\t\tif err := e.crash(); err != nil {\n\t\t\tlog.Infof(\"[Engine] Mark node crash failed %v\", err)\n\t\t}\n\t\treturn err\n\t}\n}", "func (a *MockAgent) Run() {\n\tfor {\n\t\t<-a.Input // consume message to unblock Sender\n\t}\n}", "func (this *Connection) run() {\n\tgo this.routineMain()\n}", "func (ftm *FtmBridge) run() {\n\tftm.wg.Add(1)\n\tgo ftm.observeBlocks()\n}", "func (i *instanceManager) run() {\n\t// Dispense once to ensure we are given a valid plugin\n\tif _, err := i.dispense(); err != nil {\n\t\ti.logger.Error(\"dispensing initial plugin failed\", \"error\", err)\n\t\treturn\n\t}\n\n\t// Create a waitgroup to block on shutdown for all created goroutines to\n\t// exit\n\tvar wg sync.WaitGroup\n\n\t// Start the fingerprinter\n\twg.Add(1)\n\tgo func() {\n\t\ti.fingerprint()\n\t\twg.Done()\n\t}()\n\n\t// Start event handler\n\twg.Add(1)\n\tgo func() {\n\t\ti.handleEvents()\n\t\twg.Done()\n\t}()\n\n\t// Do a final cleanup\n\twg.Wait()\n\ti.cleanup()\n}", "func (a *API) Run() error {\n\treturn a.e.Start(a.addr)\n}", "func (r *Raft) run() {\n\tfor {\n\t\t// Check if we are doing a shutdown\n\t\tselect {\n\t\tcase <-r.shutdownCh:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\t// Enter into a sub-FSM\n\t\tswitch r.getState() {\n\t\tcase Follower:\n\t\t\tr.runFollower()\n\t\tcase Candidate:\n\t\t\tr.runCandidate()\n\t\tcase Leader:\n\t\t\tr.runLeader()\n\t\t}\n\t}\n}", "func run(instance apply.Strategy, recorded, local, remote, expected map[string]interface{}) {\n\trunWith(instance, recorded, local, remote, expected, fakeResources)\n}", "func (pr *PolicyReflector) run() {\n\tdefer pr.wg.Done()\n\n\tpr.Log.Info(\"Policy reflector is now running\")\n\tpr.k8sPolicyController.Run(pr.stopCh)\n\tpr.Log.Info(\"Stopping Policy reflector\")\n}", "func run() int {\n\tconst cfgNamespace = \"arachne\"\n\tconst defaultAddress = \":10000\"\n\tvar address string\n\tvar err error\n\tvar exitCode int\n\tvar c client.Client\n\tvar lg client.LocalGame\n\n\terr = cfg.Init(cfg.EnvProvider{Namespace: cfgNamespace})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif address, err = cfg.String(\"ADDRESS\"); err != nil {\n\t\taddress = defaultAddress\n\t}\n\n\tc, err = client.New(address)\n\tif err != nil {\n\t\tfmt.Printf(\"unable to create client: %v\\n\", err)\n\t\treturn -1\n\t}\n\n\tfmt.Println(\"arachne starts\")\n\tfmt.Println(\"\")\n\tif lg, err = c.NewGame(); err != nil {\n\t\tfmt.Printf(\"NewGame failed: %v\\n\", err)\n\t\treturn -1\n\t}\n\n\torderer := gamelib.NewHighestMove()\n\n\tif err = displayGameData(lg, orderer); err != nil {\n\t\tfmt.Printf(\"displayGameData failed: %v\\n\", err)\n\t\treturn -1\n\t}\n\n\tfmt.Println(\"\")\n\tfmt.Print(\">\")\n\n\tscanner := bufio.NewScanner(os.Stdin)\nRUN_LOOP:\n\tfor scanner.Scan() {\n\n\t\trawLine := scanner.Text()\n\t\tsplitLine := strings.SplitN(rawLine, \" \", 2)\n\t\tif len(splitLine) == 0 {\n\t\t\tfmt.Println(\"unparsable command\")\n\t\t\tcontinue RUN_LOOP\n\t\t}\n\t\tswitch splitLine[0] {\n\t\tcase \"new\":\n\t\t\tfmt.Println(\"starting new random game\")\n\t\t\tif lg, err = c.NewGame(); err != nil {\n\t\t\t\tfmt.Printf(\"NewGame failed: %v\\n\", err)\n\t\t\t\tbreak RUN_LOOP\n\t\t\t}\n\t\t\tif err = displayGameData(lg, orderer); err != nil {\n\t\t\t\tfmt.Printf(\"displayGameData failed: %v\\n\", err)\n\t\t\t\tbreak RUN_LOOP\n\t\t\t}\n\t\tcase \"replay\":\n\t\t\tif len(splitLine) < 2 {\n\t\t\t\tfmt.Println(\"no seed value given for replay\")\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tseed, err := strconv.ParseInt(splitLine[1], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Unable to parse seed '%s'\\n\", splitLine[1])\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tfmt.Println(\"replaying game from seed %d\", seed)\n\t\t\tif lg, err = c.ReplayGame(seed); err != nil {\n\t\t\t\tfmt.Printf(\"ReplayGame(%d) failed: %v\\n\", seed, err)\n\t\t\t\tbreak RUN_LOOP\n\t\t\t}\n\t\tcase \"display\":\n\t\t\tdisplayTableauStrings(lg.Tableau)\n\t\tcase \"scan\":\n\t\t\tif err = displayMoves(lg.Tableau, orderer); err != nil {\n\t\t\t\tfmt.Printf(\"Unable to display tableau: %s\\n\", err)\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\tcase \"move\":\n\t\t\tvar move gamelib.MoveType\n\t\t\tif move, err = parseMoveComand(splitLine); err != nil {\n\t\t\t\tfmt.Printf(\"unparseable move command: %s\\n\", err)\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tif lg, err = c.Move(move); err != nil {\n\t\t\t\tfmt.Printf(\"move failed: %s\\n\", err)\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tif err = displayGameData(lg, orderer); err != nil {\n\t\t\t\tfmt.Printf(\"displayGameData failed: %v\\n\", err)\n\t\t\t\tbreak RUN_LOOP\n\t\t\t}\n\t\tcase \"deal\":\n\t\t\tif lg.CardsRemaining == 0 {\n\t\t\t\tfmt.Println(\"no cards available to deal\")\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tif lg.Tableau.EmptyStack() {\n\t\t\t\tfmt.Println(\"cannot deal over empty stack\")\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tif lg, err = c.Deal(); err != nil {\n\t\t\t\tfmt.Printf(\"deal failed: %v\\n\", err)\n\t\t\t\tcontinue RUN_LOOP\n\t\t\t}\n\t\t\tif err = displayGameData(lg, orderer); err != nil {\n\t\t\t\tfmt.Printf(\"displayGameData failed: %v\\n\", err)\n\t\t\t\tbreak RUN_LOOP\n\t\t\t}\n\t\tcase \"quit\":\n\t\t\tfmt.Println(\"quitting\")\n\t\t\tif err := c.Close(); err != nil {\n\t\t\t\tfmt.Printf(\"Close failed: %v\\n\", err)\n\t\t\t}\n\t\t\tbreak RUN_LOOP\n\n\t\tdefault:\n\t\t\tfmt.Println(\"unknown command\")\n\t\t}\n\t\tfmt.Println(\"\")\n\t\tfmt.Printf(\">\")\n\t}\n\tlog.Printf(\"info: end\")\n\n\treturn exitCode\n}", "func (e *executor) run(timeout time.Duration, opts opts, path string, args ...string) error {\n\t_, err := e.execute(true, timeout, opts, path, args...)\n\treturn err\n}", "func (h *Hub) run(ctx context.Context) {\n\t// Unsubscribe when finished.\n\tdefer func() {\n\t\terr := h.unsubscribeOnNATSSubects()\n\t\tif err != nil {\n\t\t\th.logger.Warningf(\"could not unsubscribe on NATS server: %w\", err)\n\t\t}\n\t}()\n\n\t// Start event handling loop.\n\th.logger.Infof(\"started NATS event receiver loop\")\n\tdefer h.logger.Infof(\"stopped NATS event receiver loop\")\n\n\tfor {\n\t\tloopCtx := context.Background()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\th.logger.Infof(\"stopping NATS hub by context done\")\n\n\t\tcase msg := <-h.diceRollCreatedChan:\n\t\t\th.logger.Debugf(\"diceRollCreated NATS event received, broadcasting\")\n\t\t\terr := h.handleDiceRollCreatedEvent(loopCtx, msg.Data)\n\t\t\tif err != nil {\n\t\t\t\th.logger.Errorf(\"could not handle diceRollCreated event: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (cmd *command) run(c *kingpin.ParseContext) error {\n\tfmt.Fprintln(os.Stderr, \"Intializing Acquia client\")\n\n\ta, err := auth.New(cmd.Key, cmd.Secret)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed creating authentication client: %w\", err)\n\t}\n\n\tfmt.Fprintln(os.Stderr, \"Triggering a code switch\")\n\n\t_, err = environment.CodeSwitch(a, cmd.Environment, cmd.Branch)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintln(os.Stderr, \"Code switch submitted\")\n\n\treturn nil\n}", "func (c *listCommand) Run(ctx context.Context, _ *commoncli.Env, serverClient util.ServerClient) error {\n\tfilter := &agentv1.ListAgentsRequest_Filter{}\n\tif len(c.selectors) > 0 {\n\t\tmatchBehavior, err := parseToSelectorMatch(c.matchSelectorsOn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tselectors := make([]*types.Selector, len(c.selectors))\n\t\tfor i, sel := range c.selectors {\n\t\t\tselector, err := util.ParseSelector(sel)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error parsing selector %q: %w\", sel, err)\n\t\t\t}\n\t\t\tselectors[i] = selector\n\t\t}\n\t\tfilter.BySelectorMatch = &types.SelectorMatch{\n\t\t\tSelectors: selectors,\n\t\t\tMatch: matchBehavior,\n\t\t}\n\t}\n\n\tagentClient := serverClient.NewAgentClient()\n\n\tpageToken := \"\"\n\tresponse := new(agentv1.ListAgentsResponse)\n\tfor {\n\t\tlistResponse, err := agentClient.ListAgents(ctx, &agentv1.ListAgentsRequest{\n\t\t\tPageSize: 1000, // comfortably under the (4 MB/theoretical maximum size of 1 agent in MB)\n\t\t\tPageToken: pageToken,\n\t\t\tFilter: filter,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresponse.Agents = append(response.Agents, listResponse.Agents...)\n\t\tif pageToken = listResponse.NextPageToken; pageToken == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn c.printer.PrintProto(response)\n}", "func (t *ManagePatient) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n fmt.Println(\"run is running \" + function)\n return t.Invoke(stub, function, args)\n }", "func run() error {\n\tport := os.Getenv(\"PORT\")\n\tdbURI := os.Getenv(\"DATABASE_URI\")\n\n\t// conn -> repo\n\tr, err := NewRepo(dbURI)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer r.Close()\n\n\t// repo -> service\n\tservice := NewService(r)\n\n\treadTimeoutSecondsCount, _ := strconv.Atoi(os.Getenv(\"SERVER_READ_TIMEOUT\"))\n\t// fiber initialize\n\tapp := fiber.New(fiber.Config{\n\t\tReadTimeout: time.Second * time.Duration(readTimeoutSecondsCount),\n\t})\n\n\tif !IsProduction() {\n\t\tapp.Use(logger.New())\n\t\tapp.Use(cors.New())\n\t}\n\n\t// service -> routes\n\tRoutes(app, service)\n\treturn app.Listen(fmt.Sprintf(\":%s\", port))\n}", "func (a *Agent) Run(shutdown chan struct{}) error {\n\tvar wg sync.WaitGroup\n\n\tlog.Printf(\"INFO Agent Config: Interval:%s, Hostname:%#v, Flush Interval:%s \\n\",\n\t\ta.Config.Agent.Interval, a.Config.Agent.Hostname, a.Config.Agent.FlushInterval)\n\n\t// configure all sources\n\tfor _, source := range a.Config.Sources {\n\t\tsource.SetDefaultTags(a.Config.Tags)\n\t}\n\n\t// Start all ServiceSources\n\tfor _, source := range a.Config.Sources {\n\t\tswitch p := source.Source.(type) {\n\t\tcase optic.ServiceSource:\n\t\t\tacc := NewAccumulator(source, source.EventsCh())\n\t\t\tif err := p.Start(acc); err != nil {\n\t\t\t\tlog.Printf(\"ERROR Service for source %s failed to start, exiting\\n%s\\n\",\n\t\t\t\t\tsource.Name(), err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer p.Stop()\n\t\t}\n\t}\n\n\twg.Add(len(a.Config.Sources))\n\tfor _, source := range a.Config.Sources {\n\t\tinterval := a.Config.Agent.Interval\n\t\t// overwrite global interval if this plugin has it's own\n\t\tif source.Config.Interval != 0 {\n\t\t\tinterval = source.Config.Interval\n\t\t}\n\t\tgo func(source *models.RunningSource, interval time.Duration) {\n\t\t\tdefer wg.Done()\n\t\t\ta.gatherer(shutdown, source, interval)\n\t\t}(source, interval)\n\t}\n\n\twg.Wait()\n\ta.Close()\n\treturn nil\n}", "func (p *Probe) runProbe() {\n\t// Resolve targets if target resolve interval has elapsed.\n\tif (p.runCnt % uint64(p.c.GetResolveTargetsInterval())) == 0 {\n\t\tp.targets = p.opts.Targets.List()\n\t\tp.resolveTargets()\n\t}\n\tp.runCnt++\n\trunID := p.newRunID()\n\twg := new(sync.WaitGroup)\n\ttracker := make(chan bool, int(p.c.GetPacketsPerProbe())*len(p.targets))\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tp.recvPackets(runID, tracker)\n\t}()\n\tp.sendPackets(runID, tracker)\n\twg.Wait()\n}", "func (e *Election) Run(ctx context.Context) {\n\te.campaign(ctx)\n}", "func (a *Agent) Run() error {\n\tuserCredentials := fmt.Sprintf(\"%s:%s\", a.config.User, a.config.Password)\n\tuserCredentials = base64.StdEncoding.EncodeToString([]byte(userCredentials))\n\theader := a.buildTransportHeaderMap()\n\theader.Set(\"Authorization\", \"Basic \"+userCredentials)\n\n\tconn, err := transport.Connect(a.backendSelector.Select(), a.config.TLS, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.conn = conn\n\n\tif _, _, err := a.createListenSockets(); err != nil {\n\t\treturn err\n\t}\n\n\t// These are in separate goroutines so that they can, theoretically, be executing\n\t// concurrently.\n\tgo a.sendPump(conn)\n\tgo a.receivePump(conn)\n\n\t// Send an immediate keepalive once we've connected.\n\tif err := a.sendKeepalive(); err != nil {\n\t\tlogger.Error(err)\n\t}\n\n\tgo func() {\n\t\tkeepaliveTicker := time.NewTicker(time.Duration(a.config.KeepaliveInterval) * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-keepaliveTicker.C:\n\t\t\t\tif err := a.sendKeepalive(); err != nil {\n\t\t\t\t\tlogger.WithError(err).Error(\"failed sending keepalive\")\n\t\t\t\t}\n\t\t\tcase <-a.stopping:\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n\n\t// Prepare the HTTP API server\n\ta.api = newServer(a)\n\n\t// Start the HTTP API server\n\tgo func() {\n\t\tlogger.Info(\"starting api on address: \", a.api.Addr)\n\n\t\tif err := a.api.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\tlogger.Fatal(err)\n\t\t}\n\t}()\n\n\t// Allow Stop() to block until the HTTP server shuts down.\n\ta.wg.Add(1)\n\tgo func() {\n\t\t// NOTE: This does not guarantee a clean shutdown of the HTTP API.\n\t\t// This is _only_ for the purpose of making Stop() a blocking call.\n\t\t// The goroutine running the HTTP Server has to return before Stop()\n\t\t// can return, so we use this to signal that goroutine to shutdown.\n\t\t<-a.stopping\n\t\tlogger.Info(\"api shutting down\")\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\t\tdefer cancel()\n\n\t\tif err := a.api.Shutdown(ctx); err != nil {\n\t\t\tlogger.Error(err)\n\t\t}\n\t\ta.wg.Done()\n\t}()\n\n\treturn nil\n}", "func run(t targeter, tmuxCmd string, args ...string) (string, error) {\n\targs = append([]string{\"-t\", t.Target()}, args...)\n\treturn Run(tmuxCmd, args...)\n}", "func (c *LoadAgentCluster) Run() error {\n\tfor _, agent := range c.agents {\n\t\tif _, err := agent.Run(); err != nil {\n\t\t\treturn fmt.Errorf(\"cluster: failed to start agent: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func run(name string, arg ...string) error {\n\treturn runInDir(\".\", name, arg...)\n}", "func (n *Ncd) Run() {\n\tn._start()\n}", "func (s actionStep) run(ctx context.Context, logger logr.Logger) (bool, error) {\n\treturn s.f(ctx, logger)\n}", "func main() {\n args := args.Parse(os.Args)\n fmt.Println(\"[MAIN] App starting\")\n\n switch args.Mode {\n case \"agent\":\n go agent.Run(args.Source, args.ServerAddress, args.ServerPort)\n case \"server\":\n go server.Run(args.BindAddress, args.BindPort)\n case \"mixed\":\n go server.Run(args.BindAddress, args.BindPort)\n go agent.Run(args.Source, args.ServerAddress, args.ServerPort)\n default:\n fmt.Println(\"[MAIN] No agent, no server running\")\n }\n\n for {\n time.Sleep(100 * time.Millisecond)\n }\n}", "func (oe *OVFExporter) run(ctx context.Context) error {\n\toe.Logger.User(\"Starting OVF export.\")\n\tif oe.params.Timeout.Nanoseconds() > 0 {\n\t\tvar cancel func()\n\t\tctx, cancel = context.WithTimeout(ctx, oe.params.Timeout)\n\t\tdefer cancel()\n\t}\n\n\t//TODO: if machine image export, create instance from machine image and add it to cleanup\n\n\tinstance, err := oe.computeClient.GetInstance(oe.params.Project, oe.params.Zone, oe.params.InstanceName)\n\tif err != nil {\n\t\treturn daisy.Errf(\"Error retrieving instance `%v`: %v\", oe.params.InstanceName, err)\n\t}\n\tdefer func() {\n\t\toe.cleanup(instance, err)\n\t}()\n\tif err = oe.prepare(ctx, instance); err != nil {\n\t\treturn err\n\t}\n\tif err := oe.exportDisks(ctx, instance); err != nil {\n\t\treturn err\n\t}\n\tif err := oe.inspectBootDisk(ctx); err != nil {\n\t\treturn err\n\t}\n\tif err = oe.generateDescriptor(ctx, instance); err != nil {\n\t\treturn err\n\t}\n\tif err = oe.generateManifest(ctx); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (h *healthcheckManager) run() {\n\tfor {\n\t\tselect {\n\t\tcase <-h.quit:\n\t\t\th.unmarkAllBackends()\n\t\t\th.stopped <- true\n\t\tcase vc := <-h.vcc:\n\t\t\th.update(vc.vserverName, vc.checks)\n\t\t}\n\t}\n}", "func run(cli client.Client, request model.PostPipelineRequest, variables model.PipelineVariables, securedVariables model.PipelineVariables) (err error) {\n\tif len(variables) > 0 {\n\t\tvars := append(*request.Variables, variables...)\n\t\trequest.Variables = &vars\n\t}\n\n\tif len(securedVariables) > 0 {\n\t\tsecVars := append(*request.Variables, securedVariables...)\n\t\trequest.Variables = &secVars\n\t}\n\n\t// Use a builder to help override the target using args\n\ttargetBuilder := builders.Target()\n\ttargetBuilder.PipelineTarget = *request.Target\n\n\tif targetPipeline != \"\" {\n\t\ttargetBuilder.Pattern(targetPipeline)\n\t}\n\n\tif targetType != \"\" {\n\t\ttargetBuilder.RefType = targetType\n\t}\n\n\tif targetName != \"\" {\n\t\ttargetBuilder.RefName = targetName\n\t}\n\n\ttarget := targetBuilder.Build()\n\trequest.Target = &target\n\n\tfmt.Println(\"============================================================\")\n\tfmt.Printf(\"running %s/%s\\n\", *request.Workspace, *request.Repository)\n\tlogs, err := DoRun(cli, request, dryRun)\n\tprintStepLogs(logs)\n\treturn err\n}", "func (r *Runner) Run(ctx context.Context) error {\n\treturn errors.New(\"not implemented\")\n}", "func Run() {\n\trun()\n}", "func run(cfg config) {\n\tlog.SetFlags(0)\n\n\tcmds := []acmd.Command{\n\t\t{\n\t\t\tName: \"check\",\n\t\t\tDescription: \"run linter over specified targets\",\n\t\t\tExecFunc: runCheck,\n\t\t},\n\t\t{\n\t\t\tName: \"doc\",\n\t\t\tDescription: \"get installed checkers documentation\",\n\t\t\tExecFunc: runDocs,\n\t\t},\n\t}\n\n\tr := acmd.RunnerOf(cmds, acmd.Config{\n\t\tAppName: cfg.Name,\n\t\tVersion: cfg.Version,\n\t})\n\tif err := r.Run(); err != nil {\n\t\tlog.Print(err.Error())\n\t}\n}", "func (b *Work) Run() {\n\t// append hey's user agent\n\tua := b.Request.UserAgent()\n\tif ua == \"\" {\n\t\tua = megSenderUA\n\t} else {\n\t\tua += \" \" + megSenderUA\n\t}\n\n\tb.results = make(chan *result)\n\tb.stopCh = make(chan struct{}, b.C)\n\tb.startTime = time.Now()\n\tb.report = newReport(b.writer(), b.results, b.Output)\n\tb.report.start()\n\n\tb.runWorkers()\n\tb.Finish()\n}", "func (c *connection) run(msg Message) error {\n\tchannel, requests, err := c.ssh.OpenChannel(\"session\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession := &session{\n\t\tconnection: c,\n\t\tchannel: channel,\n\t\trequests: requests,\n\t\texit: make(chan status),\n\t}\n\tgo session.serviceRequests()\n\n\tif err = session.start(string(msg.payload)); err != nil {\n\t\treturn err\n\t}\n\n\treaper := make(chan int)\n\tc.reapers = append(c.reapers, reaper)\n\n\tsession.finish(msg.responses, reaper)\n\treturn nil\n}", "func (ta *TestApp) run() {\n\tlog.Info(\">>> child >>> test application started\")\n\tif *maxUptime != 0 {\n\t\tlog.Infof(\">>> child >>> max uptime set to %d second(s)\", *maxUptime)\n\t}\n\n\tticker := time.NewTicker(1 * time.Second)\n\tvar uptime uint\n\n\tfunc() {\n\t\tfor range ticker.C {\n\t\t\tuptime++\n\t\t\tif uptime == *maxUptime {\n\t\t\t\tlog.Info(\">>> child >>> time's up, bye\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tlog.Info(\">>> child >>> test application ended\")\n\treturn\n}", "func (mc *MonitorCore) run(runtimeConf RuntimeConfig, stdin io.Reader, stdout io.Writer) error {\n\tmc.logger.Info(\"Starting Python runner child process\")\n\n\tcmd := exec.CommandContext(mc.ctx, runtimeConf.PythonBinary, runtimeConf.PythonArgs...)\n\tcmd.SysProcAttr = procAttrs()\n\tcmd.Stdin = stdin\n\tcmd.Stdout = stdout\n\tcmd.Env = runtimeConf.PythonEnv\n\n\t// Stderr is just the normal output from the Python code that isn't\n\t// specially encoded\n\tstderr, err := cmd.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tmc.logger = mc.logger.WithFields(log.Fields{\n\t\t\"runnerPID\": cmd.Process.Pid,\n\t})\n\n\tgo func() {\n\t\tscanner := utils.ChunkScanner(stderr)\n\t\tfor scanner.Scan() {\n\t\t\tmc.logger.Error(scanner.Text())\n\t\t}\n\t}()\n\n\tif err := cmd.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (m *M) Run() int", "func (o *Orchestrator) Run() {\n\tv := newValidator(o.Plugin)\n\tm := newMetrics(o.healthzPath, o.healthzPort, o.metricsPath, o.metricsPort)\n\n\tv.mustValidatePrerequisites()\n\n\to.mustServeKMSRequests()\n\n\t// Giving some time for kmsPlugin to start Serving.\n\t// TODO: Must be a better way than to sleep.\n\ttime.Sleep(3 * time.Millisecond)\n\n\tv.mustPingRPC()\n\tmustGatherMetrics()\n\n\tm.mustServeHealthzAndMetrics()\n\n\t// Giving some time for HealthZ and Metrics to start Serving.\n\t// TODO: Must be a better way than to sleep.\n\ttime.Sleep(3 * time.Millisecond)\n\tmustEmitOKHealthz()\n\tmustEmitMetrics()\n}", "func (c *Controller) Run(ctx context.Context) error {\n\t// Start the informer factories to begin populating the informer caches\n\tc.log.Infof(\"starting step control loop, node name: %s\", c.nodeName)\n\n\t// 初始化runner\n\tc.log.Info(\"init controller engine\")\n\tif err := engine.Init(c.wc, c.informer.Recorder()); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.sync(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tc.waitDown(ctx)\n\treturn nil\n}", "func (s *Service) Run(ctx context.Context) error {\n\tdefer s.avRegistry.Close()\n\n\t// Start the registry update loop\n\tagentRegistered := make(chan struct{})\n\tgo s.runUpdateAgentRegistration(ctx, agentRegistered)\n\n\t// Wait until agent is first registered\n\tselect {\n\tcase <-agentRegistered:\n\t\t// Agent was register. Good to start\n\tcase <-ctx.Done():\n\t\t// Context was canceled\n\t\treturn maskAny(ctx.Err())\n\t}\n\n\t// Serve API\n\taddr := fmt.Sprintf(\"0.0.0.0:%d\", s.port)\n\tlis, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\ts.log.Error().Err(err).Msg(\"Failed to listen\")\n\t\treturn maskAny(err)\n\t}\n\tsvr := grpc.NewServer()\n\tdefer svr.GracefulStop()\n\tannotatedvalue.RegisterAnnotatedValuePublisherServer(svr, s.avPublisher)\n\tannotatedvalue.RegisterAnnotatedValueSourceServer(svr, s.avSource)\n\t// Register reflection service on gRPC server.\n\treflection.Register(svr)\n\tg, lctx := errgroup.WithContext(ctx)\n\tg.Go(func() error {\n\t\tif err := svr.Serve(lis); err != nil {\n\t\t\ts.log.Fatal().Err(err).Msg(\"Failed to service\")\n\t\t}\n\t\treturn nil\n\t})\n\tg.Go(func() error {\n\t\tif err := s.avPublisher.Run(lctx); err != nil {\n\t\t\treturn maskAny(err)\n\t\t}\n\t\treturn nil\n\t})\n\tg.Go(func() error {\n\t\tif err := s.avSource.Run(lctx); err != nil {\n\t\t\treturn maskAny(err)\n\t\t}\n\t\treturn nil\n\t})\n\ts.log.Info().Msgf(\"Started link %s, listening on %s\", s.linkName, addr)\n\n\t// Wait until context closed\n\tif err := g.Wait(); err != nil {\n\t\treturn maskAny(err)\n\t}\n\treturn nil\n}", "func (o *options) run(cmd *cobra.Command) error {\n\t// FIXME: Support multiple leader election config maps.\n\tcmName := \"datadog-leader-election\"\n\n\t// Get the config map holding the leader identity.\n\tcm := &corev1.ConfigMap{}\n\terr := o.Client.Get(context.TODO(), client.ObjectKey{Namespace: o.UserNamespace, Name: cmName}, cm)\n\tif err != nil && apierrors.IsNotFound(err) {\n\t\treturn fmt.Errorf(\"config map %s/%s not found\", o.UserNamespace, cmName)\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"unable to get leader election config map: %w\", err)\n\t}\n\n\t// Get leader from annotations.\n\tannotations := cm.GetAnnotations()\n\tleaderInfo, found := annotations[\"control-plane.alpha.kubernetes.io/leader\"]\n\tif !found {\n\t\treturn fmt.Errorf(\"couldn't find leader annotation on %s config map\", cmName)\n\t}\n\tleader := leaderResponse{}\n\tif err := json.Unmarshal([]byte(leaderInfo), &leader); err != nil {\n\t\treturn fmt.Errorf(\"couldn't unmarshal leader annotation: %w\", err)\n\t}\n\tcmd.Println(\"The Pod name of the Cluster Agent is:\", leader.HolderIdentity)\n\n\treturn nil\n}", "func run() {\n\n\tvar amdata amData\n\tget(&amdata)\n\tmergeData(amdata)\n\tsortAlert()\n\tfilter()\n\n\tif *jsonOutput {\n\t\tif name != \"\" {\n\t\t\tjsonPrintDetails()\n\t\t} else {\n\t\t\tjsonPrint()\n\t\t}\n\t} else {\n\t\tif name != \"\" {\n\t\t\tdetailPrint()\n\t\t} else {\n\t\t\ttabulate()\n\t\t}\n\t}\n}", "func (s *SendEventToMeshAndCheckEventId) Run() error {\n\teventId := uuid.New().String()\n\n\terr := s.sendEventToMesh(eventId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = s.checkEventId(eventId)\n\tif err != nil {\n\t\treturn errors.Wrap(err, s.testService.DumpAllReceivedEvents().Error())\n\t}\n\n\treturn nil\n}", "func (nm *NodeMonitor) run(sockPath, bpfRoot string) error {\n\tos.Remove(sockPath)\n\tif err := syscall.Mkfifo(sockPath, 0600); err != nil {\n\t\treturn fmt.Errorf(\"Unable to create named pipe %s: %s\", sockPath, err)\n\t}\n\n\tdefer os.Remove(sockPath)\n\n\tpipe, err := os.OpenFile(sockPath, os.O_RDWR, 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to open named pipe for writing: %s\", err)\n\t}\n\n\tdefer pipe.Close()\n\n\tnm.pipeLock.Lock()\n\tnm.pipe = pipe\n\tnm.pipeLock.Unlock()\n\n\tnm.Launcher.SetArgs([]string{\"--bpf-root\", bpfRoot})\n\tif err := nm.Launcher.Run(); err != nil {\n\t\treturn err\n\t}\n\tmetrics.SubprocessStart.WithLabelValues(targetName).Inc()\n\n\tr := bufio.NewReader(nm.GetStdout())\n\tfor nm.GetProcess() != nil {\n\t\tl, err := r.ReadBytes('\\n') // this is a blocking read\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to read stdout from monitor: %s\", err)\n\t\t}\n\n\t\tvar tmp *models.MonitorStatus\n\t\tif err := json.Unmarshal(l, &tmp); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to unmarshal stdout from monitor: %s\", err)\n\t\t}\n\n\t\tnm.setState(tmp)\n\t}\n\n\treturn fmt.Errorf(\"Monitor process quit unexepctedly\")\n}", "func (n *NodeDrainer) run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase <-n.ctx.Done():\n\t\t\treturn\n\t\tcase nodes := <-n.deadlineNotifier.NextBatch():\n\t\t\tn.handleDeadlinedNodes(nodes)\n\t\tcase req := <-n.jobWatcher.Drain():\n\t\t\tn.handleJobAllocDrain(req)\n\t\tcase allocs := <-n.jobWatcher.Migrated():\n\t\t\tn.handleMigratedAllocs(allocs)\n\t\t}\n\t}\n}", "func run() <-chan struct{} {\n\t// Start the brain loop\n\tgo runBrain()\n\n\tbot := &botContext{\n\t\tenvironment: make(map[string]string),\n\t}\n\tbot.registerActive()\n\tbot.loadConfig(false)\n\tbot.deregister()\n\n\tvar cl []string\n\trobot.RLock()\n\tcl = append(cl, robot.joinChannels...)\n\trobot.RUnlock()\n\tfor _, channel := range cl {\n\t\trobot.JoinChannel(channel)\n\t}\n\n\t// signal handler\n\tgo func() {\n\t\trobot.RLock()\n\t\tdone := robot.done\n\t\trobot.RUnlock()\n\t\tsigs := make(chan os.Signal, 1)\n\n\t\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\tloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase sig := <-sigs:\n\t\t\t\trobot.Lock()\n\t\t\t\tif robot.shuttingDown {\n\t\t\t\t\tLog(Warn, \"Received SIGINT/SIGTERM while shutdown in progress\")\n\t\t\t\t\trobot.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\trobot.shuttingDown = true\n\t\t\t\t\trobot.Unlock()\n\t\t\t\t\tsignal.Stop(sigs)\n\t\t\t\t\tLog(Info, fmt.Sprintf(\"Exiting on signal: %s\", sig))\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\tcase <-done:\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t}()\n\n\t// connector loop\n\trobot.RLock()\n\tgo func(conn Connector, stop <-chan struct{}, done chan<- struct{}) {\n\t\tconn.Run(stop)\n\t\tclose(done)\n\t}(robot.Connector, robot.stop, robot.done)\n\trobot.RUnlock()\n\n\tinitializePlugins()\n\trobot.RLock()\n\tdefer robot.RUnlock()\n\treturn robot.done\n}", "func (m *Manager) Run() {\n\tgo func() {\n\t\tif err := m.Start(context.Background()); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}", "func (vm *VM) Run() error {\n\treturn vm.core(0)\n}", "func (p *Probe) run() {\n\tstart := p.recordStart()\n\tdefer func() {\n\t\t// Prevent a panic within one probe function from killing the\n\t\t// entire prober, so that a single buggy probe doesn't destroy\n\t\t// our entire ability to monitor anything. A panic is recorded\n\t\t// as a probe failure, so panicking probes will trigger an\n\t\t// alert for debugging.\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Printf(\"probe %s panicked: %v\", p.name, r)\n\t\t\tp.recordEnd(start, errors.New(\"panic\"))\n\t\t}\n\t}()\n\ttimeout := time.Duration(float64(p.interval) * 0.8)\n\tctx, cancel := context.WithTimeout(p.ctx, timeout)\n\tdefer cancel()\n\n\terr := p.doProbe(ctx)\n\tp.recordEnd(start, err)\n\tif err != nil {\n\t\tlog.Printf(\"probe %s: %v\", p.name, err)\n\t}\n}", "func run() error {\n\tif err := ShowInfo(Hello); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ShowInfo(func(\n\t\tw io.Writer,\n\t\tname string,\n\t) error {\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := ShowInfo(new(P).Hello); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *VMTServer) Run(_ []string) error {\n\tif err := s.checkFlag(); err != nil {\n\t\tglog.Errorf(\"check flag failed:%v. abort.\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tglog.V(3).Infof(\"spec path is: %v\", s.K8sTAPSpec)\n\tk8sTAPSpec, err := kubeturbo.ParseK8sTAPServiceSpec(s.K8sTAPSpec)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to generate correct TAP config: %v\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tkubeConfig := s.createKubeConfigOrDie()\n\tkubeClient := s.createKubeClientOrDie(kubeConfig)\n\tkubeletClient := s.createKubeletClientOrDie(kubeConfig)\n\tprobeConfig := s.createProbeConfigOrDie(kubeConfig, kubeletClient)\n\tbroker := turbostore.NewPodBroker()\n\n\tvmtConfig := kubeturbo.NewVMTConfig2()\n\tvmtConfig.WithTapSpec(k8sTAPSpec).\n\t\tWithKubeClient(kubeClient).\n\t\tWithKubeletClient(kubeletClient).\n\t\tWithProbeConfig(probeConfig).\n\t\tWithBroker(broker).\n\t\tWithK8sVersion(s.K8sVersion).\n\t\tWithNoneScheduler(s.NoneSchedulerName).\n\t\tWithRecorder(createRecorder(kubeClient))\n\tglog.V(3).Infof(\"Finished creating turbo configuration: %+v\", vmtConfig)\n\n\tvmtService := kubeturbo.NewKubeturboService(vmtConfig)\n\trun := func(_ <-chan struct{}) {\n\t\tvmtService.Run()\n\t\tselect {}\n\t}\n\n\tgo s.startHttp()\n\n\t//if !s.LeaderElection.LeaderElect {\n\tglog.V(2).Infof(\"No leader election\")\n\trun(nil)\n\n\tglog.Fatal(\"this statement is unreachable\")\n\tpanic(\"unreachable\")\n}", "func (r *Runner) run(ctx context.Context, job *tests.Job, results chan<- tests.Event) {\n\tvar (\n\t\tworkingDir string\n\t\tlogFile string\n\t)\n\n\tr.Lock()\n\tid := fmt.Sprintf(\"%s-%d\", job.Name, r.names[job.Name])\n\tr.names[job.Name]++\n\tr.Unlock()\n\n\tif job.Dir != \"\" {\n\t\tworkingDir = filepath.Join(job.Dir, id)\n\t\tif err := os.MkdirAll(workingDir, 0755); err != nil {\n\t\t\tresults <- tests.NewErrorEvent(err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlogFile = fmt.Sprintf(\"%s.log\", strings.TrimSuffix(id, \"-0\"))\n\t}\n\n\tt3xf := job.Config.K3.T3XF\n\tif workingDir != \"\" {\n\t\tabsT3xf, err := filepath.Abs(t3xf)\n\t\tif err != nil {\n\t\t\tresults <- tests.NewErrorEvent(err)\n\t\t\treturn\n\t\t}\n\t\tabsDir, err := filepath.Abs(workingDir)\n\t\tif err != nil {\n\t\t\tresults <- tests.NewErrorEvent(err)\n\t\t\treturn\n\t\t}\n\t\tt3xf, err = filepath.Rel(absDir, absT3xf)\n\t\tif err != nil {\n\t\t\tresults <- tests.NewErrorEvent(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tt := k3r.NewTest(t3xf, job.Name)\n\tt.Job = job\n\n\tvar (\n\t\ttimeout time.Duration\n\t\terr error\n\t)\n\tif err != nil {\n\t\tresults <- tests.NewErrorEvent(err)\n\t\treturn\n\t}\n\tif timeout > 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, timeout)\n\t\tdefer cancel()\n\t}\n\n\t// TODO(5nord) implement module parameters\n\tt.Dir = workingDir\n\tt.LogFile = logFile\n\tt.Env = env.Environ()\n\tif s := env.Getenv(\"NTT_CACHE\"); s != \"\" {\n\t\tt.Env = append(t.Env, strings.Split(s, string(os.PathListSeparator))...)\n\t}\n\n\tfor event := range t.Run(ctx) {\n\t\tresults <- event\n\t}\n}", "func (s *server) run() {\n\n\tfor cmd := range s.commands {\n\n\t\tswitch cmd.id {\n\n\t\tcase CMD_Name:\n\t\t\ts.name(cmd.client, cmd.args[1])\n\n\t\tcase CMD_Join:\n\t\t\ts.join(cmd.client, cmd.args[1])\n\n\t\tcase CMD_Msg:\n\t\t\ts.msg(cmd.client, cmd.args)\n\n\t\tcase CMD_Private_Message:\n\t\t\ts.Pmsg(cmd.client, cmd.args[1], cmd.args[2:])\n\n\t\tcase CMD_Rooms:\n\t\t\ts.listRooms(cmd.client)\n\n\t\tcase CMD_Back:\n\t\t\ts.quitCurrentRoom(cmd.client)\n\n\t\tcase CMD_Exit:\n\t\t\ts.quit(cmd.client)\n\t\t}\n\t}\n}", "func (c *canaryImpl) Run() error {\n\tvar err error\n\tlog := c.runtime.logger\n\n\tif err = c.createDomain(); err != nil {\n\t\tlog.Error(\"createDomain failed\", zap.Error(err))\n\t\treturn err\n\t}\n\n\tif err = c.createArchivalDomain(); err != nil {\n\t\tlog.Error(\"createArchivalDomain failed\", zap.Error(err))\n\t\treturn err\n\t}\n\n\t// start the initial cron workflow\n\tc.startCronWorkflow()\n\n\terr = c.startWorker()\n\tif err != nil {\n\t\tlog.Error(\"start worker failed\", zap.Error(err))\n\t\treturn err\n\t}\n\treturn nil\n}", "func (bf *brainfog) run() {\n\tfor bf.ip < len(bf.program) {\n\t\terr := bf.doInstruction()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tclose(bf.outCh)\n}", "func run() {\n\tlogs.Start()\n\n\t// Send all data for the centralized database\n\tgo store.push()\n\tstore.Lock()\n\tdefer store.Unlock()\n\n\t// Creating the listener\n\tconfigData := config.GetConfig()\n\twatcher(configData)\n}", "func (c *Coordinator) run(ctx context.Context) error {\n\tminRemoteClientsPerGame := 1\n\tmaxRemoteClientsPerGame := 10\n\tfor {\n\t\tclients, err := c.awaitRemoteClients(ctx, minRemoteClientsPerGame, maxRemoteClientsPerGame)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"error awaiting remote clients\")\n\t\t}\n\n\t\t// Add a couple of AI clients.\n\t\tnumAIClients := 4 - len(clients)\n\t\tif numAIClients <= 0 {\n\t\t\tnumAIClients = 1\n\t\t}\n\t\tfor i := 0; i < numAIClients; i++ {\n\t\t\tvar aiClient *ai.Client\n\t\t\tvar err error\n\t\t\tif i%3 == 2 {\n\t\t\t\taiClient, err = ai.NewClient(c.logEntry.Logger, ai.RandomStrategy(rand.Int63n(30)+2))\n\t\t\t} else {\n\t\t\t\taiClient, err = ai.NewClient(c.logEntry.Logger, ai.OpportunisticStrategy())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error creating ai client\")\n\t\t\t}\n\t\t\tclients = append(clients, aiClient)\n\t\t}\n\n\t\tc.logEntry.Debug(\"Starting a new game\")\n\t\terr = c.startGame(ctx, clients)\n\t\tif err != nil {\n\t\t\t// As we still own the clients here, make sure we stop them\n\t\t\t// before quiting ourselves.\n\t\t\tdisconnectAll(clients)\n\t\t\treturn errors.Wrap(err, \"Error starting game\")\n\t\t}\n\t}\n}", "func (c *raftClient) run(ctx context.Context, wg *sync.WaitGroup, n *Node) {\n\tdefer wg.Done()\n\n\tn.logger.Debugw(\"remote node client worker start running\", c.logKV()...)\n\n\t// Add grpc client interceptor for logging, and metrics collection (if enabled). We do not use payload logging\n\t// because it is currently nailed to InfoLevel.\n\tgcl := n.logger.Named(\"GRPC_C\").Desugar()\n\tunaryInterceptorChain := []grpc.UnaryClientInterceptor{}\n\tif c.node.verboseLogging {\n\t\tunaryInterceptorChain = append(unaryInterceptorChain,\n\t\t\tgrpc_zap.UnaryClientInterceptor(\n\t\t\t\tgcl, grpc_zap.WithLevels(func(code codes.Code) zapcore.Level { return zapcore.DebugLevel })))\n\t}\n\n\tif n.messaging.clientUnaryInterceptorForMetrics != nil {\n\t\tunaryInterceptorChain = append(unaryInterceptorChain, n.messaging.clientUnaryInterceptorForMetrics)\n\t}\n\n\t// Prepend our options such that they can be overridden by the client options if they overlap.\n\toptions := []grpc.DialOption{\n\t\tgrpc.WithBlock(),\n\t\tgrpc.WithKeepaliveParams(keepalive.ClientParameters{\n\t\t\tTime: time.Second * defaultInactivityTriggeredPingSeconds,\n\t\t\tTimeout: time.Second * defaultTimeoutAfterPingSeconds,\n\t\t}),\n\t\tgrpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(unaryInterceptorChain...))}\n\n\t// Append client provided dial options specifically for this client to server connection.\n\tif n.config.clientDialOptionsFn != nil {\n\t\toptions = append(options, n.config.clientDialOptionsFn(n.messaging.server.localAddr, c.remoteAddress)...)\n\t}\n\n\tconn, err := grpc.DialContext(ctx, c.remoteAddress, options...)\n\tif err != nil {\n\t\tif ctx.Err() == nil {\n\t\t\t// This is not a shutdown. We have taken a fatal error (i.e. this is not a transient error). Possibly\n\t\t\t// a misconfiguration of the options, for example. We will return a fatal error.\n\t\t\tn.logger.Errorw(\"remote node client worker aborting\", append(c.logKV(), raftErrKeyword, err)...)\n\t\t\tn.signalFatalError(raftErrorf(\n\t\t\t\tRaftErrorClientConnectionUnrecoverable, \"grpc client connection to remote node, err [%v]\", err))\n\t\t}\n\t\treturn\n\t}\n\n\tdefer func() { _ = conn.Close() }()\n\n\tn.logger.Debugw(\"remote node client worker connected\",\n\t\tappend(c.logKV(), \"connState\", conn.GetState().String())...)\n\tc.grpcClient = raft_pb.NewRaftServiceClient(conn)\n\n\tfor {\n\t\tselect {\n\t\tcase e := <-c.eventChan.channel:\n\t\t\t// The event handler carries all the context necessary, and equally handles the\n\t\t\t// feedback based on the outcome of the event.\n\t\t\te.handle(ctx)\n\n\t\tcase <-ctx.Done():\n\t\t\t// We're done. By this point we will have cleaned up and we're ready to go.\n\t\t\tn.logger.Debugw(\"remote node client worker shutting down\", c.logKV()...)\n\t\t\treturn\n\t\t}\n\n\t}\n\n}", "func (t *task) run(ctx context.Context) {\n\tgo func() {\n\t\tresult, err := t.handler(ctx, t.request)\n\t\tt.resultQ <- Response{Result: result, Err: err} // out channel is buffered by 1\n\t\tt.running = false\n\t\tclose(t.resultQ)\n\t}()\n}", "func (a *BMWS1000RR) Run() {\n\tprintln(\"I can run at 300km/h\")\n}", "func (m *Manager) Run(ctx context.Context, run func() error) (err error) {\n\t// Acquire mutex lock\n\tm.mux.Lock()\n\t// Defer the release of mutex lock\n\tdefer m.mux.Unlock()\n\t// Call internal run func\n\treturn m.run(ctx, run)\n}", "func Run(cfg config.Config, store storage.Store, back backend.Backend, logger log.Logger) int {\n\t// Build queue writer.\n\tqw, err := sqs.NewWriter(cfg.SQSWriter.ARN, cfg.SQSWriter.Endpoint, logger)\n\tif err != nil {\n\t\tlogger.Errorf(\"error creating SQS writer: %+v\", err)\n\t\treturn 1\n\t}\n\n\t// Build queue reader.\n\tvar maxTimeNoMsg *time.Duration\n\tif cfg.Agent.MaxNoMsgsInterval > 0 {\n\t\tt := time.Duration(cfg.Agent.MaxNoMsgsInterval) * time.Second\n\t\tmaxTimeNoMsg = &t\n\t}\n\n\t// A nil queue.MessageProcessor is passed as argument because\n\t// RunWithQueues will set it before starting reading messages.\n\tqr, err := sqs.NewReader(logger, cfg.SQSReader, maxTimeNoMsg, nil)\n\tif err != nil {\n\t\tlogger.Errorf(\"error creating SQS reader: %+v\", err)\n\t\treturn 1\n\t}\n\n\t// Run agent with SQS queues.\n\treturn RunWithQueues(cfg, store, back, qw, qr, logger)\n}", "func (n *node) Run() error {\n\t_, _, err := n.run(false)\n\treturn err\n}", "func (s *scene) run(ctx context.Context, r *sdl.Renderer) chan error {\n\terrc := make(chan error)\n\tgo func() {\n\t\tdefer close(errc)\n\t\tfor range time.Tick(10 * time.Millisecond) {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tif err := s.paint(r); err != nil {\n\t\t\t\t\terrc <- err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn errc\n}", "func (s *Service) run() {\n\n\t// Create a communicator for sending and receiving packets.\n\tcommunicator := comm.NewCommunicator(s.config.PollInterval, s.config.Port)\n\tdefer communicator.Stop()\n\n\t// Create a ticker for sending pings.\n\tpingTicker := time.NewTicker(s.config.PingInterval)\n\tdefer pingTicker.Stop()\n\n\t// Create a ticker for timeout checks.\n\tpeerTicker := time.NewTicker(s.config.PeerTimeout)\n\tdefer peerTicker.Stop()\n\n\t// Create the packet that will be sent to all peers.\n\tpkt := &comm.Packet{\n\t\tID: s.config.ID,\n\t\tUserData: s.config.UserData,\n\t}\n\n\t// Continue processing events until explicitly stopped.\n\tfor {\n\t\tselect {\n\t\tcase p := <-communicator.PacketChan:\n\t\t\ts.processPacket(p)\n\t\tcase <-pingTicker.C:\n\t\t\tcommunicator.Send(pkt)\n\t\tcase <-peerTicker.C:\n\t\t\ts.processPeers()\n\t\tcase <-s.stopChan:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Master) Run() int {\n\tm.Build()\n\treturn m.Start()\n}", "func run(file string) error {\n\tvar cmd *exec.Cmd\n\tcmd = exec.Command(\"go\", \"run\", file)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}", "func Run() {\n\tcfg, err := config.Read()\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatalf(\"cannot read configuration.\")\n\t}\n\n\tlogging.ConfigureLogging(cfg)\n\tbeConn, err := rpc.GRPCClientFromConfig(cfg, \"api.backend\")\n\tif err != nil {\n\t\tlogger.Fatalf(\"failed to connect to Open Match Backend, got %v\", err)\n\t}\n\n\tdefer beConn.Close()\n\tbe := pb.NewBackendClient(beConn)\n\n\tfeConn, err := rpc.GRPCClientFromConfig(cfg, \"api.frontend\")\n\tif err != nil {\n\t\tlogger.Fatalf(\"failed to connect to Open Match Frontend, got %v\", err)\n\t}\n\n\tdefer feConn.Close()\n\tfe := pb.NewFrontendClient(feConn)\n\n\tgo doFetch(cfg, be)\n\tgo doAssign(be)\n\tgo doDelete(fe)\n\n\tselect {}\n\n}", "func (c *ConsensusState) run() {\n\tfor {\n\t\tselect {\n\t\tcase op := <-c.accessOp:\n\t\t\tlogger.Debugf(\"cycle %v execute op\", c.cycleId)\n\t\t\top.Execute()\n\t\t}\n\t}\n}", "func (app *App) Run(addr string) {}", "func (g *GateKeeper) Run() error {\n\terr := g.announce()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn g.initSSHServer()\n}", "func (c *Controllor) Run(ctx context.Context) {\n\tlog.Logger.Info(\"running...\")\n\tenv := gutils.Settings.GetString(\"env\")\n\n\tjournal := c.initJournal(ctx)\n\n\treceivers := c.initRecvs(env)\n\tacceptor := c.initAcceptor(ctx, journal, receivers)\n\tacceptorPipeline, err := c.initAcceptorPipeline(ctx, env)\n\tif err != nil {\n\t\tlog.Logger.Panic(\"initAcceptorPipeline\", zap.Error(err))\n\t}\n\n\twaitCommitChan := journal.GetCommitChan()\n\twaitAccepPipelineSyncChan := acceptor.GetSyncOutChan()\n\twaitAccepPipelineAsyncChan := acceptor.GetAsyncOutChan()\n\twaitDumpChan, skipDumpChan := acceptorPipeline.Wrap(ctx, waitAccepPipelineAsyncChan, waitAccepPipelineSyncChan)\n\n\t// after `journal.DumpMsgFlow`, every discarded msg should commit to waitCommitChan\n\twaitDispatchChan := journal.DumpMsgFlow(ctx, c.msgPool, waitDumpChan, skipDumpChan)\n\n\ttagPipeline := c.initTagPipeline(ctx, env, waitCommitChan)\n\tdispatcher := c.initDispatcher(ctx, waitDispatchChan, tagPipeline)\n\twaitPostPipelineChan := dispatcher.GetOutChan()\n\tpostPipeline := c.initPostPipeline(env, waitCommitChan)\n\twaitProduceChan := postPipeline.Wrap(ctx, waitPostPipelineChan)\n\tproducerSenders := c.initSenders(env)\n\tproducer := c.initProducer(env, waitProduceChan, waitCommitChan, producerSenders)\n\n\t// heartbeat\n\tgo c.runHeartBeat(ctx)\n\n\t// monitor\n\tmonitor.AddMetric(\"controllor\", func() map[string]interface{} {\n\t\treturn map[string]interface{}{\n\t\t\t\"goroutine\": runtime.NumGoroutine(),\n\t\t\t\"waitAccepPipelineSyncChanLen\": len(waitAccepPipelineSyncChan),\n\t\t\t\"waitAccepPipelineSyncChanCap\": cap(waitAccepPipelineSyncChan),\n\t\t\t\"waitAccepPipelineAsyncChanLen\": len(waitAccepPipelineAsyncChan),\n\t\t\t\"waitAccepPipelineAsyncChanCap\": cap(waitAccepPipelineAsyncChan),\n\t\t\t\"waitDumpChanLen\": len(waitDumpChan),\n\t\t\t\"waitDumpChanCap\": cap(waitDumpChan),\n\t\t\t\"skipDumpChanLen\": len(skipDumpChan),\n\t\t\t\"skipDumpChanCap\": cap(skipDumpChan),\n\t\t\t\"waitDispatchChanLen\": len(waitDispatchChan),\n\t\t\t\"waitDispatchChanCap\": cap(waitDispatchChan),\n\t\t\t\"waitPostPipelineChanLen\": len(waitPostPipelineChan),\n\t\t\t\"waitPostPipelineChanCap\": cap(waitPostPipelineChan),\n\t\t\t\"waitProduceChanLen\": len(waitProduceChan),\n\t\t\t\"waitProduceChanCap\": cap(waitProduceChan),\n\t\t\t\"waitCommitChanLen\": len(waitCommitChan),\n\t\t\t\"waitCommitChanCap\": cap(waitCommitChan),\n\t\t}\n\t})\n\tmonitor.BindHTTP(server)\n\n\tgo producer.Run(ctx)\n\tRunServer(ctx, gutils.Settings.GetString(\"addr\"))\n}", "func Run(ctx context.Context, client *guardian.Client, config Config) (err error) {\n\tif config.Icon == nil {\n\t\tconfig.Icon = leaseui.DefaultIcon()\n\t}\n\n\trunner, err := New(client, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn runner.Run(ctx)\n\n\t/*\n\t\tg, ctx := errgroup.WithContext(ctx)\n\n\t\trun := func() error {\n\t\t\trunner, err := New(client, config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn runner.Run(ctx)\n\t\t}\n\n\t\tg.Go(run)\n\t\tg.Go(run)\n\n\t\treturn g.Wait()\n\t*/\n}", "func (wsv *web) run() {\n\tdefer wsv.doCloseDone.Done()\n\tdefer wsv.isRun.Store(false)\n\tdefer func() {\n\t\tif wsv.conf.Socket == \"\" {\n\t\t\treturn\n\t\t}\n\t\tif wsv.conf.Mode == \"unix\" || wsv.conf.Mode == \"unixpacket\" {\n\t\t\t_ = os.Remove(wsv.conf.Socket)\n\t\t}\n\t}()\n\n\t// Configure net/http web server\n\twsv.server = wsv.loadConfiguration()\n\tif wsv.err != nil {\n\t\treturn\n\t}\n\n\t// Configure keep alives of web server\n\tif wsv.conf.KeepAliveDisable {\n\t\twsv.server.SetKeepAlivesEnabled(false)\n\t}\n\t// Begin serve\n\twsv.err = wsv.server.Serve(wsv.listener)\n}" ]
[ "0.6973518", "0.69351375", "0.68651646", "0.6625114", "0.65953296", "0.6519422", "0.65191615", "0.6410184", "0.63794345", "0.63402677", "0.6325699", "0.6325376", "0.6293736", "0.6268254", "0.61926425", "0.61826265", "0.6170785", "0.61572945", "0.61572236", "0.61414754", "0.61207044", "0.6023803", "0.5987214", "0.598488", "0.59620404", "0.5949169", "0.5948983", "0.594405", "0.59304494", "0.5923924", "0.58812284", "0.5868851", "0.586727", "0.5864109", "0.58527815", "0.5833454", "0.5797769", "0.578373", "0.57603174", "0.5715022", "0.57054365", "0.5689286", "0.56833076", "0.5672435", "0.5671237", "0.5670846", "0.5660472", "0.5660322", "0.5657533", "0.5655154", "0.5643928", "0.56438977", "0.5643426", "0.56367594", "0.5631353", "0.56260824", "0.562388", "0.56237304", "0.56180376", "0.56112134", "0.561111", "0.5603851", "0.5596329", "0.55932856", "0.5583654", "0.55815655", "0.5577972", "0.55669457", "0.5563217", "0.55593586", "0.55570316", "0.55556947", "0.5550314", "0.554878", "0.55450475", "0.5542488", "0.5536518", "0.5529962", "0.5529285", "0.5529228", "0.55209917", "0.55179954", "0.55165416", "0.55130416", "0.55069983", "0.55046004", "0.5504433", "0.5490971", "0.5488907", "0.5482003", "0.548109", "0.5473495", "0.5472762", "0.5470866", "0.54688424", "0.5458379", "0.5451164", "0.54450303", "0.54425114", "0.5431142" ]
0.6532814
5
NewStorageConfig loads storage configuration for a S3 FileSystem service in the given namespace. If no storage config is found in that namespace, the koaljasystem namespace is used. +kubebuilder:rbac:groups=,resources=configmaps,verbs=get;list;watch
func NewStorageConfig(ctx context.Context, c client.Reader, ns string) (*StorageConfig, error) { var configMap corev1.ConfigMap key := client.ObjectKey{ Name: constants.ConfigMapS3Storage, Namespace: ns, } if err := c.Get(ctx, key, &configMap); errors.IsNotFound(err) { // Try koalja-system namespace key.Namespace = constants.NamespaceKoaljaSystem if err := c.Get(ctx, key, &configMap); err != nil { return nil, maskAny(err) } } else if err != nil { return nil, maskAny(err) } // Parse config map sc, err := newStorageConfigFromConfigMap(ctx, &configMap, c, ns) if err != nil { return nil, maskAny(err) } return sc, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newStorageConfigFromConfigMap(ctx context.Context, configMap *corev1.ConfigMap, c client.Reader, ns string) (*StorageConfig, error) {\n\tvar sc StorageConfig\n\thasDefault := false\n\tfor k, v := range configMap.Data {\n\t\tvar bc BucketConfig\n\t\terr := yaml.Unmarshal([]byte(v), &bc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbc.fixEndpoint()\n\t\tbc.isDefault = k == \"default\"\n\n\t\t// Try loading the secret\n\t\tvar secret corev1.Secret\n\t\tkey := client.ObjectKey{\n\t\t\tName: bc.SecretName,\n\t\t\tNamespace: configMap.GetNamespace(),\n\t\t}\n\t\tif err := c.Get(ctx, key, &secret); err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3AccessKey]; found {\n\t\t\tbc.accessKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3AccessKey))\n\t\t}\n\t\tif raw, found := secret.Data[constants.SecretKeyS3SecretKey]; found {\n\t\t\tbc.secretKey = string(raw)\n\t\t} else {\n\t\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v refers to Secret '%s' that has no '%s' field\", configMap.Data, bc.SecretName, constants.SecretKeyS3SecretKey))\n\t\t}\n\n\t\t// Add to config\n\t\thasDefault = hasDefault || bc.isDefault\n\t\tsc.Buckets = append(sc.Buckets, bc)\n\t}\n\tif !hasDefault {\n\t\treturn nil, maskAny(fmt.Errorf(\"Config %#v must have a default bucket\", configMap.Data))\n\t}\n\tsort.Slice(sc.Buckets, func(i, j int) bool {\n\t\ta, b := sc.Buckets[i], sc.Buckets[j]\n\t\tif a.isDefault && !b.isDefault {\n\t\t\treturn true\n\t\t}\n\t\tif !a.isDefault && b.isDefault {\n\t\t\treturn false\n\t\t}\n\t\treturn strings.Compare(a.Name, b.Name) < 0\n\t})\n\treturn &sc, nil\n}", "func (c *S3StorageConfig) NewStorage() (Storage, error) {\n\treturn NewS3Storage(c, nil)\n}", "func NewStorage(namespace, name string) (*Storage, error) {\n\tif err := k8sutil.CreateCRD(name); err != nil {\n\t\treturn nil, err\n\t}\n\tcli := k8sutil.NewRESTClient()\n\treturn &Storage{\n\t\tNamespace: namespace,\n\t\tName: strings.ToLower(name),\n\t\trestcli: cli,\n\t}, nil\n}", "func New(bucketName string, cdnConf *config.CDNConfig) (*Storage, error) {\n\tconst op errors.Op = \"s3.New\"\n\tu, err := url.Parse(fmt.Sprintf(\"http://%s.s3.amazonaws.com\", bucketName))\n\tif err != nil {\n\t\treturn nil, errors.E(op, err)\n\t}\n\n\t// create a session\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, errors.E(op, err)\n\t}\n\tuploader := s3manager.NewUploader(sess)\n\n\treturn &Storage{\n\t\tbucket: bucketName,\n\t\tuploader: uploader,\n\t\tbaseURI: u,\n\t\tcdnConf: cdnConf,\n\t}, nil\n}", "func newS3Storage(backend *backup.S3) (*S3Storage, error) {\n\tqs := *backend\n\tawsConfig := aws.NewConfig().\n\t\tWithMaxRetries(maxRetries).\n\t\tWithS3ForcePathStyle(qs.ForcePathStyle).\n\t\tWithRegion(qs.Region)\n\tif qs.Endpoint != \"\" {\n\t\tawsConfig.WithEndpoint(qs.Endpoint)\n\t}\n\tvar cred *credentials.Credentials\n\tif qs.AccessKey != \"\" && qs.SecretAccessKey != \"\" {\n\t\tcred = credentials.NewStaticCredentials(qs.AccessKey, qs.SecretAccessKey, \"\")\n\t}\n\tif cred != nil {\n\t\tawsConfig.WithCredentials(cred)\n\t}\n\t// awsConfig.WithLogLevel(aws.LogDebugWithSigning)\n\tawsSessionOpts := session.Options{\n\t\tConfig: *awsConfig,\n\t}\n\tses, err := session.NewSessionWithOptions(awsSessionOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !sendCredential {\n\t\t// Clear the credentials if exists so that they will not be sent to TiKV\n\t\tbackend.AccessKey = \"\"\n\t\tbackend.SecretAccessKey = \"\"\n\t} else if ses.Config.Credentials != nil {\n\t\tif qs.AccessKey == \"\" || qs.SecretAccessKey == \"\" {\n\t\t\tv, cerr := ses.Config.Credentials.Get()\n\t\t\tif cerr != nil {\n\t\t\t\treturn nil, cerr\n\t\t\t}\n\t\t\tbackend.AccessKey = v.AccessKeyID\n\t\t\tbackend.SecretAccessKey = v.SecretAccessKey\n\t\t}\n\t}\n\n\tc := s3.New(ses)\n\terr = checkS3Bucket(c, qs.Bucket)\n\tif err != nil {\n\t\treturn nil, errors.Errorf(\"Bucket %s is not accessible: %v\", qs.Bucket, err)\n\t}\n\n\tqs.Prefix += \"/\"\n\treturn &S3Storage{\n\t\tsession: ses,\n\t\tsvc: c,\n\t\toptions: &qs,\n\t}, nil\n}", "func NewStorage(config StorageConfig) (spec.Storage, error) {\n\tnewStorage := &storage{\n\t\tStorageConfig: config,\n\n\t\tID: id.MustNew(),\n\t\tShutdownOnce: sync.Once{},\n\t\tType: ObjectType,\n\t}\n\n\t// Dependencies.\n\tif newStorage.Log == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"logger must not be empty\")\n\t}\n\tif newStorage.Pool == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"connection pool must not be empty\")\n\t}\n\t// Settings.\n\tif newStorage.BackOffFactory == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"backoff factory must not be empty\")\n\t}\n\tif newStorage.Prefix == \"\" {\n\t\treturn nil, maskAnyf(invalidConfigError, \"prefix must not be empty\")\n\t}\n\n\tnewStorage.Log.Register(newStorage.GetType())\n\n\treturn newStorage, nil\n}", "func NewStorageConfig() *StorageConfig {\n\tmodel := new(StorageConfig)\n\n\treturn model\n}", "func New(bucket string) (*Storage, error) {\n\tif bucket == \"\" {\n\t\treturn nil, errors.New(\"a bucket is required to create a storage\")\n\t}\n\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Storage{\n\t\tsvc: s3.New(sess),\n\t\tuploader: s3manager.NewUploader(sess),\n\t\tdownloader: s3manager.NewDownloader(sess),\n\t\tBucket: bucket,\n\t}, nil\n}", "func NewStorageService(conf *myconf.Config) (*StorageService, error) {\n\tbranch := util.GetRequiredEnv(\"BRANCH\")\n\tvar svc *minio.Client\n\tvar err error\n\tif branch != \"production\" {\n\t\tcredentials, err := myaws.NewSession().Config.Credentials.Get()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendPoint := \"s3.amazonaws.com\"\n\t\tuseSSL := true\n\t\tsvc, err = minio.NewWithRegion(\n\t\t\tendPoint,\n\t\t\tcredentials.AccessKeyID,\n\t\t\tcredentials.SecretAccessKey,\n\t\t\tuseSSL,\n\t\t\tmyaws.AWSRegion,\n\t\t)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tiam := minioCreds.NewIAM(\"\")\n\t\tendPoint := \"s3.amazonaws.com\"\n\t\tuseSSL := true\n\t\tsvc, err = minio.NewWithCredentials(\n\t\t\tendPoint,\n\t\t\tiam,\n\t\t\tuseSSL,\n\t\t\tmyaws.AWSRegion,\n\t\t)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// svc.TraceOn(nil)\n\treturn &StorageService{\n\t\tbucket: conf.AWSUploadBucket,\n\t\tsvc: svc,\n\t}, nil\n}", "func (d *driver) CreateStorage(cr *opapi.ImageRegistry, modified *bool) error {\n\tsvc, err := d.getSVC()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tic, err := util.GetInstallConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcv, err := util.GetClusterVersionConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; i < 5000; i++ {\n\t\tif len(d.Config.Bucket) == 0 {\n\t\t\td.Config.Bucket = fmt.Sprintf(\"%s-%s-%s-%s\", clusterconfig.StoragePrefix, d.Config.Region, strings.Replace(string(cv.Spec.ClusterID), \"-\", \"\", -1), strings.Replace(string(uuid.NewUUID()), \"-\", \"\", -1))[0:62]\n\t\t}\n\n\t\t_, err := svc.CreateBucket(&s3.CreateBucketInput{\n\t\t\tBucket: aws.String(d.Config.Bucket),\n\t\t})\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tswitch aerr.Code() {\n\t\t\t\tcase s3.ErrCodeBucketAlreadyExists:\n\t\t\t\t\tif cr.Spec.Storage.S3.Bucket != \"\" {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\td.Config.Bucket = \"\"\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\tif len(cr.Spec.Storage.S3.Bucket) == 0 && len(d.Config.Bucket) == 0 {\n\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, \"Unable to Generate Unique Bucket Name\", \"\", modified)\n\t\treturn fmt.Errorf(\"unable to generate a unique s3 bucket name\")\n\t}\n\n\t// Wait until the bucket exists\n\tif err := svc.WaitUntilBucketExists(&s3.HeadBucketInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t}); err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t}\n\n\t\treturn err\n\t}\n\n\t// Tag the bucket with the openshiftClusterID\n\t// along with any user defined tags from the cluster configuration\n\tif ic.Platform.AWS != nil {\n\t\tvar tagSet []*s3.Tag\n\t\ttagSet = append(tagSet, &s3.Tag{Key: aws.String(\"openshiftClusterID\"), Value: aws.String(string(cv.Spec.ClusterID))})\n\t\tfor k, v := range ic.Platform.AWS.UserTags {\n\t\t\ttagSet = append(tagSet, &s3.Tag{Key: aws.String(k), Value: aws.String(v)})\n\t\t}\n\n\t\t_, err := svc.PutBucketTagging(&s3.PutBucketTaggingInput{\n\t\t\tBucket: aws.String(d.Config.Bucket),\n\t\t\tTagging: &s3.Tagging{\n\t\t\t\tTagSet: tagSet,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t\t} else {\n\t\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t\t}\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionTrue, \"Tagging Successful\", \"UserTags were successfully applied to the S3 bucket\", modified)\n\t\t}\n\t}\n\n\t// Enable default encryption on the bucket\n\t_, err = svc.PutBucketEncryption(&s3.PutBucketEncryptionInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t\tServerSideEncryptionConfiguration: &s3.ServerSideEncryptionConfiguration{\n\t\t\tRules: []*s3.ServerSideEncryptionRule{\n\t\t\t\t{\n\t\t\t\t\tApplyServerSideEncryptionByDefault: &s3.ServerSideEncryptionByDefault{\n\t\t\t\t\t\tSSEAlgorithm: aws.String(s3.ServerSideEncryptionAes256),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t}\n\t} else {\n\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionTrue, \"Encryption Successful\", \"Default encryption was successfully enabled on the S3 bucket\", modified)\n\t}\n\n\t// Enable default incomplete multipart upload cleanup after one (1) day\n\t_, err = svc.PutBucketLifecycleConfiguration(&s3.PutBucketLifecycleConfigurationInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t\tLifecycleConfiguration: &s3.BucketLifecycleConfiguration{\n\t\t\tRules: []*s3.LifecycleRule{\n\t\t\t\t{\n\t\t\t\t\tID: aws.String(\"cleanup-incomplete-multipart-registry-uploads\"),\n\t\t\t\t\tStatus: aws.String(\"Enabled\"),\n\t\t\t\t\tFilter: &s3.LifecycleRuleFilter{\n\t\t\t\t\t\tPrefix: aws.String(\"\"),\n\t\t\t\t\t},\n\t\t\t\t\tAbortIncompleteMultipartUpload: &s3.AbortIncompleteMultipartUpload{\n\t\t\t\t\t\tDaysAfterInitiation: aws.Int64(1),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t}\n\t} else {\n\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionTrue, \"Enable Cleanup Successful\", \"Default cleanup of incomplete multipart uploads after one (1) day was successfully enabled\", modified)\n\t}\n\n\tcr.Status.Storage.State.S3 = d.Config\n\tcr.Status.Storage.Managed = true\n\n\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionTrue, \"Creation Successful\", \"S3 bucket was successfully created\", modified)\n\n\treturn nil\n}", "func NewS3Storage(region aws.Region, auth aws.Auth, bucketName string, prefix string, bucketACL s3.ACL) (*S3Storage, error) {\n\ts3obj := s3.New(auth, region)\n\tbucket := s3obj.Bucket(bucketName)\n\n\t// Running PutBucket too many times in parallel (such as distributed cron) can generate the error:\n\t// \"A conflicting conditional operation is currently in progress against this resource. Please try again\"\n\t// We should only call PutBucket when we suspect that the bucket doesn't exist. Unfortunately, the\n\t// current AdRoll/goamz lib doesn't implement ListBuckets, so to check that the bucket exists\n\t// do a List and see if we get an error before calling PutBucket.\n\t_, err := bucket.List(\"\", \"/\", \"\", 1)\n\t// technically, there are many reasons this could fail (such as access denied, or other network error)\n\t// but this should sufficiently limit the number of times PutBucket is called in normal operations\n\tif err != nil {\n\t\terr = bucket.PutBucket(bucketACL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &S3Storage{\n\t\ts3: s3obj,\n\t\tbucket: bucket,\n\t\tregion: region,\n\t\tauth: auth,\n\t\tprefix: prefix,\n\t}, nil\n}", "func ConfigStorageSettingsFromStringS3(config string) (FileStorageSettings, error) {\n\tif match := s3ServerFlagRegexp.MatchString(config); !match {\n\t\treturn FileStorageSettings{}, fmt.Errorf(\"error parsing S3 config location: %s\", config)\n\t}\n\tmatches := s3ServerFlagRegexp.FindStringSubmatch(config)\n\tregion := matches[s3ServerFlagRegexp.SubexpIndex(\"region\")]\n\tbucket := matches[s3ServerFlagRegexp.SubexpIndex(\"bucket\")]\n\tkey := matches[s3ServerFlagRegexp.SubexpIndex(\"key\")]\n\tendpoint := matches[s3ServerFlagRegexp.SubexpIndex(\"endpoint\")]\n\n\treturn FileStorageSettings{\n\t\tType: FileStorageTypeS3,\n\t\tS3: FileStorageS3{\n\t\t\tRegion: region,\n\t\t\tBucket: bucket,\n\t\t\tKey: key,\n\t\t\tEndpoint: endpoint,\n\t\t},\n\t}, nil\n}", "func NewRawStorage(config *storagebackend.ConfigForResource, newFunc func() runtime.Object) (storage.Interface, factory.DestroyFunc, error) {\n\treturn factory.Create(*config, newFunc)\n}", "func newStorage(account *account, prov provider.Account, cfg *config.Storage) (*storage, error) {\n\tlog.Debug(\"Initializing Storage\")\n\n\t// Validate the config.Storage object.\n\tif cfg.Buckets == nil {\n\t\treturn nil, fmt.Errorf(\"The buckets element is missing from the storage configuration\")\n\t}\n\n\ts := &storage{\n\t\tResources: resource.NewResources(),\n\t\tStorage: cfg,\n\t\taccount: account,\n\t}\n\n\tvar err error\n\ts.providerStorage, err = prov.NewStorage(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.buckets, err = newBuckets(s, prov, cfg.Buckets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Append(s.buckets)\n\treturn s, nil\n}", "func NewStorage(cfg *api.Config, rootPath string, syncFrequency time.Duration) (storage.Interface, error) {\n\tcfg.WaitTime = syncFrequency\n\n\t// Get a new client\n\tclient, err := api.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating consul client\")\n\t}\n\n\treturn &Client{\n\t\tv1: &v1client{\n\t\t\tupstreams: &upstreamsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/upstreams\", client),\n\t\t\t},\n\t\t\tvirtualHosts: &virtualHostsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/virtualhosts\", client),\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func New() (*Storage, error) {\n\ts, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Storage{\n\t\tbucket: os.Getenv(\"S3_BUCKET\"),\n\t\ts3: s3.New(s),\n\t}, nil\n}", "func NewStorage(s map[string]interface{}) (Storage, error) {\n\tstype, ok := s[\"Type\"].(string)\n\tif !ok || stype == \"\" {\n\t\treturn nil, errors.New(\"Template do not have Storage type\")\n\t}\n\n\tswitch stype {\n\tcase \"Local\":\n\t\treturn newStorageLocal(s), nil\n\tcase \"S3\":\n\t\treturn newStorageS3(s)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexecepted Storage type: %v\", stype)\n\t}\n}", "func New(config *config.ConfYaml) *Storage {\n\treturn &Storage{\n\t\tconfig: config,\n\t}\n}", "func ExportStorageConfFromURI(path string) (roachpb.ExportStorage, error) {\n\tconf := roachpb.ExportStorage{}\n\turi, err := url.Parse(path)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\tswitch uri.Scheme {\n\tcase \"s3\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_S3\n\t\tconf.S3Config = &roachpb.ExportStorage_S3{\n\t\t\tBucket: uri.Host,\n\t\t\tPrefix: uri.Path,\n\t\t\tAccessKey: uri.Query().Get(S3AccessKeyParam),\n\t\t\tSecret: uri.Query().Get(S3SecretParam),\n\t\t\tEndpoint: uri.Query().Get(S3EndpointParam),\n\t\t\tRegion: uri.Query().Get(S3RegionParam),\n\t\t}\n\t\tif conf.S3Config.AccessKey == \"\" {\n\t\t\treturn conf, errors.Errorf(\"s3 uri missing %q parameter\", S3AccessKeyParam)\n\t\t}\n\t\tif conf.S3Config.Secret == \"\" {\n\t\t\treturn conf, errors.Errorf(\"s3 uri missing %q parameter\", S3SecretParam)\n\t\t}\n\t\tconf.S3Config.Prefix = strings.TrimLeft(conf.S3Config.Prefix, \"/\")\n\t\t// AWS secrets often contain + characters, which must be escaped when\n\t\t// included in a query string; otherwise, they represent a space character.\n\t\t// More than a few users have been bitten by this.\n\t\t//\n\t\t// Luckily, AWS secrets are base64-encoded data and thus will never actually\n\t\t// contain spaces. We can convert any space characters we see to +\n\t\t// characters to recover the original secret.\n\t\tconf.S3Config.Secret = strings.Replace(conf.S3Config.Secret, \" \", \"+\", -1)\n\tcase \"gs\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_GoogleCloud\n\t\tconf.GoogleCloudConfig = &roachpb.ExportStorage_GCS{\n\t\t\tBucket: uri.Host,\n\t\t\tPrefix: uri.Path,\n\t\t\tAuth: uri.Query().Get(AuthParam),\n\t\t}\n\t\tconf.GoogleCloudConfig.Prefix = strings.TrimLeft(conf.GoogleCloudConfig.Prefix, \"/\")\n\tcase \"azure\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_Azure\n\t\tconf.AzureConfig = &roachpb.ExportStorage_Azure{\n\t\t\tContainer: uri.Host,\n\t\t\tPrefix: uri.Path,\n\t\t\tAccountName: uri.Query().Get(AzureAccountNameParam),\n\t\t\tAccountKey: uri.Query().Get(AzureAccountKeyParam),\n\t\t}\n\t\tif conf.AzureConfig.AccountName == \"\" {\n\t\t\treturn conf, errors.Errorf(\"azure uri missing %q parameter\", AzureAccountNameParam)\n\t\t}\n\t\tif conf.AzureConfig.AccountKey == \"\" {\n\t\t\treturn conf, errors.Errorf(\"azure uri missing %q parameter\", AzureAccountKeyParam)\n\t\t}\n\t\tconf.AzureConfig.Prefix = strings.TrimLeft(conf.AzureConfig.Prefix, \"/\")\n\tcase \"http\", \"https\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_Http\n\t\tconf.HttpPath.BaseUri = path\n\tcase \"nodelocal\":\n\t\tif uri.Host != \"\" {\n\t\t\treturn conf, errors.Errorf(\"nodelocal does not support hosts: %s\", path)\n\t\t}\n\t\tconf.Provider = roachpb.ExportStorageProvider_LocalFile\n\t\tconf.LocalFile.Path = uri.Path\n\tdefault:\n\t\treturn conf, errors.Errorf(\"unsupported storage scheme: %q\", uri.Scheme)\n\t}\n\treturn conf, nil\n}", "func NewStorageOperation(bucket string, keyPrefix string, key string, value []byte) StorageOperation {\n\treturn StorageOperation{\n\t\tKey: []byte(fmt.Sprintf(\"%s:%s\", keyPrefix, key)),\n\t\tValue: value,\n\t\tBucket: bucket,\n\t}\n}", "func InitStorage(service string, bucket string) {\n\ttransferType = service\n\tbenchName = bucket\n\tawsAccessKey, ok := os.LookupEnv(\"AWS_ACCESS_KEY\")\n\tif ok {\n\t\tAKID = awsAccessKey\n\t}\n\tawsSecretKey, ok := os.LookupEnv(\"AWS_SECRET_KEY\")\n\tif ok {\n\t\tSECRET_KEY = awsSecretKey\n\t}\n\tAWS_S3_REGION = \"us-west-1\"\n\tawsRegion, ok := os.LookupEnv(\"AWS_REGION\")\n\tif ok {\n\t\tAWS_S3_REGION = awsRegion\n\t}\n\tif transferType == S3 {\n\t\tvar err error\n\t\ts3session, err = session.NewSession(&aws.Config{\n\t\t\tRegion: aws.String(AWS_S3_REGION),\n\t\t\tCredentials: credentials.NewStaticCredentials(AKID, SECRET_KEY, TOKEN),\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed establish s3 session: %s\", err)\n\t\t}\n\t} else if transferType == ELASTICACHE {\n\t\tredisClient = redis.NewClient(&redis.Options{\n\t\t\tAddr: benchName,\n\t\t\tPassword: \"\", // no password set\n\t\t\tDB: 0, // use default DB\n\t\t})\n\t}\n}", "func Storage(config map[string]interface{}) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tstorage, err := storage.Create(config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tc.Set(\"storage\", storage)\n\t\tc.Next()\n\t}\n}", "func New(o *Options) *Storage {\n\ts := &Storage{}\n\tif o.GraphiteAddress != \"\" {\n\t\tc := graphite.NewClient(\n\t\t\to.GraphiteAddress, o.GraphiteTransport,\n\t\t\to.StorageTimeout, o.GraphitePrefix)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.OpentsdbURL != \"\" {\n\t\tc := opentsdb.NewClient(o.OpentsdbURL, o.StorageTimeout)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.InfluxdbURL != nil {\n\t\tconf := influx.Config{\n\t\t\tURL: *o.InfluxdbURL,\n\t\t\tUsername: o.InfluxdbUsername,\n\t\t\tPassword: o.InfluxdbPassword,\n\t\t\tTimeout: o.StorageTimeout,\n\t\t}\n\t\tc := influxdb.NewClient(conf, o.InfluxdbDatabase, o.InfluxdbRetentionPolicy)\n\t\tprometheus.MustRegister(c)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.GenericURL != \"\" {\n\t\theaders := http.Header{}\n\t\tif o.GenericHeaderName != \"\" {\n\t\t\theaders.Add(o.GenericHeaderName, o.GenericHeaderValue)\n\t\t}\n\t\tc := generic.NewClient(o.GenericURL, headers, o.StorageTimeout)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif len(s.queues) == 0 {\n\t\treturn nil\n\t}\n\treturn s\n}", "func New(configs ...Configurator) (*Storage, error) {\n\tinstance := &Storage{}\n\tfor _, configure := range configs {\n\t\tif err := configure(instance); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn instance, nil\n}", "func New() (*g3storage.Storage, error) {\n\treturn NewWithHostname(makoAppHostname)\n}", "func (p StorageProvider) NewRESTStorage(\n\tapiResourceConfigSource serverstorage.APIResourceConfigSource,\n\trestOptionsGetter generic.RESTOptionsGetter,\n) (*genericapiserver.APIGroupInfo, error) {\n\n\tstorage, err := p.v1beta1Storage(apiResourceConfigSource, restOptionsGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(servicecatalog.GroupName, api.Registry, api.Scheme, api.ParameterCodec, api.Codecs)\n\tapiGroupInfo.GroupMeta.GroupVersion = servicecatalogv1beta1.SchemeGroupVersion\n\n\tapiGroupInfo.VersionedResourcesStorageMap = map[string]map[string]rest.Storage{\n\t\tservicecatalogv1beta1.SchemeGroupVersion.Version: storage,\n\t}\n\n\treturn &apiGroupInfo, nil\n}", "func InitConfigurationStorage(config model.ConfigStorageSettings) (model.ConfigurationStorage, error) {\n\tswitch config.Type {\n\t// case model.ConfigStorageTypeEtcd:\n\t// \treturn etcd.NewConfigurationStorage(config)\n\tcase model.ConfigStorageTypeS3:\n\t\treturn s3.NewConfigurationStorage(config)\n\tcase model.ConfigStorageTypeFile:\n\t\treturn file.NewConfigurationStorage(config)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"config type is not supported\")\n\t}\n}", "func GetStorage(ctx *Context, storageType string, storageConfig interface{}) (Storage, error) {\n\tLog(INFO, ctx, \"System.GetStorage\", \"storageType\", storageType, \"storageConfig\", storageConfig)\n\n\tswitch storageType {\n\tcase \"none\":\n\t\treturn NewNoStorage(ctx)\n\n\tcase \"memory\", \"mem\":\n\t\treturn NewMemStorage(ctx)\n\n\tcase \"cassandra\":\n\t\tnodes := storageConfig\n\t\tvar ns []string\n\t\tvar configStr string\n\n\t\tswitch vv := nodes.(type) {\n\t\tcase []interface{}:\n\t\t\tns = make([]string, 0, len(vv))\n\t\t\tfor _, n := range vv {\n\t\t\t\tns = append(ns, n.(string))\n\t\t\t}\n\t\t\tLog(INFO, ctx, \"core.GetStorage\", \"nodes\", ns)\n\t\t\tconfigStr = strings.Join(ns, \",\")\n\t\tcase string:\n\t\t\tconfigStr = nodes.(string)\n\t\tcase []string:\n\t\t\tconfigStr = strings.Join(nodes.([]string), \",\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"bad type for nodes %v (%T); should be []interface{}.\", nodes, nodes)\n\t\t}\n\t\tconfig, err := cassandra.ParseConfig(configStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn cassandra.NewStorage(ctx, *config)\n\n\tcase \"bolt\":\n\t\tfilename := storageConfig\n\t\tswitch s := filename.(type) {\n\t\tcase string:\n\t\t\treturn bolt.NewStorage(ctx, s)\n\t\tdefault:\n\t\t\treturn nil,\n\t\t\t\tfmt.Errorf(\"Bad type for filenames %v (%T); should be a string\", filename, filename)\n\t\t}\n\n\tcase \"dynamodb\":\n\t\tregion := storageConfig\n\t\tswitch vv := region.(type) {\n\t\tcase string:\n\t\t\tconfig, err := dynamodb.ParseConfig(vv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn dynamodb.GetStorage(ctx, *config)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Bad type for DynamoDB region %v (%T); should be string.\",\n\t\t\t\tstorageConfig,\n\t\t\t\tstorageConfig)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown storage '%s'\", storageType)\n\t}\n\n}", "func NewStorage(vol string) *Storage {\n\tloc := vol\n\n\tif vol[len(vol)-1:] != \"/\" {\n\t\tloc = fmt.Sprintf(\"%s/\", vol)\n\t}\n\n\treturn &Storage{\n\t\tloc,\n\t}\n}", "func NewS3Storage(config *S3StorageConfig, client S3Client) (*S3Storage, error) {\n\tif client == nil {\n\t\tvar err error\n\t\tclient, err = newS3Client(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\ts := &S3Storage{\n\t\tconfig: config,\n\t\tclient: client,\n\t}\n\n\treturn s, nil\n}", "func newK8sSvcWithConfig(cluster string, cloudPlatform string, dbType string, namespace string, config *rest.Config) (*K8sSvc, error) {\n\t// creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tglog.Errorln(\"kubernetes.NewForConfig error\", err)\n\t\treturn nil, err\n\t}\n\n\tprovisioner := awsStorageProvisioner\n\tif cloudPlatform != common.CloudPlatformAWS {\n\t\tglog.Errorln(\"unsupport cloud platform\", cloudPlatform)\n\t\treturn nil, common.ErrNotSupported\n\t}\n\n\tsvc := &K8sSvc{\n\t\tcliset: clientset,\n\t\tcluster: cluster,\n\t\tnamespace: namespace,\n\t\tprovisioner: provisioner,\n\t\tcloudPlatform: cloudPlatform,\n\t\tdbType: dbType,\n\t}\n\treturn svc, nil\n}", "func New(ctx context.Context, bucket string) (fs.Interface, error) {\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &gcs{\n\t\tbucket: client.Bucket(bucket),\n\t}, nil\n}", "func New(ctx context.Context, storageConfig *config.StorageConfig) *Storage {\n\tctx, cancel := context.WithCancel(ctx)\n\treturn &Storage{\n\t\tctx: ctx,\n\t\tconfig: storageConfig,\n\t\tcancel: cancel,\n\t\tstate: Created,\n\t\tlog: logger.GetLogger(),\n\t}\n}", "func NewStorage(opts generic.RESTOptions) rest.Storage {\n\tprefix := \"/\" + opts.ResourcePrefix\n\n\tnewListFunc := func() runtime.Object { return &servicecatalog.ServiceClassList{} }\n\tstorageInterface, dFunc := opts.Decorator(\n\t\topts.StorageConfig,\n\t\t1000,\n\t\t&servicecatalog.ServiceClass{},\n\t\tprefix,\n\t\tserviceclassRESTStrategies,\n\t\tnewListFunc,\n\t\tnil,\n\t\tstorage.NoTriggerPublisher,\n\t)\n\n\tstore := registry.Store{\n\t\tNewFunc: func() runtime.Object {\n\t\t\treturn &servicecatalog.ServiceClass{}\n\t\t},\n\t\t// NewListFunc returns an object capable of storing results of an etcd list.\n\t\tNewListFunc: newListFunc,\n\t\t// KeyRootFunc places this resource at the prefix for this resource;\n\t\t// not namespaced.\n\t\tKeyRootFunc: func(ctx api.Context) string {\n\t\t\treturn prefix\n\t\t},\n\t\t// Produces a path that etcd understands by combining the object's\n\t\t// name with the prefix.\n\t\tKeyFunc: func(ctx api.Context, name string) (string, error) {\n\t\t\treturn registry.NoNamespaceKeyFunc(ctx, prefix, name)\n\t\t},\n\t\t// Retrieve the name field of the resource.\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*servicecatalog.ServiceClass).Name, nil\n\t\t},\n\t\t// Used to match objects based on labels/fields for list.\n\t\tPredicateFunc: Match,\n\t\t// QualifiedResource should always be plural\n\t\tQualifiedResource: api.Resource(\"serviceclasses\"),\n\n\t\tCreateStrategy: serviceclassRESTStrategies,\n\t\tUpdateStrategy: serviceclassRESTStrategies,\n\t\tDeleteStrategy: serviceclassRESTStrategies,\n\t\tStorage: storageInterface,\n\t\tDestroyFunc: dFunc,\n\t}\n\n\treturn &store\n}", "func NewStorage(\n\tlogger *zerolog.Logger,\n\tcfg *config.TSDBStorageConfig,\n\tmetadataStorage metadata.Storage,\n) (data.Storage, error) {\n\tgoKitWrapper, err := NewGoKitLogWrapper(logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create data directory if not exists\n\tif _, err = os.Stat(cfg.DataDir); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err = os.MkdirAll(cfg.DataDir, 0750); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// create storage\n\tstor, err := prometheus.OpenTSDB(cfg.DataDir, goKitWrapper)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\ts := &storage{\n\t\tcodec: newB64Codec(),\n\t\tmetadataStorage: metadataStorage,\n\t\tcfg: cfg,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\twg: sync.WaitGroup{},\n\t\tlogger: logger,\n\t\ttsdbStorage: stor,\n\t}\n\treturn s, nil\n}", "func DefaultStorageConfig() StorageConfig {\n\tnewInstrumentation, err := memory.NewInstrumentation(memory.DefaultInstrumentationConfig())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnewStorageConfig := StorageConfig{\n\t\t// Dependencies.\n\t\tInstrumentation: newInstrumentation,\n\t\tLog: log.New(log.DefaultConfig()),\n\t\tPool: NewPool(DefaultPoolConfig()),\n\n\t\t// Settings.\n\t\tBackOffFactory: func() spec.BackOff {\n\t\t\treturn &backoff.StopBackOff{}\n\t\t},\n\t\tPrefix: \"prefix\",\n\t}\n\n\treturn newStorageConfig\n}", "func MakeHTTPStorage(\n\tbase string, settings *cluster.Settings, ioConf base.ExternalIODirConfig,\n) (cloud.ExternalStorage, error) {\n\tif base == \"\" {\n\t\treturn nil, errors.Errorf(\"HTTP storage requested but prefix path not provided\")\n\t}\n\n\tclient, err := makeHTTPClient(settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi, err := url.Parse(base)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &httpStorage{\n\t\tbase: uri,\n\t\tclient: client,\n\t\thosts: strings.Split(uri.Host, \",\"),\n\t\tsettings: settings,\n\t\tioConf: ioConf,\n\t}, nil\n}", "func (s *GenericStorage) New(gvk schema.GroupVersionKind) (runtime.Object, error) {\n\tobj, err := s.serializer.Scheme().New(gvk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Default either through the scheme, or the high-level serializer Object\n\tif gvk.Version == kruntime.APIVersionInternal {\n\t\tif err := s.serializer.DefaultInternal(obj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\ts.serializer.Scheme().Default(obj)\n\t}\n\n\t// Cast to runtime.Object, and make sure it works\n\tmetaObj, ok := obj.(runtime.Object)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"can't convert to libgitops.runtime.Object\")\n\t}\n\t// Set the desired gvk from the caller of this Object\n\t// In practice, this means, although we created an internal type,\n\t// from defaulting external TypeMeta information was set. Set the\n\t// desired gvk here so it's correctly handled in all code that gets\n\t// the gvk from the Object\n\tmetaObj.SetGroupVersionKind(gvk)\n\treturn metaObj, nil\n}", "func NewStorage(conf *ConfService) (*goejdb.Ejdb, error) {\n\tvar storageConf StorageConfiguration\n\tconf.Get(&storageConf)\n\n\t// Create a new database file and open it\n\tdb, err := goejdb.Open(storageConf.DBName, goejdb.JBOWRITER|goejdb.JBOCREAT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}", "func S3(access, secret, bucket, region, content, prefix string) (Storage, error) {\n\treturn s3.New(access, secret, bucket, region, content, prefix)\n}", "func (s *CreateHubInput) SetS3StorageConfig(v *HubS3StorageConfig) *CreateHubInput {\n\ts.S3StorageConfig = v\n\treturn s\n}", "func New(c Config) *stor {\n\ts := stor{\n\t\tpath: c.Path,\n\t\troot: []byte(c.BucketName),\n\t\tlogFn: log.EmptyLogFn,\n\t\terrFn: log.EmptyLogFn,\n\t}\n\tif c.ErrFn != nil {\n\t\ts.errFn = c.ErrFn\n\t}\n\tif c.LogFn != nil {\n\t\ts.logFn = c.LogFn\n\t}\n\treturn &s\n}", "func initStorage() storage.Engine {\n\t// Name of the storage engine.\n\tname := viper.GetString(\"storage\")\n\tpath := viper.GetString(\"path\")\n\n\t// Directory of the config file. Ensure the storage engine\n\t// path is resolved relative to the config file.\n\tdir := filepath.Dir(viper.ConfigFileUsed())\n\tpath = filepath.Join(dir, path)\n\n\t// Supported options.\n\topts := storage.Options{\n\t\t\"path\": path,\n\t}\n\n\t// Initialize the storage engine.\n\tengine, err := origins.Init(name, &opts)\n\n\tif err != nil {\n\t\tlogrus.Fatal(\"storage:\", err)\n\t}\n\n\treturn engine\n}", "func configureStorage(dep *appsv1.Deployment, nodeSet v1alpha1.NodeSet) error {\n\tif nuxeoContainer, err := GetNuxeoContainer(dep); err != nil {\n\t\treturn err\n\t} else {\n\t\tfor _, storage := range nodeSet.Storage {\n\t\t\tif volume, err := createVolumeForStorage(storage); err != nil {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tvolMnt := createVolumeMountForStorage(storage.StorageType, volume.Name)\n\t\t\t\tenvVar := createEnvVarForStorage(storage.StorageType, volMnt.MountPath)\n\t\t\t\tif err := util.OnlyAddVol(dep, volume); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := util.OnlyAddVolMnt(nuxeoContainer, volMnt); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif envVar != (corev1.EnvVar{}) {\n\t\t\t\t\tif err := util.OnlyAddEnvVar(nuxeoContainer, envVar); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func NewStorage(address common.Address, backend bind.ContractBackend) (*Storage, error) {\n\tcontract, err := bindStorage(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil\n}", "func NewStorage(address common.Address, backend bind.ContractBackend) (*Storage, error) {\n\tcontract, err := bindStorage(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil\n}", "func NewS3(ctx context.Context, config *config.Control) (*S3, error) {\n\tif config.EtcdS3BucketName == \"\" {\n\t\treturn nil, errors.New(\"s3 bucket name was not set\")\n\t}\n\ttr := http.DefaultTransport\n\n\tswitch {\n\tcase config.EtcdS3EndpointCA != \"\":\n\t\ttrCA, err := setTransportCA(tr, config.EtcdS3EndpointCA, config.EtcdS3SkipSSLVerify)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttr = trCA\n\tcase config.EtcdS3 && config.EtcdS3SkipSSLVerify:\n\t\ttr.(*http.Transport).TLSClientConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: config.EtcdS3SkipSSLVerify,\n\t\t}\n\t}\n\n\tvar creds *credentials.Credentials\n\tif len(config.EtcdS3AccessKey) == 0 && len(config.EtcdS3SecretKey) == 0 {\n\t\tcreds = credentials.NewIAM(\"\") // for running on ec2 instance\n\t} else {\n\t\tcreds = credentials.NewStaticV4(config.EtcdS3AccessKey, config.EtcdS3SecretKey, \"\")\n\t}\n\n\topt := minio.Options{\n\t\tCreds: creds,\n\t\tSecure: !config.EtcdS3Insecure,\n\t\tRegion: config.EtcdS3Region,\n\t\tTransport: tr,\n\t\tBucketLookup: bucketLookupType(config.EtcdS3Endpoint),\n\t}\n\tc, err := minio.New(config.EtcdS3Endpoint, &opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogrus.Infof(\"Checking if S3 bucket %s exists\", config.EtcdS3BucketName)\n\n\tctx, cancel := context.WithTimeout(ctx, config.EtcdS3Timeout)\n\tdefer cancel()\n\n\texists, err := c.BucketExists(ctx, config.EtcdS3BucketName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"bucket: %s does not exist\", config.EtcdS3BucketName)\n\t}\n\tlogrus.Infof(\"S3 bucket %s exists\", config.EtcdS3BucketName)\n\n\treturn &S3{\n\t\tconfig: config,\n\t\tclient: c,\n\t}, nil\n}", "func NewStorage(address common.Address, backend bind.ContractBackend) (*Storage, error) {\n\tcontract, err := bindStorage(address, backend, backend, backend)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Storage{StorageCaller: StorageCaller{contract: contract}, StorageTransactor: StorageTransactor{contract: contract}, StorageFilterer: StorageFilterer{contract: contract}}, nil\n}", "func NewStorage(opts ...StorageOption) *Storage {\n\ts := &Storage{\n\t\tcr: config.DefaultManager,\n\t\tmu: sync.RWMutex{},\n\t}\n\tfor _, opt := range opts {\n\t\tif opt != nil {\n\t\t\topt(s)\n\t\t}\n\t}\n\treturn s\n}", "func (s *DescribeHubOutput) SetS3StorageConfig(v *HubS3StorageConfig) *DescribeHubOutput {\n\ts.S3StorageConfig = v\n\treturn s\n}", "func ConfigureS3Bucket(_ context.Context, cm resource.Claim, cs resource.Class, mg resource.Managed) error {\n\tbucketClaim, cmok := cm.(*storagev1alpha1.Bucket)\n\tif !cmok {\n\t\treturn errors.Errorf(\"expected resource claim %s to be %s\", cm.GetName(), storagev1alpha1.BucketGroupVersionKind)\n\t}\n\n\ts3BucketClass, csok := cs.(*cloudscaleStoragev1alpha1.S3BucketClass)\n\tif !csok {\n\t\treturn errors.Errorf(\"expected resource class %s to be %s\", cs.GetName(), cloudscaleStoragev1alpha1.S3BucketClassGroupVersionKind)\n\t}\n\n\ts3Bucket, mgok := mg.(*cloudscaleStoragev1alpha1.S3Bucket)\n\tif !mgok {\n\t\treturn errors.Errorf(\"expected managed resource %s to be %s\", mg.GetName(), cloudscaleStoragev1alpha1.S3BucketGroupVersionKind)\n\t}\n\n\tspec := &cloudscaleStoragev1alpha1.S3BucketSpec{\n\t\tResourceSpec: runtimev1alpha1.ResourceSpec{\n\t\t\tReclaimPolicy: runtimev1alpha1.ReclaimRetain,\n\t\t},\n\t\tForProvider: s3BucketClass.SpecTemplate.ForProvider,\n\t}\n\n\tif s3BucketClass.SpecTemplate.ReclaimPolicy != \"\" {\n\t\tspec.ResourceSpec.ReclaimPolicy = s3BucketClass.SpecTemplate.ReclaimPolicy\n\t}\n\n\tif bucketClaim.Spec.PredefinedACL != nil {\n\t\tspec.ForProvider.CannedACL = translateACL(bucketClaim.Spec.PredefinedACL)\n\t}\n\n\tspec.WriteConnectionSecretToReference = &runtimev1alpha1.SecretReference{\n\t\tNamespace: s3BucketClass.SpecTemplate.WriteConnectionSecretsToNamespace,\n\t\tName: string(cm.GetUID()),\n\t}\n\tspec.ProviderReference = s3BucketClass.SpecTemplate.ProviderReference\n\n\ts3Bucket.Spec = *spec\n\n\treturn nil\n}", "func NewGenericStorage(rawStorage RawStorage, serializer serializer.Serializer) Storage {\n\treturn &GenericStorage{rawStorage, serializer, patchutil.NewPatcher(serializer)}\n}", "func NewNamespace(opts ...NamespaceOption) (*Namespace, error) {\n\tns := &Namespace{\n\t\tEnvironment: azure.PublicCloud,\n\t\tamqpDial: amqp.Dial,\n\t}\n\n\tfor _, opt := range opts {\n\t\terr := opt(ns)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn ns, nil\n}", "func newGoogleStorageClient(config stow.Config) (*storage.Service, error) {\n\tjson, _ := config.Config(ConfigJSON)\n\tvar httpClient *http.Client\n\tscopes := []string{storage.DevstorageReadWriteScope}\n\tif s, ok := config.Config(ConfigScopes); ok && s != \"\" {\n\t\tscopes = strings.Split(s, \",\")\n\t}\n\tif json != \"\" {\n\t\tjwtConf, err := google.JWTConfigFromJSON([]byte(json), scopes...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = jwtConf.Client(context.Background())\n\n\t} else {\n\t\tcreds, err := google.FindDefaultCredentials(context.Background(), strings.Join(scopes, \",\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = oauth2.NewClient(context.Background(), creds.TokenSource)\n\t}\n\tservice, err := storage.New(httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service, nil\n}", "func NewStoragePluginConfig() pluggable.PluginTypeConfig {\n\treturn pluggable.PluginTypeConfig{\n\t\tInterface: crudstore.PluginInterface,\n\t\tPlugin: &crudstore.Plugin{},\n\t\tGetDefaultPluggable: func(datastore *config.Data) string {\n\t\t\treturn datastore.GetDefaultStorage()\n\t\t},\n\t\tGetPluggable: func(datastore *config.Data, name string) (pluggable.Entry, error) {\n\t\t\treturn datastore.GetStorage(name)\n\t\t},\n\t\tGetDefaultPlugin: func(datastore *config.Data) string {\n\t\t\treturn datastore.GetDefaultStoragePlugin()\n\t\t},\n\t}\n}", "func New(kubeconfig *rest.Config, opa opa_client.Data, ns types.ResourceType, name string, owner metav1.OwnerReference) *Initializer {\n\tcpy := *kubeconfig\n\tif ns.Group == \"\" {\n\t\tcpy.APIPath = \"/api\"\n\t} else {\n\t\tcpy.APIPath = \"/apis\"\n\t}\n\tcpy.GroupVersion = &schema.GroupVersion{\n\t\tGroup: ns.Group,\n\t\tVersion: ns.Version,\n\t}\n\tcpy.NegotiatedSerializer = dynamic.ContentConfig().NegotiatedSerializer\n\treturn &Initializer{\n\t\tkubeconfig: &cpy,\n\t\tname: name,\n\t\tns: ns,\n\t\topa: opa,\n\t\towner: owner,\n\t}\n}", "func InitKVStorage() *kv.LibKVBackend {\n\n\tswitch storagebackend := Get(\"EnvDefaultKVBackend\"); storagebackend {\n\tcase structs.StorageBoltDB:\n\t\treturn generateDefaultStorageBackend()\n\tcase structs.StorageConsul:\n\t\tconsul.Register()\n\t\tdb := Get(\"EnvDefaultConsulAddr\")\n\t\tkv, err := kv.NewLibKVBackend(structs.StorageConsul, \"default\", []string{db})\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"path\": db,\n\t\t\t\t\"error\": err,\n\t\t\t}).Fatal(\"failed to create new consult connection\")\n\t\t}\n\t\treturn kv\n\tdefault:\n\t\treturn generateDefaultStorageBackend()\n\t}\n}", "func WithStorageConfig(c ffs.StorageConfig) PushStorageConfigOption {\n\treturn func(r *rpc.PushStorageConfigRequest) {\n\t\tr.HasConfig = true\n\t\tr.Config = &rpc.StorageConfig{\n\t\t\tRepairable: c.Repairable,\n\t\t\tHot: toRPCHotConfig(c.Hot),\n\t\t\tCold: toRPCColdConfig(c.Cold),\n\t\t}\n\t}\n}", "func newStorageLayer(disk string) (storage StorageAPI, err error) {\n\tif !strings.ContainsRune(disk, ':') || filepath.VolumeName(disk) != \"\" {\n\t\t// Initialize filesystem storage API.\n\t\treturn newPosix(disk)\n\t}\n\t// Initialize rpc client storage API.\n\treturn newRPCClient(disk)\n}", "func NewPublishedStorage(accessKey, secretKey, region, endpoint, bucket, defaultACL, prefix,\n\tstorageClass, encryptionMethod string, plusWorkaround, disableMultiDel bool) (*PublishedStorage, error) {\n\tauth, err := aws.GetAuth(accessKey, secretKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar awsRegion aws.Region\n\n\tif endpoint == \"\" {\n\t\tvar ok bool\n\n\t\tawsRegion, ok = aws.Regions[region]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"unknown region: %#v\", region)\n\t\t}\n\t} else {\n\t\tawsRegion = aws.Region{\n\t\t\tName: region,\n\t\t\tS3Endpoint: endpoint,\n\t\t\tS3LocationConstraint: true,\n\t\t\tS3LowercaseBucket: true,\n\t\t}\n\t}\n\n\treturn NewPublishedStorageRaw(auth, awsRegion, bucket, defaultACL, prefix, storageClass, encryptionMethod,\n\t\tplusWorkaround, disableMultiDel)\n}", "func New(test ...bool) (*Controller, error) {\n\tvar c Controller\n\n\tc.bucket = \"wedgenix-app-storage\"\n\tif len(test) > 0 && test[0] {\n\t\tc.bucket = \"wedgenixtestbucket\"\n\t}\n\n\tsess, err := session.NewSession(&aws.Config{Credentials: credentials.NewEnvCredentials()})\n\tif err != nil {\n\t\treturn &c, err\n\t}\n\n\tc.c3svc = s3.New(sess)\n\n\tc.verIDs = map[string]*string{}\n\n\treturn &c, nil\n}", "func InitStorage() *storage.BucketHandle {\n\tctx := context.Background()\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create Storage client: %v\\n\", err)\n\t}\n\tbucket := client.Bucket(os.Getenv(envVarNames[evBucket]))\n\tattrs, err := bucket.Attrs(context.Background())\n\tif attrs == nil {\n\t\tlog.Fatalf(\"Bucket has not attributes...\\n\")\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get Bucket information: %v\\n\", err)\n\t}\n\treturn bucket\n}", "func NewStorage(lgr *log.Logger) *Storage {\n\treturn &Storage{\n\t\tdataStack: graph.NewStack(),\n\t\tdataStorage: NewKVStorage(),\n\t\tlgr: lgr,\n\t}\n}", "func Init(bucket string) (*GCPStorage, error) {\n\tctx := context.TODO()\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GCPStorage{client, bucket}, nil\n}", "func (s *NamespaceStorage) Insert(ctx context.Context, namespace *types.Namespace) error {\n\n\tlog.V(logLevel).Debug(\"storage:etcd:namespace:> insert namespace: %#v\", namespace)\n\n\tif err := s.checkNamespaceArgument(namespace); err != nil {\n\t\treturn err\n\t}\n\n\tclient, destroy, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"Storage: Namespace: create client err: %s\", err.Error())\n\t\treturn err\n\t}\n\tdefer destroy()\n\n\ttx := client.Begin(ctx)\n\n\tkey := keyCreate(namespaceStorage, namespace.Meta.Name, \"meta\")\n\tif err := tx.Create(key, namespace.Meta, 0); err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> insert namespace meta err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tkeySpec := keyCreate(namespaceStorage, namespace.Meta.Name, \"spec\")\n\tif err := tx.Create(keySpec, namespace.Spec, 0); err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> insert namespace spec err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> insert namespace err: %s\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *Options) GetStorageConfig() (string, error) {\n\tparams := []string{}\n\tif o.Endpoint != \"\" {\n\t\tparams = append(params, fmt.Sprintf(`endpoint = \"%s\"`, o.Endpoint))\n\t}\n\tif o.HaEnabled {\n\t\tparams = append(params, `ha_enabled = \"true\"`)\n\t}\n\tif o.Region != \"\" {\n\t\tparams = append(params, fmt.Sprintf(`region = \"%s\"`, o.Region))\n\t}\n\tif o.ReadCapacity != 0 {\n\t\tparams = append(params, fmt.Sprintf(`read_capacity = %d`, o.ReadCapacity))\n\t}\n\tif o.WriteCapacity != 0 {\n\t\tparams = append(params, fmt.Sprintf(`write_capacity = %d`, o.WriteCapacity))\n\t}\n\tif o.Table != \"\" {\n\t\tparams = append(params, fmt.Sprintf(`table = \"%s\"`, o.Table))\n\t}\n\tif o.MaxParallel != 0 {\n\t\tparams = append(params, fmt.Sprintf(`max_parallel = %d`, o.MaxParallel))\n\t}\n\n\tstorageCfg := fmt.Sprintf(dynamodbStorageFmt, strings.Join(params, \"\\n\"))\n\treturn storageCfg, nil\n}", "func Open(cfg Config) (backend.Backend, error) {\n\tdebug.Log(\"s3.Open\", \"open, config %#v\", cfg)\n\n\tclient, err := minio.New(cfg.Endpoint, cfg.KeyID, cfg.Secret, cfg.UseHTTP)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbe := &s3{client: client, bucketname: cfg.Bucket, prefix: cfg.Prefix}\n\tbe.createConnections()\n\n\tif err := client.BucketExists(cfg.Bucket); err != nil {\n\t\tdebug.Log(\"s3.Open\", \"BucketExists(%v) returned err %v, trying to create the bucket\", cfg.Bucket, err)\n\n\t\t// create new bucket with default ACL in default region\n\t\terr = client.MakeBucket(cfg.Bucket, \"\")\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn be, nil\n}", "func ConfigureS3Bucket(_ context.Context, cm resource.Claim, cs resource.Class, mg resource.Managed) error {\n\tb, cmok := cm.(*storagev1alpha1.Bucket)\n\tif !cmok {\n\t\treturn errors.Errorf(\"expected resource claim %s to be %s\", cm.GetName(), storagev1alpha1.BucketGroupVersionKind)\n\t}\n\n\trs, csok := cs.(*v1alpha3.S3BucketClass)\n\tif !csok {\n\t\treturn errors.Errorf(\"expected resource class %s to be %s\", cs.GetName(), v1alpha3.S3BucketClassGroupVersionKind)\n\t}\n\n\ts3b, mgok := mg.(*v1alpha3.S3Bucket)\n\tif !mgok {\n\t\treturn errors.Errorf(\"expected managed resource %s to be %s\", mg.GetName(), v1alpha3.S3BucketGroupVersionKind)\n\t}\n\n\tspec := &v1alpha3.S3BucketSpec{\n\t\tResourceSpec: runtimev1alpha1.ResourceSpec{\n\t\t\tReclaimPolicy: runtimev1alpha1.ReclaimRetain,\n\t\t},\n\t\tS3BucketParameters: rs.SpecTemplate.S3BucketParameters,\n\t}\n\n\tif b.Spec.PredefinedACL != nil {\n\t\tspec.CannedACL = translateACL(b.Spec.PredefinedACL)\n\t}\n\n\tif b.Spec.LocalPermission != nil {\n\t\tspec.LocalPermission = b.Spec.LocalPermission\n\t}\n\n\tspec.WriteConnectionSecretToReference = &runtimev1alpha1.SecretReference{\n\t\tNamespace: rs.SpecTemplate.WriteConnectionSecretsToNamespace,\n\t\tName: string(cm.GetUID()),\n\t}\n\tspec.ProviderReference = rs.SpecTemplate.ProviderReference.DeepCopy()\n\tspec.ReclaimPolicy = rs.SpecTemplate.ReclaimPolicy\n\n\ts3b.Spec = *spec\n\n\treturn nil\n}", "func makeStorage(name string) ds.Storage {\n\tswitch name {\n\tcase \"skiplist\":\n\t\treturn ds.NewSkipList()\n\tcase \"dict\":\n\t\treturn ds.NewDict()\n\tcase \"b-tree\":\n\t\treturn ds.InitBTree(10)\n\t}\n\treturn ds.NewDict()\n}", "func New(name, platformName, path, format string, parentUI *ui.UI, envConfig map[string]string) (*Kluster, error) {\n\tif len(format) == 0 {\n\t\tformat = DefaultFormat\n\t}\n\tif !validFormat(format) {\n\t\treturn nil, fmt.Errorf(\"invalid format %q for the kubernetes cluster config file\", format)\n\t}\n\tpath = filepath.Join(path, DefaultConfigFilename+\".\"+format)\n\n\tif _, err := os.Stat(path); os.IsExist(err) {\n\t\treturn nil, fmt.Errorf(\"the Kluster config file %q already exists\", path)\n\t}\n\n\tnewUI := parentUI.Copy()\n\n\tcluster := Kluster{\n\t\tVersion: Version,\n\t\tKind: \"cluster\",\n\t\tName: name,\n\t\tpath: path,\n\t\tui: newUI,\n\t}\n\n\t// // TODO: Improve this, all platforms are not needed\n\t// allPlatforms := provisioner.SupportedPlatforms(name, envConfig)\n\t// platform, ok := allPlatforms[platformName]\n\t// if !ok {\n\t// \treturn nil, fmt.Errorf(\"platform %q is not supported\", platformName)\n\t// }\n\n\tplatform, err := provisioner.New(name, platformName, envConfig, newUI, Version)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"platform %q is not supported. %s\", platformName, err)\n\t}\n\n\tlogPrefix := fmt.Sprintf(\"KubeKit [ %s@%s ]\", cluster.Name, platformName)\n\tcluster.ui.SetLogPrefix(logPrefix)\n\n\tcluster.Platforms = make(map[string]interface{}, 1)\n\tcluster.provisioner = make(map[string]provisioner.Provisioner, 1)\n\tcluster.State = make(map[string]*State, 1)\n\n\tcluster.Platforms[platformName] = platform.Config()\n\tcluster.provisioner[platformName] = platform\n\tcluster.State[platformName] = &State{\n\t\tStatus: AbsentStatus.String(),\n\t}\n\n\tcluster.Resources = resources.DefaultResourcesFor(platformName)\n\n\t// return if this is a platform with no configuration, such as EKS or AKS\n\tswitch platformName {\n\tcase \"eks\", \"aks\":\n\t\treturn &cluster, nil\n\t}\n\n\tcluster.Config, err = configurator.DefaultConfig(envConfig)\n\n\treturn &cluster, err\n}", "func NewStorage(client *clientv3.Client, codec codec.Codec) storage.Store {\n\treturn &Storage{\n\t\tclient: client,\n\t\tcodec: codec,\n\t}\n}", "func NewPublishedStorage(\n\taccessKey, secretKey, sessionToken, region, endpoint, bucket, defaultACL, prefix, storageClass, encryptionMethod string,\n\tplusWorkaround, disableMultiDel, forceSigV2, forceVirtualHostedStyle, debug bool) (*PublishedStorage, error) {\n\n\tconfig := &aws.Config{\n\t\tRegion: aws.String(region),\n\t}\n\n\tif endpoint != \"\" {\n\t\tconfig = config.WithEndpoint(endpoint)\n\t\tif !forceVirtualHostedStyle {\n\t\t\tconfig = config.WithS3ForcePathStyle(true)\n\t\t}\n\t}\n\n\tif accessKey != \"\" {\n\t\tconfig.Credentials = credentials.NewStaticCredentials(accessKey, secretKey, sessionToken)\n\t}\n\n\tif debug {\n\t\tconfig = config.WithLogLevel(aws.LogDebug)\n\t}\n\n\tresult, err := NewPublishedStorageRaw(bucket, defaultACL, prefix, storageClass,\n\t\tencryptionMethod, plusWorkaround, disableMultiDel, config)\n\n\tif err == nil && forceSigV2 {\n\t\tcreds := []awsauth.Credentials{}\n\n\t\tif accessKey != \"\" {\n\t\t\tcreds = append(creds, awsauth.Credentials{\n\t\t\t\tAccessKeyID: accessKey,\n\t\t\t\tSecretAccessKey: secretKey,\n\t\t\t})\n\t\t}\n\n\t\tresult.s3.Handlers.Sign.Clear()\n\t\tresult.s3.Handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler)\n\t\tresult.s3.Handlers.Sign.PushBack(func(req *request.Request) {\n\t\t\tawsauth.SignS3(req.HTTPRequest, creds...)\n\t\t})\n\t}\n\n\treturn result, err\n}", "func (s *NamespaceStorage) Get(ctx context.Context, name string) (*types.Namespace, error) {\n\n\tlog.V(logLevel).Debugf(\"storage:etcd:namespace:> get by name: %s\", name)\n\n\tconst filter = `\\b.+` + namespaceStorage + `\\/.+\\/(meta|spec)\\b`\n\n\tif len(name) == 0 {\n\t\terr := errors.New(\"name can not be empty\")\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> get by name err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tclient, destroy, err := getClient(ctx)\n\tif err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> get by name err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\tdefer destroy()\n\n\tnamespace := new(types.Namespace)\n\tkey := keyDirCreate(namespaceStorage, name)\n\n\tif err := client.Map(ctx, key, filter, namespace); err != nil {\n\t\tlog.V(logLevel).Errorf(\"storage:etcd:namespace:> get by name err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn namespace, nil\n}", "func NewStorage(mds MetadataStore, tr track.Tracker, chunks *chunk.Storage, opts ...StorageOption) *Storage {\n\ts := &Storage{\n\t\tstore: mds,\n\t\ttracker: tr,\n\t\tchunks: chunks,\n\t\tidxCache: index.NewCache(chunks, DefaultIndexCacheSize),\n\t\tmemThreshold: DefaultMemoryThreshold,\n\t\tshardConfig: &index.ShardConfig{\n\t\t\tNumFiles: index.DefaultShardNumThreshold,\n\t\t\tSizeBytes: index.DefaultShardSizeThreshold,\n\t\t},\n\t\tcompactionConfig: &CompactionConfig{\n\t\t\tLevelFactor: DefaultCompactionLevelFactor,\n\t\t},\n\t\tfilesetSem: semaphore.NewWeighted(math.MaxInt64),\n\t\tprefetchLimit: DefaultPrefetchLimit,\n\t}\n\tfor _, opt := range opts {\n\t\topt(s)\n\t}\n\tif s.compactionConfig.LevelFactor < 1 {\n\t\tpanic(\"level factor cannot be < 1\")\n\t}\n\treturn s\n}", "func GCS(cfg *config.StorageGCSConfig, loggerHandle logger.Logger) (stg Storage, err error) {\n\tloggerHandle.Debugf(\"GCS(cfg): %#v\", cfg)\n\n\tstg = &gcs{\n\t\tbucketName: cfg.Bucket,\n\t\tcredentialsJSON: cfg.CredentialsJSON,\n\t\tlog: loggerHandle,\n\t}\n\n\treturn\n}", "func NewStorage(path string) (Storage, error) {\n\tif err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {\n\t\treturn Storage{}, err\n\t}\n\n\treturn Storage{path}, nil\n}", "func newS3Client(config *S3StorageConfig) (S3Client, error) {\n\tcfg := &awsbase.Config{\n\t\tAccessKey: config.AccessKey,\n\t\tAssumeRoleARN: config.RoleARN,\n\t\tProfile: config.Profile,\n\t\tRegion: config.Region,\n\t\tSecretKey: config.SecretKey,\n\t\tSkipCredsValidation: config.SkipCredentialsValidation,\n\t\tSkipMetadataApiCheck: config.SkipMetadataAPICheck,\n\t}\n\n\tsess, err := awsbase.GetSession(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to new s3 client: %s\", err)\n\t}\n\n\tclient := s3.New(sess.Copy(&aws.Config{\n\t\tEndpoint: aws.String(config.Endpoint),\n\t\tS3ForcePathStyle: aws.Bool(config.ForcePathStyle),\n\t}))\n\n\treturn client, nil\n}", "func NewConfig() *component {\n\treturn &component{\n\t\tEnableDefaultStorageClass: true,\n\t\tEnableVolumeScheduling: true,\n\t\tEnableVolumeResizing: true,\n\t\tEnableVolumeSnapshot: true,\n\t\tReclaimPolicy: \"Retain\",\n\t}\n}", "func NewStorage(ctx context.Context, id StorageBackend, url *URL) (Storage, error) {\n\tif be, found := storageRegistry[id]; found {\n\t\treturn be.New(ctx, url)\n\t}\n\treturn nil, errors.Wrapf(ErrNotFound, \"unknown backend: %s\", url.String())\n}", "func NewStorage(t mockConstructorTestingTNewStorage) *Storage {\n\tmock := &Storage{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewStorage(t mockConstructorTestingTNewStorage) *Storage {\n\tmock := &Storage{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (s *OfflineStoreConfig) SetS3StorageConfig(v *S3StorageConfig) *OfflineStoreConfig {\n\ts.S3StorageConfig = v\n\treturn s\n}", "func newFactory() func(config *client.Config) (client.Client, *probe.Error) {\n\tclientCache := make(map[uint32]minio.CloudStorageAPI)\n\tmutex := &sync.Mutex{}\n\n\t// Return New function.\n\treturn func(config *client.Config) (client.Client, *probe.Error) {\n\t\tu := client.NewURL(config.HostURL)\n\t\ttransport := http.DefaultTransport\n\t\tif config.Debug == true {\n\t\t\tif config.Signature == \"S3v4\" {\n\t\t\t\ttransport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)\n\t\t\t}\n\t\t\tif config.Signature == \"S3v2\" {\n\t\t\t\ttransport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)\n\t\t\t}\n\t\t}\n\n\t\t// New S3 configuration.\n\t\ts3Conf := minio.Config{\n\t\t\tAccessKeyID: config.AccessKey,\n\t\t\tSecretAccessKey: config.SecretKey,\n\t\t\tTransport: transport,\n\t\t\tEndpoint: u.Scheme + u.SchemeSeparator + u.Host,\n\t\t\tSignature: func() minio.SignatureType {\n\t\t\t\tif config.Signature == \"S3v2\" {\n\t\t\t\t\treturn minio.SignatureV2\n\t\t\t\t}\n\t\t\t\treturn minio.SignatureV4\n\t\t\t}(),\n\t\t}\n\n\t\ts3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)\n\n\t\t// Generate a hash out of s3Conf.\n\t\tconfHash := fnv.New32a()\n\t\tconfHash.Write([]byte(s3Conf.Endpoint + s3Conf.AccessKeyID + s3Conf.SecretAccessKey))\n\t\tconfSum := confHash.Sum32()\n\n\t\t// Lookup previous cache by hash.\n\t\tmutex.Lock()\n\t\tdefer mutex.Unlock()\n\t\tvar api minio.CloudStorageAPI\n\t\tfound := false\n\t\tif api, found = clientCache[confSum]; !found {\n\t\t\t// Not found. Instantiate a new minio client.\n\t\t\tvar e error\n\t\t\tapi, e = minio.New(s3Conf)\n\t\t\tif e != nil {\n\t\t\t\treturn nil, probe.NewError(e)\n\t\t\t}\n\t\t\t// Cache the new minio client with hash of config as key.\n\t\t\tclientCache[confSum] = api\n\t\t}\n\n\t\ts3Clnt := &s3Client{\n\t\t\tmu: new(sync.Mutex),\n\t\t\tapi: api,\n\t\t\thostURL: u,\n\t\t\tvirtualStyle: isVirtualHostStyle(u.Host),\n\t\t}\n\t\treturn s3Clnt, nil\n\t}\n}", "func New() gocsi.StoragePluginProvider {\n\tsvc := service.New()\n\treturn &gocsi.StoragePlugin{\n\t\tController: svc,\n\t\tIdentity: svc,\n\t\tNode: svc,\n\t\tBeforeServe: svc.BeforeServe,\n\t\tRegisterAdditionalServers: svc.RegisterAdditionalServers,\n\n\t\tEnvVars: []string{\n\t\t\t// Enable request validation\n\t\t\tgocsi.EnvVarSpecReqValidation + \"=true\",\n\n\t\t\t// Enable serial volume access\n\t\t\tgocsi.EnvVarSerialVolAccess + \"=true\",\n\t\t},\n\t}\n}", "func NewStorage(l log.Logger, reg prometheus.Registerer, stCallback startTimeCallback, walDir string, flushDeadline time.Duration, sm ReadyScrapeManager) *Storage {\n\tif l == nil {\n\t\tl = log.NewNopLogger()\n\t}\n\tlogger := logging.Dedupe(l, 1*time.Minute)\n\n\ts := &Storage{\n\t\tlogger: logger,\n\t\tlocalStartTimeCallback: stCallback,\n\t}\n\ts.rws = NewWriteStorage(s.logger, reg, walDir, flushDeadline, sm)\n\treturn s\n}", "func NewS3Store(location string) (S3Store, error) {\n\ts := S3Store{Location: location}\n\tu, err := url.Parse(location)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\tif !strings.HasPrefix(u.Scheme, \"s3+http\") {\n\t\treturn s, fmt.Errorf(\"invalid scheme '%s', expected 's3+http' or 's3+https'\", u.Scheme)\n\t}\n\tvar useSSL bool\n\tif strings.HasSuffix(u.Scheme, \"s\") {\n\t\tuseSSL = true\n\t}\n\n\t// Pull the bucket as well as the prefix from a path-style URL\n\tpath := strings.Trim(u.Path, \"/\")\n\tif path == \"\" {\n\t\treturn s, fmt.Errorf(\"expected bucket name in path of '%s'\", u.Scheme)\n\t}\n\tf := strings.Split(path, \"/\")\n\ts.bucket = f[0]\n\ts.prefix = filepath.Join(f[1:]...)\n\n\t// Read creds from the environment and setup a client\n\taccessKey := os.Getenv(\"S3_ACCESS_KEY\")\n\tsecretKey := os.Getenv(\"S3_SECRET_KEY\")\n\n\ts.client, err = minio.New(u.Host, accessKey, secretKey, useSSL)\n\tif err != nil {\n\t\treturn s, errors.Wrap(err, location)\n\t}\n\n\t// Might as well confirm the bucket exists\n\tbucketExists, err := s.client.BucketExists(s.bucket)\n\tif err != nil {\n\t\treturn s, errors.Wrap(err, location)\n\t}\n\tif !bucketExists {\n\t\treturn s, fmt.Errorf(\"bucket '%s' does not exist in %s\", s.bucket, location)\n\t}\n\treturn s, nil\n}", "func NewStorage(cfg *Config) *Storage {\n\tif cfg.Engine == nil {\n\t\tlog.Fatalln(\"Cannot create a ops proxy without an engine\")\n\t}\n\tif cfg.App == nil {\n\t\tnrConfig := newrelic.NewConfig(\"widget\", \"\")\n\t\tnrConfig.Enabled = false\n\t\tapp, err := newrelic.NewApplication(nrConfig)\n\t\tif err != nil {\n\t\t\tlogrus.WithField(\"error\", err).Fatalln(\"could not create dummy new relic app\")\n\t\t}\n\t\tcfg.App = app\n\t}\n\treturn &Storage{engine: cfg.Engine, newrelic: cfg.App}\n}", "func newStorage() *storage {\n\tr := make(map[string][]byte)\n\treturn &storage{\n\t\trepository: r,\n\t}\n}", "func NewStorage(cfg *configuration.Storage, timeout time.Duration) (*Storage, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.URI))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connect to mongo %s: %s\", cfg.URI, err)\n\t}\n\n\terr = client.Ping(ctx, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ping mongo %s: %s\", cfg.URI, err)\n\t}\n\n\treturn &Storage{\n\t\tclient: client,\n\t\tcollection: client.Database(cfg.DBName).Collection(cfg.CollectionName),\n\t}, nil\n}", "func (s storageBucketNamespaceLister) Get(name string) (*v1beta1.StorageBucket, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound(v1beta1.Resource(\"storagebucket\"), name)\n\t}\n\treturn obj.(*v1beta1.StorageBucket), nil\n}", "func (s *storageBucketLister) StorageBuckets(namespace string) StorageBucketNamespaceLister {\n\treturn storageBucketNamespaceLister{indexer: s.indexer, namespace: namespace}\n}", "func NewEtcdStorage(t *testing.T) (*storagebackend.Config, *etcdtesting.EtcdTestServer) {\n\tserver, config := etcdtesting.NewUnsecuredEtcd3TestClientServer(t)\n\tmediaType, _, err := mime.ParseMediaType(runtime.ContentTypeJSON)\n\tif err != nil {\n\t\tt.Errorf(\"failed to parse media type: %v\", err)\n\t}\n\tstorageSerializer, ok := runtime.SerializerInfoForMediaType(api.Codecs.SupportedMediaTypes(), mediaType)\n\tif !ok {\n\t\tt.Errorf(\"no serializer for %s\", mediaType)\n\t}\n\ts := storageSerializer.Serializer\n\tds := recognizer.NewDecoder(s, api.Codecs.UniversalDeserializer())\n\tconfig.Codec = api.Codecs.CodecForVersions(s, ds, schema.GroupVersions{coapi.SchemeGroupVersion}, nil)\n\treturn config, server\n}", "func NewStorage() Storage {\n\treturn &storage{}\n}", "func NewStorage(cat *repository.MongoCatalog, cache *rediscache.Redis) *Storage {\n\treturn &Storage{\n\t\tcat,\n\t\tcache,\n\t}\n}", "func NewStow() *Stow {\n\tendpoint := os.Getenv(\"AWS_S3_ENDPOINT\")\n\tid := env.Get(\"AWS_ACCESS_KEY_ID\", os.Getenv(\"AWS_ACCESS_KEY\"))\n\tsecret := env.Get(\"AWS_SECRET_ACCESS_KEY\", os.Getenv(\"AWS_SECRET_KEY\"))\n\tregion := env.Get(\"AWS_REGION\", \"eu-west-1\")\n\tbucket := env.Get(\"AWS_S3_BUCKET\", \"pandora\")\n\n\t// TODO enable aws debug logging\n\tkind := \"s3\"\n\tconfig := stow.ConfigMap{\n\t\ts3.ConfigEndpoint: endpoint,\n\t\ts3.ConfigAccessKeyID: id,\n\t\ts3.ConfigSecretKey: secret,\n\t\ts3.ConfigRegion: region,\n\t\ts3.ConfigDisableSSL: \"true\",\n\t}\n\treturn &Stow{\n\t\tkind: kind,\n\t\tconfig: config,\n\t\tbucket: bucket,\n\t}\n}", "func newGoogleStorageStore(config *GoogleStorageStoreConfig) (*googleStorageStore, error) {\n\tif config.Bucket == \"\" {\n\t\treturn nil, errors.New(\"bucket required\")\n\t}\n\n\tvar opts []option.ClientOption\n\tvar noAuth bool\n\tcredsPath := getGoogleCredsPath()\n\tif credsPath == \"\" {\n\t\tnoAuth = true\n\t\topts = append(opts, option.WithoutAuthentication())\n\t} else {\n\t\topts = append(opts, option.WithCredentialsFile(credsPath), option.WithScopes(storage.ScopeFullControl))\n\t}\n\n\tvar httpTransport http.Transport\n\tvar err error\n\tctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: &httpTransport})\n\tgcpTransport, err := gcphttp.NewTransport(ctx, &httpTransport, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpClient := &http.Client{Transport: gcpTransport}\n\tclientOpt := option.WithHTTPClient(httpClient)\n\tclient, err := storage.NewClient(context.Background(), clientOpt)\n\tif err != nil {\n\t\thttpTransport.CloseIdleConnections()\n\t\tif noAuth {\n\t\t\treturn nil, errors.Wrap(err, 0)\n\t\t}\n\t\thttpClient.Transport, err = gcphttp.NewTransport(ctx, &httpTransport, option.WithoutAuthentication())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclient, err = storage.NewClient(context.Background(), clientOpt)\n\t\tif err != nil {\n\t\t\thttpTransport.CloseIdleConnections()\n\t\t\treturn nil, errors.Wrap(err, 0)\n\t\t}\n\t}\n\n\treturn &googleStorageStore{\n\t\tclient: client,\n\t\tbucket: client.Bucket(config.Bucket),\n\t\thttpTransport: &httpTransport,\n\t}, nil\n}", "func NewStorageAPI(g func(ctx context.Context) (*grpc.ClientConn, error)) *StorageAPI {\n\treturn &StorageAPI{g}\n}", "func NewStorageListOptions() *StorageListOptions {\n\treturn &StorageListOptions{}\n}", "func NewDefault() *Config {\n\tname := fmt.Sprintf(\"ec2-%s-%s\", getTS()[:10], randutil.String(12))\n\tif v := os.Getenv(AWS_K8S_TESTER_EC2_PREFIX + \"NAME\"); v != \"\" {\n\t\tname = v\n\t}\n\treturn &Config{\n\t\tmu: new(sync.RWMutex),\n\n\t\tUp: false,\n\t\tDeletedResources: make(map[string]string),\n\n\t\tName: name,\n\t\tPartition: endpoints.AwsPartitionID,\n\t\tRegion: endpoints.UsWest2RegionID,\n\n\t\t// to be auto-generated\n\t\tConfigPath: \"\",\n\t\tRemoteAccessCommandsOutputPath: \"\",\n\n\t\tLogColor: true,\n\t\tLogColorOverride: \"\",\n\n\t\tLogLevel: logutil.DefaultLogLevel,\n\t\t// default, stderr, stdout, or file name\n\t\t// log file named with cluster name will be added automatically\n\t\tLogOutputs: []string{\"stderr\"},\n\n\t\tOnFailureDelete: true,\n\t\tOnFailureDeleteWaitSeconds: 120,\n\n\t\tS3: getDefaultS3(),\n\t\tRole: getDefaultRole(),\n\t\tVPC: getDefaultVPC(),\n\t\tRemoteAccessKeyCreate: true,\n\t\tRemoteAccessPrivateKeyPath: filepath.Join(os.TempDir(), randutil.String(10)+\".insecure.key\"),\n\n\t\tASGsFetchLogs: true,\n\t\tASGs: map[string]ASG{\n\t\t\tname + \"-asg\": {\n\t\t\t\tName: name + \"-asg\",\n\t\t\t\tSSM: &SSM{\n\t\t\t\t\tDocumentCreate: false,\n\t\t\t\t\tDocumentName: \"\",\n\t\t\t\t\tDocumentCommands: \"\",\n\t\t\t\t\tDocumentExecutionTimeoutSeconds: 3600,\n\t\t\t\t},\n\t\t\t\tRemoteAccessUserName: \"ec2-user\", // for AL2\n\t\t\t\tAMIType: AMITypeAL2X8664,\n\t\t\t\tImageID: \"\",\n\t\t\t\tImageIDSSMParameter: \"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\",\n\t\t\t\tInstanceType: DefaultNodeInstanceTypeCPU,\n\t\t\t\tVolumeSize: DefaultNodeVolumeSize,\n\t\t\t\tASGMinSize: 1,\n\t\t\t\tASGMaxSize: 1,\n\t\t\t\tASGDesiredCapacity: 1,\n\t\t\t},\n\t\t},\n\t}\n}", "func SetStorageConfig(cr config.Reader) StorageOption {\n\treturn func(s *Storage) { s.cr = cr }\n}" ]
[ "0.63567257", "0.6230881", "0.60596675", "0.5861226", "0.5835127", "0.57842094", "0.5706375", "0.5677003", "0.56734043", "0.5671543", "0.56431067", "0.56058097", "0.55307925", "0.5496921", "0.5466971", "0.54075783", "0.5371226", "0.5356307", "0.5315504", "0.527059", "0.5255381", "0.524933", "0.5241069", "0.52370757", "0.5185947", "0.5165296", "0.5156196", "0.5145774", "0.51400524", "0.51149446", "0.5086559", "0.5039416", "0.50179553", "0.50120664", "0.49838933", "0.49788252", "0.4962872", "0.4936098", "0.49296004", "0.4920716", "0.49197307", "0.49092063", "0.49028134", "0.4902514", "0.4877706", "0.4877706", "0.48762918", "0.48755658", "0.48649502", "0.48419717", "0.48416728", "0.4835412", "0.48070312", "0.480318", "0.4799662", "0.4777789", "0.4776015", "0.47753373", "0.47723675", "0.47720823", "0.4762762", "0.4761042", "0.47560617", "0.47537786", "0.47535253", "0.47507784", "0.47486782", "0.47428703", "0.47351807", "0.47169968", "0.47158754", "0.47124368", "0.4704491", "0.4704257", "0.46995077", "0.46959475", "0.4693501", "0.4684998", "0.46787843", "0.46778154", "0.46778154", "0.46703947", "0.46651253", "0.46643057", "0.46639758", "0.46620238", "0.46602482", "0.46574247", "0.46563026", "0.46552914", "0.46543926", "0.46524855", "0.46521792", "0.4636976", "0.46350056", "0.46340838", "0.4623305", "0.46227464", "0.46212912", "0.46175665" ]
0.779615
0
Equals returns true if the given StorageConfig's are the same.
func (sc StorageConfig) Equals(other StorageConfig) bool { return reflect.DeepEqual(sc, other) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c Config) Equal(rhs Config) bool {\n\n\tif len(c.Addresses) != len(rhs.Addresses) {\n\t\treturn false\n\t}\n\tfor i := range c.Addresses {\n\t\tif c.Addresses[i] != rhs.Addresses[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(c.Middlewares) != len(rhs.Middlewares) {\n\t\treturn false\n\t}\n\tfor i := range c.Middlewares {\n\t\tif c.Middlewares[i] != rhs.Middlewares[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn c.PacketSize == rhs.PacketSize\n}", "func (c Config) Equals(another Config) bool {\n\tpathEquals := c.Filepath == another.Filepath\n\tdpEquals := c.DownloadsPath == another.DownloadsPath\n\ttpEquals := c.TargetBasePath == another.TargetBasePath\n\n\treturn pathEquals && dpEquals && tpEquals\n}", "func (e1 *Config) Equal(e2 *Config) bool {\n\tif e1 == e2 {\n\t\treturn true\n\t}\n\tif e1 == nil || e2 == nil {\n\t\treturn false\n\t}\n\tif e1.InfluxDBEnabled != e2.InfluxDBEnabled {\n\t\treturn false\n\t}\n\tif e1.InfluxDBPort != e2.InfluxDBPort {\n\t\treturn false\n\t}\n\tif e1.InfluxDBHost != e2.InfluxDBHost {\n\t\treturn false\n\t}\n\tif e1.InfluxDBServerName != e2.InfluxDBServerName {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (e1 *Config) Equal(e2 *Config) bool {\n\tif e1 == e2 {\n\t\treturn true\n\t}\n\tif e1 == nil || e2 == nil {\n\t\treturn false\n\t}\n\tif e1.URL != e2.URL {\n\t\treturn false\n\t}\n\tif e1.Host != e2.Host {\n\t\treturn false\n\t}\n\tif e1.SigninURL != e2.SigninURL {\n\t\treturn false\n\t}\n\tif e1.SigninURLRedirectParam != e2.SigninURLRedirectParam {\n\t\treturn false\n\t}\n\tif e1.Method != e2.Method {\n\t\treturn false\n\t}\n\n\tmatch := sets.StringElementsMatch(e1.ResponseHeaders, e2.ResponseHeaders)\n\tif !match {\n\t\treturn false\n\t}\n\n\tif e1.RequestRedirect != e2.RequestRedirect {\n\t\treturn false\n\t}\n\tif e1.AuthSnippet != e2.AuthSnippet {\n\t\treturn false\n\t}\n\n\tif e1.AuthCacheKey != e2.AuthCacheKey {\n\t\treturn false\n\t}\n\n\tif e1.KeepaliveConnections != e2.KeepaliveConnections {\n\t\treturn false\n\t}\n\n\tif e1.KeepaliveShareVars != e2.KeepaliveShareVars {\n\t\treturn false\n\t}\n\n\tif e1.KeepaliveRequests != e2.KeepaliveRequests {\n\t\treturn false\n\t}\n\n\tif e1.KeepaliveTimeout != e2.KeepaliveTimeout {\n\t\treturn false\n\t}\n\n\tif e1.AlwaysSetCookie != e2.AlwaysSetCookie {\n\t\treturn false\n\t}\n\n\treturn sets.StringElementsMatch(e1.AuthCacheDuration, e2.AuthCacheDuration)\n}", "func (l1 *Config) Equal(l2 *Config) bool {\n\tif l1 == l2 {\n\t\treturn true\n\t}\n\tif l1 == nil || l2 == nil {\n\t\treturn false\n\t}\n\tif l1.BodySize != l2.BodySize {\n\t\treturn false\n\t}\n\tif l1.ReadTimeout != l2.ReadTimeout {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c Config) Equal(rhs Config) bool {\n\treturn (c.Dir == rhs.Dir &&\n\t\tc.ValueDir == rhs.ValueDir)\n}", "func (c Config) Equal(rhs Config) bool {\n\treturn c == rhs\n}", "func (k *Config) Equal(other *Config) bool {\n\treturn other != nil && *k == *other\n}", "func (c1 *Config) Equal(c2 *Config) bool {\n\tif c1.Mode != c2.Mode {\n\t\treturn false\n\t}\n\treturn true\n}", "func (conf *Config) Equals(other *Config) bool {\n\tif !conf.UnicastConfig.Equals(other.UnicastConfig) {\n\t\treturn false\n\t}\n\tif !conf.ExtensionConfig.Equals(other.ExtensionConfig) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (lhs OSConfig) Equal(rhs OSConfig) bool {\n\tif len(lhs.Nameservers) != len(rhs.Nameservers) {\n\t\treturn false\n\t}\n\n\tif len(lhs.Domains) != len(rhs.Domains) {\n\t\treturn false\n\t}\n\n\t// With how we perform resolution order shouldn't matter,\n\t// but it is unlikely that we will encounter different orders.\n\tfor i, server := range lhs.Nameservers {\n\t\tif rhs.Nameservers[i] != server {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// The order of domains, on the other hand, is significant.\n\tfor i, domain := range lhs.Domains {\n\t\tif rhs.Domains[i] != domain {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (flogs *fileLogs) Equal(config dvid.StoreConfig) bool {\n\tpath, _, err := parseConfig(config)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn path == flogs.path\n}", "func (in *EnvoyConfig) DeepEqual(other *EnvoyConfig) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif in.Kind != other.Kind {\n\t\treturn false\n\t}\n\tif in.Name != other.Name {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (c *Configuration) EqualsTo(c1 *Configuration) bool {\n\treturn reflect.DeepEqual(c, c1)\n}", "func (b *BaseATNConfig) Equals(o Collectable[ATNConfig]) bool {\n\tif b == o {\n\t\treturn true\n\t} else if o == nil {\n\t\treturn false\n\t}\n\n\tvar other, ok = o.(*BaseATNConfig)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tvar equal bool\n\n\tif b.context == nil {\n\t\tequal = other.context == nil\n\t} else {\n\t\tequal = b.context.Equals(other.context)\n\t}\n\n\tvar (\n\t\tnums = b.state.GetStateNumber() == other.state.GetStateNumber()\n\t\talts = b.alt == other.alt\n\t\tcons = b.semanticContext.Equals(other.semanticContext)\n\t\tsups = b.precedenceFilterSuppressed == other.precedenceFilterSuppressed\n\t)\n\n\treturn nums && alts && cons && sups && equal\n}", "func instanceConfigEqual(current, desired *InstanceConfig) bool {\n\tif current.UserData != desired.UserData {\n\t\treturn false\n\t}\n\n\tif current.ImageID != desired.ImageID {\n\t\treturn false\n\t}\n\n\t// TODO: explain\n\tfor k, v := range desired.Tags {\n\t\tif currentValue, ok := current.Tags[k]; !ok || v != currentValue {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c *ServiceConfig) IsEqual(other *ServiceConfig) bool {\n\tif c.RestartLimitInterval != other.RestartLimitInterval ||\n\t\tc.Chroot != other.Chroot ||\n\t\tc.Disabled != other.Disabled ||\n\t\tlen(c.GetStartArgs()) != len(other.GetStartArgs()) ||\n\t\tlen(c.Env) != len(other.Env) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(c.GetStartArgs()); i++ {\n\t\tif c.GetStartArgs()[i] != other.GetStartArgs()[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor k, v := range c.Env {\n\t\tif other.Env[k] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor k, v := range other.Env {\n\t\tif c.Env[k] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c *ConfigRelation) Equals(other *ConfigRelation) bool {\n\treturn c.Type == other.Type && c.Field == other.Field && c.ForeignTable == other.ForeignTable && c.ForeignField == other.ForeignField\n}", "func (fOpenCfg *FileOpenConfig) Equal(fOpStat2 *FileOpenConfig) bool {\n\n if fOpenCfg.fileOpenModes == nil {\n fOpenCfg.fileOpenModes = make([]FileOpenMode, 0)\n }\n\n if fOpStat2.fileOpenModes == nil {\n fOpStat2.fileOpenModes = make([]FileOpenMode, 0)\n }\n\n if fOpenCfg.isInitialized != fOpStat2.isInitialized {\n return false\n }\n\n lenfOpStat1 := len(fOpenCfg.fileOpenModes)\n\n lenfOpStat2 := len(fOpStat2.fileOpenModes)\n\n if lenfOpStat1 != lenfOpStat2 {\n return false\n }\n\n if fOpenCfg.fileOpenType != fOpStat2.fileOpenType {\n return false\n }\n\n for i := 0; i < lenfOpStat1; i++ {\n isFound := false\n\n for j := 0; j < lenfOpStat1; j++ {\n if fOpStat2.fileOpenModes[j] == fOpenCfg.fileOpenModes[i] {\n isFound = true\n }\n }\n\n if !isFound {\n return false\n }\n }\n\n return true\n}", "func (cfg *Defaults) Equals(other *Defaults) bool {\n\tif cfg == nil && other == nil {\n\t\treturn true\n\t}\n\n\tif cfg == nil || other == nil {\n\t\treturn false\n\t}\n\n\treturn other.DefaultCloudEventsSink == cfg.DefaultCloudEventsSink\n}", "func (k Kconfig) KconfigEqual(other Kconfig) bool {\n\treturn reflect.DeepEqual(k.Spec, other.Spec)\n}", "func (ndb *Ndb) IsConfigHashEqual() (string, bool, error) {\n\n\tconfigHash, err := ndb.calculateNewConfigHash()\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\tif ndb.Status.ReceivedConfigHash == \"\" {\n\t\treturn configHash, false, nil\n\t}\n\tif ndb.Status.ReceivedConfigHash != configHash {\n\t\treturn configHash, false, nil\n\t}\n\treturn configHash, true, nil\n}", "func (t TxPublish) Equals(that TxPublish) bool {\n\treturn t.Name == that.Name &&\n\t\tt.Size == that.Size &&\n\t\ttools.BytesToHexString(t.MetafileHash) == tools.BytesToHexString(that.MetafileHash)\n}", "func (s Secret) Equal(a Secret) bool {\n\tswitch {\n\tcase len(s.Previous) != len(a.Previous):\n\t\treturn false\n\tcase !bytes.Equal(s.Current, a.Current):\n\t\treturn false\n\t}\n\tfor i, blob := range s.Previous {\n\t\tif !bytes.Equal(blob, a.Previous[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func configsAreEqual(config1, config2 *ServiceAliasConfig) bool {\n\treturn config1.Name == config2.Name &&\n\t\tconfig1.Namespace == config2.Namespace &&\n\t\tconfig1.Host == config2.Host &&\n\t\tconfig1.Path == config2.Path &&\n\t\tconfig1.TLSTermination == config2.TLSTermination &&\n\t\treflect.DeepEqual(config1.Certificates, config2.Certificates) &&\n\t\t// Status isn't compared since whether certs have been written\n\t\t// to disk or not isn't relevant in determining whether a\n\t\t// route needs to be updated.\n\t\tconfig1.PreferPort == config2.PreferPort &&\n\t\tconfig1.InsecureEdgeTerminationPolicy == config2.InsecureEdgeTerminationPolicy &&\n\t\tconfig1.RoutingKeyName == config2.RoutingKeyName &&\n\t\tconfig1.IsWildcard == config2.IsWildcard &&\n\t\tconfig1.VerifyServiceHostname == config2.VerifyServiceHostname &&\n\t\treflect.DeepEqual(config1.HTTPResponseHeaders, config2.HTTPResponseHeaders) &&\n\t\treflect.DeepEqual(config1.HTTPRequestHeaders, config2.HTTPRequestHeaders) &&\n\t\treflect.DeepEqual(config1.Annotations, config2.Annotations) &&\n\t\treflect.DeepEqual(config1.ServiceUnits, config2.ServiceUnits)\n}", "func (s StorageClass) EqualTo(storageClass string) bool {\n\treturn strings.EqualFold(storageClass, s.String())\n}", "func (config *SysConfig) IsDifferentConfig(origin *SysConfig) bool {\n\tif strings.EqualFold(config.Host, origin.Host) && strings.EqualFold(config.Auth, origin.Auth) &&\n\t\tstrings.EqualFold(config.Healthz, origin.Healthz) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (sf *StoredFrags) Equal(sf2 *StoredFrags) bool {\n\tif len(sf.Frags) != len(sf2.Frags) {\n\t\treturn false\n\t}\n\tfor i, n := range sf.Frags {\n\t\tif sf2.Frags[i] != n {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (info *endpointsInfo) Equal(other proxy.Endpoint) bool {\n\treturn info.String() == other.String() && info.GetIsLocal() == other.GetIsLocal()\n}", "func (g *Graph) Equal(g2 *Graph, debug bool) bool {\n\n\t// Check the vertices\n\tkeys1 := g.listOfKeys()\n\tkeys2 := g2.listOfKeys()\n\n\tif !SlicesHaveSameElements(&keys1, &keys2) {\n\t\tif debug {\n\t\t\tlog.Println(\"Lists of keys are different\")\n\t\t\tlog.Printf(\"Keys1: %v\\n\", keys1)\n\t\t\tlog.Printf(\"Keys2: %v\\n\", keys2)\n\t\t}\n\t\treturn false\n\t}\n\n\t// Walk through each vertex and check its connections\n\tfor _, vertex := range keys1 {\n\t\tconns1 := g.Nodes[vertex]\n\t\tconns2 := g2.Nodes[vertex]\n\n\t\tif !SetsEqual(conns1, conns2) {\n\t\t\tif debug {\n\t\t\t\tlog.Printf(\"Connections different for vertex %v\", vertex)\n\t\t\t\tlog.Printf(\"Connections 1: %v\\n\", conns1)\n\t\t\t\tlog.Printf(\"Connections 2: %v\\n\", conns2)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (b *BrokerQueue) Equals(other BrokerEntity) bool {\n\treturn b.Type() == other.Type() &&\n\t\tb.Name == other.GetName()\n}", "func (s *StorageSuite) TestServersEquality(c *check.C) {\n\tservers := Servers{{\n\t\tAdvertiseIP: \"192.168.1.1\",\n\t\tHostname: \"node-1\",\n\t\tRole: \"worker\",\n\t}}\n\ttestCases := []struct {\n\t\tservers Servers\n\t\tresult bool\n\t\tcomment string\n\t}{\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\tHostname: \"node-1\",\n\t\t\t\tRole: \"worker\",\n\t\t\t}},\n\t\t\tresult: true,\n\t\t\tcomment: \"Servers should be equal\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{\n\t\t\t\t{\n\t\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\t\tHostname: \"node-1\",\n\t\t\t\t\tRole: \"worker\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAdvertiseIP: \"192.168.1.2\",\n\t\t\t\t\tHostname: \"node-2\",\n\t\t\t\t\tRole: \"worker\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different number of servers\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.2\",\n\t\t\t\tHostname: \"node-1\",\n\t\t\t\tRole: \"worker\",\n\t\t\t}},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different IPs\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\tHostname: \"node-2\",\n\t\t\t\tRole: \"worker\",\n\t\t\t}},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different hostnames\",\n\t\t},\n\t\t{\n\t\t\tservers: Servers{{\n\t\t\t\tAdvertiseIP: \"192.168.1.1\",\n\t\t\t\tHostname: \"node-1\",\n\t\t\t\tRole: \"db\",\n\t\t\t}},\n\t\t\tresult: false,\n\t\t\tcomment: \"Servers should not be equal: different roles\",\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tc.Assert(servers.IsEqualTo(tc.servers), check.Equals, tc.result,\n\t\t\tcheck.Commentf(tc.comment))\n\t}\n}", "func (tc *TestConfig) Equal(source interface{}, target interface{}) bool {\n\tvar a, b float64\n\tswitch source.(type) {\n\tcase int:\n\t\ta = float64(source.(int))\n\tcase float64:\n\t\ta = float64(source.(float64))\n\tdefault:\n\t\treturn false\n\t}\n\n\tswitch target.(type) {\n\tcase int:\n\t\tb = float64(target.(int))\n\tcase float64:\n\t\tb = float64(target.(float64))\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn (a == b)\n}", "func (s BlobSet) Equals(other BlobSet) bool {\n\tif len(s) != len(other) {\n\t\treturn false\n\t}\n\n\tfor h := range s {\n\t\tif _, ok := other[h]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecPool) Equals(other *ParamSpecPool) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (cfg *HeartbeatConfig) Equal(other *HeartbeatConfig) error {\n\tif other.updateInterval != 0 && other.updateInterval != cfg.updateInterval {\n\t\treturn terror.ErrSyncerUnitHeartbeatCheckConfig.Generatef(\"updateInterval not equal, self: %d, other: %d\", cfg.updateInterval, other.updateInterval)\n\t}\n\tif other.reportInterval != 0 && other.reportInterval != cfg.reportInterval {\n\t\treturn terror.ErrSyncerUnitHeartbeatCheckConfig.Generatef(\"reportInterval not equal, self: %d, other: %d\", cfg.reportInterval, other.reportInterval)\n\t}\n\tif cfg.serverID != other.serverID {\n\t\treturn terror.ErrSyncerUnitHeartbeatCheckConfig.Generatef(\"serverID not equal, self: %d, other: %d\", cfg.serverID, other.serverID)\n\t}\n\tif !reflect.DeepEqual(cfg.masterCfg, other.masterCfg) {\n\t\treturn terror.ErrSyncerUnitHeartbeatCheckConfig.Generatef(\"masterCfg not equal, self: %+v, other: %+v\", cfg.masterCfg, other.masterCfg)\n\t}\n\treturn nil\n}", "func (s L4Service) Equal(s2 L4Service) bool {\n\tif len(s.Endpoints) != len(s2.Endpoints) {\n\t\treturn false\n\t}\n\tfor _, s1e := range s.Endpoints {\n\t\tfound := false\n\t\tfor _, s2e := range s2.Endpoints {\n\t\t\tif reflect.DeepEqual(s1e, s2e) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\ts.Endpoints = nil\n\ts2.Endpoints = nil\n\n\treturn reflect.DeepEqual(s, s2)\n}", "func (v SigningPayload) Equal(o SigningPayload) bool {\n\treturn v.AccountIdentifier.Value.Equal(o.AccountIdentifier.Value) &&\n\t\tv.AccountIdentifier.Set == o.AccountIdentifier.Set &&\n\t\tv.Address.Value == o.Address.Value &&\n\t\tv.Address.Set == o.Address.Set &&\n\t\tstring(v.Bytes) == string(o.Bytes) &&\n\t\tv.SignatureType.Value == o.SignatureType.Value &&\n\t\tv.SignatureType.Set == o.SignatureType.Set\n}", "func (sh *SecretHashes) Equal(other *SecretHashes) bool {\n\tif sh == nil || other == nil {\n\t\treturn false\n\t} else if sh == other {\n\t\treturn true\n\t}\n\n\treturn sh.AuthJWT == other.AuthJWT &&\n\t\tsh.RocksDBEncryptionKey == other.RocksDBEncryptionKey &&\n\t\tsh.TLSCA == other.TLSCA &&\n\t\tsh.SyncTLSCA == other.SyncTLSCA\n}", "func (a *Advertisement) Equal(b *Advertisement) bool {\n\tif a.Prefix.String() != b.Prefix.String() {\n\t\treturn false\n\t}\n\tif a.LocalPref != b.LocalPref {\n\t\treturn false\n\t}\n\treturn reflect.DeepEqual(a.Communities, b.Communities)\n}", "func (p *Parameters) Equals(other *Parameters) bool {\n\tif p == other {\n\t\treturn true\n\t}\n\treturn p.N == other.N && EqualSlice(p.Qi, other.Qi) && EqualSlice(p.Pi, other.Pi) && p.Sigma == other.Sigma\n}", "func testEqual(a, b *lbConfig) bool {\n\treturn a.lookupService == b.lookupService &&\n\t\ta.lookupServiceTimeout == b.lookupServiceTimeout &&\n\t\ta.maxAge == b.maxAge &&\n\t\ta.staleAge == b.staleAge &&\n\t\ta.cacheSizeBytes == b.cacheSizeBytes &&\n\t\ta.defaultTarget == b.defaultTarget &&\n\t\ta.controlChannelServiceConfig == b.controlChannelServiceConfig &&\n\t\ta.childPolicyName == b.childPolicyName &&\n\t\ta.childPolicyTargetField == b.childPolicyTargetField &&\n\t\tchildPolicyConfigEqual(a.childPolicyConfig, b.childPolicyConfig)\n}", "func (e IfChange) Equal(e2 IfChange) bool {\n\treturn e.Added == e2.Added &&\n\t\te.Deleted == e2.Deleted &&\n\t\te.Attrs.Equal(e2.Attrs)\n}", "func (gs GenesisState) Equal(gs2 GenesisState) bool {\n\tb1 := ModuleCdc.MustMarshalBinaryBare(&gs)\n\tb2 := ModuleCdc.MustMarshalBinaryBare(&gs2)\n\treturn bytes.Equal(b1, b2)\n}", "func sameUnderlyingStorage(x, y []byte) bool {\n\treturn &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]\n}", "func (l *LexerATNConfig) Equals(other Collectable[ATNConfig]) bool {\n\tif l == other {\n\t\treturn true\n\t}\n\tvar othert, ok = other.(*LexerATNConfig)\n\n\tif l == other {\n\t\treturn true\n\t} else if !ok {\n\t\treturn false\n\t} else if l.passedThroughNonGreedyDecision != othert.passedThroughNonGreedyDecision {\n\t\treturn false\n\t}\n\n\tvar b bool\n\n\tif l.lexerActionExecutor != nil {\n\t\tb = !l.lexerActionExecutor.Equals(othert.lexerActionExecutor)\n\t} else {\n\t\tb = othert.lexerActionExecutor != nil\n\t}\n\n\tif b {\n\t\treturn false\n\t}\n\n\treturn l.BaseATNConfig.Equals(othert.BaseATNConfig)\n}", "func (mm MoneyMarket) Equal(mmCompareTo MoneyMarket) bool {\n\tif mm.Denom != mmCompareTo.Denom {\n\t\treturn false\n\t}\n\tif !mm.BorrowLimit.Equal(mmCompareTo.BorrowLimit) {\n\t\treturn false\n\t}\n\tif mm.SpotMarketID != mmCompareTo.SpotMarketID {\n\t\treturn false\n\t}\n\tif !mm.ConversionFactor.Equal(mmCompareTo.ConversionFactor) {\n\t\treturn false\n\t}\n\tif !mm.InterestRateModel.Equal(mmCompareTo.InterestRateModel) {\n\t\treturn false\n\t}\n\tif !mm.ReserveFactor.Equal(mmCompareTo.ReserveFactor) {\n\t\treturn false\n\t}\n\tif !mm.AuctionSize.Equal(mmCompareTo.AuctionSize) {\n\t\treturn false\n\t}\n\tif !mm.KeeperRewardPercentage.Equal(mmCompareTo.KeeperRewardPercentage) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (gs GenesisState) Equal(gs2 GenesisState) bool {\n\tb1 := ModuleCdc.MustMarshalBinaryBare(gs)\n\tb2 := ModuleCdc.MustMarshalBinaryBare(gs2)\n\treturn bytes.Equal(b1, b2)\n}", "func (b Bytes32) Equal(o Bytes32) bool { return bytes.Equal(b.Bytes(), o.Bytes()) }", "func (dom Domain) Equal(b ConfItem) bool {\n\tif item, ok := b.(*Domain); ok {\n\t\treturn dom.Name == item.Name\n\t}\n\treturn false\n}", "func (k1 *KeyAuth) Equal(k2 *KeyAuth) bool {\n\treturn reflect.DeepEqual(k1.KeyAuth, k2.KeyAuth)\n}", "func (v *Values) Equal(other *Values) bool {\n\tv.lock.RLock()\n\tdefer v.lock.RUnlock()\n\tother.lock.RLock()\n\tdefer other.lock.RUnlock()\n\n\treturn v.root.equal(other.root)\n}", "func (info *BaseEndpointInfo) Equal(other Endpoint) bool {\n\treturn info.String() == other.String() && info.GetIsLocal() == other.GetIsLocal()\n}", "func (s *Store) Equals(other *Store) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\treturn s.Path() == other.Path()\n}", "func (s *Store) Equals(other *Store) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\treturn s.path == other.path\n}", "func (recv *ParamSpecValueArray) Equals(other *ParamSpecValueArray) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (v SubNetworkIdentifier) Equal(o SubNetworkIdentifier) bool {\n\treturn string(v.Metadata) == string(o.Metadata) &&\n\t\tv.Network == o.Network\n}", "func sameConfigDB(loggerOne, loggerTwo backend.JSONConfigurationDB) bool {\n\treturn (loggerOne.Host == loggerTwo.Host) && (loggerOne.Port == loggerTwo.Port) && (loggerOne.Name == loggerTwo.Name)\n}", "func (s Balance) Equal(t Balance, opts ...Options) bool {\n\tif !equalPointers(s.Algorithm, t.Algorithm) {\n\t\treturn false\n\t}\n\n\tif s.HashExpression != t.HashExpression {\n\t\treturn false\n\t}\n\n\tif s.HdrName != t.HdrName {\n\t\treturn false\n\t}\n\n\tif s.HdrUseDomainOnly != t.HdrUseDomainOnly {\n\t\treturn false\n\t}\n\n\tif s.RandomDraws != t.RandomDraws {\n\t\treturn false\n\t}\n\n\tif s.RdpCookieName != t.RdpCookieName {\n\t\treturn false\n\t}\n\n\tif s.URIDepth != t.URIDepth {\n\t\treturn false\n\t}\n\n\tif s.URILen != t.URILen {\n\t\treturn false\n\t}\n\n\tif s.URIPathOnly != t.URIPathOnly {\n\t\treturn false\n\t}\n\n\tif s.URIWhole != t.URIWhole {\n\t\treturn false\n\t}\n\n\tif s.URLParam != t.URLParam {\n\t\treturn false\n\t}\n\n\tif s.URLParamCheckPost != t.URLParamCheckPost {\n\t\treturn false\n\t}\n\n\tif s.URLParamMaxWait != t.URLParamMaxWait {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (h1 *HMACAuth) Equal(h2 *HMACAuth) bool {\n\treturn reflect.DeepEqual(h1.HMACAuth, h2.HMACAuth)\n}", "func (c *Credentials) Equal(other *Credentials) bool {\n\treturn c != nil &&\n\t\tother != nil &&\n\t\tc.Key == other.Key &&\n\t\tc.ClientID == other.ClientID &&\n\t\t(c.SubAccount == other.SubAccount || c.SubAccount == \"\" && other.SubAccount == \"main\" || c.SubAccount == \"main\" && other.SubAccount == \"\")\n}", "func (a *Secret) Equal(b *Secret) bool {\n\treturn a == nil && b == nil || a != nil && b != nil && *a == *b\n}", "func (t Tags) Equal(other Tags) bool {\n\tif len(t.Values()) != len(other.Values()) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(t.Values()); i++ {\n\t\tequal := t.values[i].Name.Equal(other.values[i].Name) &&\n\t\t\tt.values[i].Value.Equal(other.values[i].Value)\n\t\tif !equal {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (j1 *JWTAuth) Equal(j2 *JWTAuth) bool {\n\treturn reflect.DeepEqual(j1.JWTAuth, j2.JWTAuth)\n}", "func (b *BrokerDivert) Equals(other BrokerEntity) bool {\n\treturn b.Type() == other.Type() &&\n\t\tb.Name == other.GetName()\n}", "func (b Bytes64) Equal(o Bytes64) bool { return bytes.Equal(b.Bytes(), o.Bytes()) }", "func includesEqual(configured []string, desired []string) bool {\n\tif len(configured) != len(desired) {\n\t\treturn false\n\t}\n\tsort.Strings(configured)\n\tsort.Strings(desired)\n\tfor i := 0; i < len(configured); i++ {\n\t\tif configured[i] != desired[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (c Chunk) Equals(other interface{}) bool {\n\tswitch oc := other.(type) {\n\tcase Chunk:\n\t\tif c.Bounds == oc.Bounds {\n\t\t\treturn chunksContainSameEntities(c, oc)\n\t\t}\n\tdefault:\n\t}\n\n\treturn false\n}", "func (t *TableValues) Equals(t2 *TableValues) bool {\n\tif t == nil || t2 == nil || t.number != t2.number || t.size != t2.size || len(t.values) != len(t2.values) {\n\t\treturn false\n\t}\n\t// now check the contents\n\tfor i, val := range t.values {\n\t\tif val != t2.values[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (gs GenesisState) Equal(data2 GenesisState) bool {\n\tb1 := ModuleCdc.MustMarshalBinaryBare(gs)\n\tb2 := ModuleCdc.MustMarshalBinaryBare(data2)\n\treturn bytes.Equal(b1, b2)\n}", "func (recv *ParamSpecBoxed) Equals(other *ParamSpecBoxed) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (t TestContent) Equals(other merkletree.Content) (bool, error) {\n\treturn t.x == other.(TestContent).x, nil\n}", "func (v *KeyValue_SetValueV2_Result) Equals(rhs *KeyValue_SetValueV2_Result) bool {\n\tif v == nil {\n\t\treturn rhs == nil\n\t} else if rhs == nil {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (v ConstructionMetadataRequest) Equal(o ConstructionMetadataRequest) bool {\n\treturn string(v.Options) == string(o.Options) &&\n\t\tlen(v.PublicKeys) == len(o.PublicKeys) &&\n\t\tpublicKeySliceEqual(v.PublicKeys, o.PublicKeys)\n}", "func profilesEqual(s, d *Profile) bool {\n\tif len(s.keys) != len(d.keys) {\n\t\treturn false\n\t}\n\tfor k, v := range s.keys {\n\t\tif d.keys[k] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (recv *ParamSpecFloat) Equals(other *ParamSpecFloat) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (rsk *ResourceStateKey) Equal(other *ResourceStateKey) bool {\n\tif rsk == nil || other == nil {\n\t\treturn false\n\t}\n\tif rsk.Mode != other.Mode {\n\t\treturn false\n\t}\n\tif rsk.Type != other.Type {\n\t\treturn false\n\t}\n\tif rsk.Name != other.Name {\n\t\treturn false\n\t}\n\tif rsk.Index != other.Index {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *Manifest) Equal(o *Manifest) bool {\n\tif m == o {\n\t\treturn true\n\t}\n\tif m.Source != o.Source {\n\t\treturn false\n\t}\n\tif m.Kind != o.Kind {\n\t\treturn false\n\t}\n\tif len(m.Owners) != len(o.Owners) {\n\t\treturn false\n\t}\n\tfor i, owner := range m.Owners {\n\t\tif o.Owners[i] != owner {\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(m.Deployments) != len(o.Deployments) {\n\t\treturn false\n\t}\n\tfor clusterName, deploySpec := range m.Deployments {\n\t\tif !o.Deployments[clusterName].Equal(deploySpec) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (v Currency) Equal(o Currency) bool {\n\treturn v.Decimals == o.Decimals &&\n\t\tstring(v.Metadata) == string(o.Metadata) &&\n\t\tv.Symbol == o.Symbol\n}", "func (in *CiliumEgressNATPolicy) DeepEqual(other *CiliumEgressNATPolicy) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif !in.Spec.DeepEqual(&other.Spec) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (state MSCBaseState) Equal(b MSCBaseState) (result bool) {\n\tif bytes.Equal(state.VpcAddress.Bytes(), b.VpcAddress.Bytes()) &&\n\t\tstate.BlockedReceiver.Cmp(b.BlockedReceiver) == 0 &&\n\t\tstate.BlockedSender.Cmp(b.BlockedSender) == 0 &&\n\t\tstate.Sid.Cmp(b.Sid) == 0 &&\n\t\tstate.Version.Cmp(b.Version) == 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (in *IPv4PoolSpec) DeepEqual(other *IPv4PoolSpec) bool {\n\tif other == nil {\n\t\treturn false\n\t}\n\n\tif ((in.CIDRs != nil) && (other.CIDRs != nil)) || ((in.CIDRs == nil) != (other.CIDRs == nil)) {\n\t\tin, other := &in.CIDRs, &other.CIDRs\n\t\tif other == nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif len(*in) != len(*other) {\n\t\t\treturn false\n\t\t} else {\n\t\t\tfor i, inElement := range *in {\n\t\t\t\tif inElement != (*other)[i] {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif in.MaskSize != other.MaskSize {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecObject) Equals(other *ParamSpecObject) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func Equal(left Value, right Value) bool {\n\t// TODO: Stop-gap for now, this will need to be much more sophisticated.\n\treturn CoerceString(left) == CoerceString(right)\n}", "func (resource *ResourceType) Equals(other Type, override EqualityOverrides) bool {\n\tif resource == other {\n\t\t// Same reference\n\t\treturn true\n\t}\n\n\totherResource, ok := other.(*ResourceType)\n\tif !ok {\n\t\treturn false\n\t}\n\n\t// Do cheap tests earlier\n\tif resource.isStorageVersion != otherResource.isStorageVersion ||\n\t\tlen(resource.testcases) != len(otherResource.testcases) ||\n\t\tlen(resource.functions) != len(otherResource.functions) ||\n\t\t!TypeEquals(resource.spec, otherResource.spec, override) ||\n\t\t!TypeEquals(resource.status, otherResource.status, override) ||\n\t\tlen(resource.annotations) != len(otherResource.annotations) ||\n\t\tresource.scope != otherResource.scope ||\n\t\tresource.armType != otherResource.armType ||\n\t\t!TypeEquals(resource.apiVersionTypeName, otherResource.apiVersionTypeName) ||\n\t\t!resource.apiVersionEnumValue.Equals(&otherResource.apiVersionEnumValue) ||\n\t\t!resource.InterfaceImplementer.Equals(otherResource.InterfaceImplementer, override) {\n\t\treturn false\n\t}\n\n\t// Check same functions present\n\tfor name, fn := range otherResource.functions {\n\t\tourFn, ok := resource.functions[name]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tif !ourFn.Equals(fn, override) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Check same test cases present\n\tfor name, testcase := range otherResource.testcases {\n\t\tourCase, ok := resource.testcases[name]\n\t\tif !ok {\n\t\t\t// Didn't find the func, not equal\n\t\t\treturn false\n\t\t}\n\n\t\tif !ourCase.Equals(testcase, override) {\n\t\t\t// Different testcase, even though same name; not-equal\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// Check same annotations present in the same order\n\tfor i, ourAnnotation := range resource.annotations {\n\t\totherAnnotation := otherResource.annotations[i]\n\t\tif ourAnnotation != otherAnnotation {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (e *Endpoints) DeepEquals(o *Endpoints) bool {\n\tswitch {\n\tcase (e == nil) != (o == nil):\n\t\treturn false\n\tcase (e == nil) && (o == nil):\n\t\treturn true\n\t}\n\n\tif len(e.Backends) != len(o.Backends) {\n\t\treturn false\n\t}\n\n\tfor ip1, ports1 := range e.Backends {\n\t\tports2, ok := o.Backends[ip1]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tif !ports1.DeepEquals(ports2) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (recv *ParamSpec) Equals(other *ParamSpec) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (m Message) IsEqual(ingest Message) (res bool) {\n\tres = m.topic == ingest.topic && m.Payload().Hash() == ingest.Payload().Hash()\n\treturn\n}", "func (b Bytes) Equal(o Bytes) bool { return bytes.Equal(b.Bytes(), o.Bytes()) }", "func (k *Key) Equal(other *Key) bool {\n\treturn k.IncompleteEqual(other) && (k.LastTok() == other.LastTok())\n}", "func (a *DeliveryArtifact) Equal(b *DeliveryArtifact) bool {\n\t// note we ignore the `Name` property when comparing equality\n\tif a.TagVersionStrategy != b.TagVersionStrategy {\n\t\treturn false\n\t}\n\tif !reflect.DeepEqual(a.VMOptions, b.VMOptions) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (recv *ParamSpecUInt64) Equals(other *ParamSpecUInt64) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (gvk GVK) IsEqualTo(other GVK) bool {\n\treturn gvk.Group == other.Group &&\n\t\tgvk.Domain == other.Domain &&\n\t\tgvk.Version == other.Version &&\n\t\tgvk.Kind == other.Kind\n}", "func (q Quat) Equals(other Quat) bool {\n\treturn q.EqualsEps(other, Epsilon)\n}", "func (uri WildcardUri) Equals(other interface{}) bool {\n\tswitch other.(type) {\n\tcase WildcardUri:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (acc *Account) Equal(a *Account) bool {\n\tif acc != nil && a != nil {\n\t\treturn acc.ID == a.ID && acc.EntityID == a.EntityID && acc.walletsEqual(a)\n\t}\n\treturn acc == a\n}", "func (list List) Equal(other List) bool {\n\tif other.Length() != list.Length() {\n\t\treturn false\n\t}\n\tfor idx, val := range list {\n\t\tif other[idx] != val {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (f *Format) Equal(v Format) bool {\n\treturn *f == v\n}", "func (a *Container) IsEqualTo(b *Container) bool {\n\t// check name\n\tif !a.IsSameKind(b) {\n\t\treturn false\n\t}\n\n\t// check configuration\n\tif !a.Config.IsEqualTo(b.Config) {\n\t\tlog.Debugf(\"Comparing '%s' and '%s': found difference in '%s'\",\n\t\t\ta.Name.String(),\n\t\t\tb.Name.String(),\n\t\t\ta.Config.LastCompareField())\n\t\treturn false\n\t}\n\n\t// check image version\n\tif a.Image != nil && !a.Image.Contains(b.Image) {\n\t\tlog.Debugf(\"Comparing '%s' and '%s': image version '%s' is not satisfied (was %s should satisfy %s)\",\n\t\t\ta.Name.String(),\n\t\t\tb.Name.String(),\n\t\t\ta.Image,\n\t\t\tb.Image,\n\t\t\ta.Image)\n\t\treturn false\n\t}\n\n\t// check image id\n\tif a.ImageID != \"\" && b.ImageID != \"\" && a.ImageID != b.ImageID {\n\t\tlog.Debugf(\"Comparing '%s' and '%s': image '%s' updated (was %.12s became %.12s)\",\n\t\t\ta.Name.String(),\n\t\t\tb.Name.String(),\n\t\t\ta.Image,\n\t\t\tb.ImageID,\n\t\t\ta.ImageID)\n\t\treturn false\n\t}\n\n\t// One of exit codes is always '0' since once of containers (a or b) is always loaded from config\n\tif a.Config.State.IsRan() && a.State.ExitCode+b.State.ExitCode > 0 {\n\t\tlog.Debugf(\"Comparing '%s' and '%s': container should run once, but previous exit code was %d\",\n\t\t\ta.Name.String(),\n\t\t\tb.Name.String(),\n\t\t\ta.State.ExitCode+b.State.ExitCode)\n\t\treturn false\n\t}\n\n\t// check state\n\tif !a.State.IsEqualState(b.State) {\n\t\tlog.Debugf(\"Comparing '%s' and '%s': found difference in state: Running: %t != %t\",\n\t\t\ta.Name.String(),\n\t\t\tb.Name.String(),\n\t\t\ta.State.Running,\n\t\t\tb.State.Running)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (recv *ParamSpecInt64) Equals(other *ParamSpecInt64) bool {\n\treturn other.ToC() == recv.ToC()\n}" ]
[ "0.7215028", "0.7100559", "0.70844483", "0.6989873", "0.691176", "0.6859806", "0.6853824", "0.6753042", "0.6624084", "0.65836465", "0.64694196", "0.6438307", "0.6187856", "0.6136497", "0.607758", "0.60505444", "0.5996127", "0.5987178", "0.59648985", "0.59618485", "0.59520084", "0.5878086", "0.58408505", "0.5831264", "0.58187485", "0.57950276", "0.5794659", "0.5724272", "0.5684481", "0.56705064", "0.56652755", "0.5644446", "0.5627526", "0.5603174", "0.5598301", "0.5593951", "0.5584", "0.5543121", "0.55366826", "0.55352116", "0.55195016", "0.55153984", "0.5502918", "0.54842454", "0.54796076", "0.5470626", "0.546257", "0.5459977", "0.54560465", "0.5424481", "0.542286", "0.54167277", "0.5391894", "0.5388507", "0.5385336", "0.53791857", "0.5366939", "0.5365883", "0.5364156", "0.5359541", "0.53510153", "0.5336979", "0.5333607", "0.5309555", "0.53032815", "0.5284315", "0.5279447", "0.52735186", "0.5263748", "0.52607757", "0.525684", "0.5252895", "0.52486795", "0.52354115", "0.52333766", "0.52319807", "0.5229175", "0.5220775", "0.5220735", "0.51743627", "0.51678693", "0.5167742", "0.51649356", "0.5160034", "0.51591414", "0.51575625", "0.5156475", "0.51510113", "0.5139995", "0.51397055", "0.5137265", "0.51364034", "0.5135727", "0.5134786", "0.51343256", "0.51331854", "0.51325464", "0.51266193", "0.5126363", "0.512603" ]
0.8606742
0
newStorageConfigFromConfigMap creates a StorageConfig from the supplied ConfigMap
func newStorageConfigFromConfigMap(ctx context.Context, configMap *corev1.ConfigMap, c client.Reader, ns string) (*StorageConfig, error) { var sc StorageConfig hasDefault := false for k, v := range configMap.Data { var bc BucketConfig err := yaml.Unmarshal([]byte(v), &bc) if err != nil { return nil, err } bc.fixEndpoint() bc.isDefault = k == "default" // Try loading the secret var secret corev1.Secret key := client.ObjectKey{ Name: bc.SecretName, Namespace: configMap.GetNamespace(), } if err := c.Get(ctx, key, &secret); err != nil { return nil, maskAny(err) } if raw, found := secret.Data[constants.SecretKeyS3AccessKey]; found { bc.accessKey = string(raw) } else { return nil, maskAny(fmt.Errorf("Config %#v refers to Secret '%s' that has no '%s' field", configMap.Data, bc.SecretName, constants.SecretKeyS3AccessKey)) } if raw, found := secret.Data[constants.SecretKeyS3SecretKey]; found { bc.secretKey = string(raw) } else { return nil, maskAny(fmt.Errorf("Config %#v refers to Secret '%s' that has no '%s' field", configMap.Data, bc.SecretName, constants.SecretKeyS3SecretKey)) } // Add to config hasDefault = hasDefault || bc.isDefault sc.Buckets = append(sc.Buckets, bc) } if !hasDefault { return nil, maskAny(fmt.Errorf("Config %#v must have a default bucket", configMap.Data)) } sort.Slice(sc.Buckets, func(i, j int) bool { a, b := sc.Buckets[i], sc.Buckets[j] if a.isDefault && !b.isDefault { return true } if !a.isDefault && b.isDefault { return false } return strings.Compare(a.Name, b.Name) < 0 }) return &sc, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newConfigFromMap(cfgMap map[string]string) (*configstore, error) {\n\tdata, ok := cfgMap[configdatakey]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"config data not present\")\n\t}\n\treturn &configstore{data}, nil\n}", "func NewStorageConfig(ctx context.Context, c client.Reader, ns string) (*StorageConfig, error) {\n\tvar configMap corev1.ConfigMap\n\tkey := client.ObjectKey{\n\t\tName: constants.ConfigMapS3Storage,\n\t\tNamespace: ns,\n\t}\n\tif err := c.Get(ctx, key, &configMap); errors.IsNotFound(err) {\n\t\t// Try koalja-system namespace\n\t\tkey.Namespace = constants.NamespaceKoaljaSystem\n\t\tif err := c.Get(ctx, key, &configMap); err != nil {\n\t\t\treturn nil, maskAny(err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\t// Parse config map\n\tsc, err := newStorageConfigFromConfigMap(ctx, &configMap, c, ns)\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\treturn sc, nil\n}", "func NewConfigFromMap(configMap map[string]string) (*Config, error) {\n\tnc := defaultConfig()\n\n\tif err := cm.Parse(configMap,\n\t\tcm.AsString(QueueSidecarImageKey, &nc.QueueSidecarImage),\n\t\tcm.AsDuration(ProgressDeadlineKey, &nc.ProgressDeadline),\n\t\tcm.AsStringSet(registriesSkippingTagResolvingKey, &nc.RegistriesSkippingTagResolving),\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif nc.QueueSidecarImage == \"\" {\n\t\treturn nil, errors.New(\"queueSidecarImage cannot be empty or unset\")\n\t}\n\n\tif nc.ProgressDeadline <= 0 {\n\t\treturn nil, fmt.Errorf(\"progressDeadline cannot be a non-positive duration, was %v\", nc.ProgressDeadline)\n\t}\n\n\treturn nc, nil\n}", "func NewConfigFromMap(configMap map[string]string) (*Config, error) {\n\tnc := defaultConfig()\n\n\tif err := cm.Parse(configMap,\n\t\tasRequiredString(QueueSidecarImageKey, &nc.QueueSidecarImage),\n\t\tcm.AsDuration(ProgressDeadlineKey, &nc.ProgressDeadline),\n\t\tasStringSet(registriesSkippingTagResolvingKey, &nc.RegistriesSkippingTagResolving),\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif nc.ProgressDeadline <= 0 {\n\t\treturn nil, fmt.Errorf(\"ProgressDeadline cannot be a non-positive duration, was %v\", nc.ProgressDeadline)\n\t}\n\n\treturn nc, nil\n}", "func FromConfigMap(ctx context.Context, clientSet kubernetes.Interface, namespace string) (*Config, error) {\n\tconfig, err := clientSet.CoreV1().ConfigMaps(namespace).Get(ctx, configMapName, metav1.GetOptions{})\n\tif err != nil {\n\t\tif k8errors.IsNotFound(err) {\n\t\t\tglog.Infof(\"cannot find launcher configmap: name=%q namespace=%q, will use default config\", configMapName, namespace)\n\t\t\t// LauncherConfig is optional, so ignore not found error.\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn &Config{data: config.Data}, nil\n}", "func NewConfigFromMap(configMap map[string]string) (*Config, error) {\n\tnc := defaultConfig()\n\tqsideCarImage, ok := configMap[QueueSidecarImageKey]\n\tif !ok {\n\t\treturn nil, errors.New(\"queue sidecar image is missing\")\n\t}\n\tnc.QueueSidecarImage = qsideCarImage\n\n\tif pd, ok := configMap[ProgressDeadlineKey]; ok {\n\t\tv, err := time.ParseDuration(pd)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing %s=%s as duration, %w\", ProgressDeadlineKey, pd, err)\n\t\t} else if v <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"%s cannot be non-positive duration, was %v\", ProgressDeadlineKey, v)\n\t\t}\n\t\tnc.ProgressDeadline = v\n\t}\n\n\tif registries, ok := configMap[registriesSkippingTagResolvingKey]; ok {\n\t\tnc.RegistriesSkippingTagResolving = sets.NewString(strings.Split(registries, \",\")...)\n\t}\n\treturn nc, nil\n}", "func FromKubernetesConfigMap(p provider.Provider, configmap v1.ConfigMap) (*ConfigMap, error) {\n\t param_name := \"\"\n\t param_type := \"\"\n\t param_key := \"\"\n\n\t for k, v := range configmap.ObjectMeta.Annotations {\n\t\t switch k {\n\t\t case anno.AWSParamName, anno.V1ParamName:\n\t\t\t param_name = v\n\t\t case anno.AWSParamType, anno.V1ParamType:\n\t\t\t param_type = v\n\t\t case anno.AWSParamKey, anno.V1ParamKey:\n\t\t\t param_key = v\n\t\t }\n\t }\n\n\t if param_name == \"\" || param_type == \"\" {\n\t\t return nil, errors.New(\"Irrelevant ConfigMap\")\n\t }\n\n\t if param_name != \"\" && param_type != \"\" {\n\t\t if param_type == \"SecureString\" && param_key == \"\" {\n\t\t\t log.Info(\"No KMS key defined. Using default key 'alias/aws/ssm'\")\n\t\t\t param_key = \"alias/aws/ssm\"\n\t\t }\n\t }\n\n\t s, err := NewConfigMap(\n\t\t configmap,\n\t\t p,\n\t\t configmap.ObjectMeta.Name,\n\t\t configmap.ObjectMeta.Namespace,\n\t\t param_name,\n\t\t param_type,\n\t\t param_key)\n\n\t if err != nil {\n\t\t return nil, err\n\t }\n\t return s, nil\n }", "func NewConfigFromConfigMap(configMap *corev1.ConfigMap) (*RedisConfig, error) {\n\treturn NewConfigFromMap(configMap.Data)\n}", "func NewConfigFromConfigMap(config *corev1.ConfigMap) (*Config, error) {\n\treturn NewConfigFromMap(config.Data)\n}", "func NewConfigFromConfigMap(config *corev1.ConfigMap) (*Config, error) {\n\treturn NewConfigFromMap(config.Data)\n}", "func NewConfigFromConfigMap(config *corev1.ConfigMap) (*Config, error) {\n\treturn NewConfigFromMap(config.Data)\n}", "func NewConfigMap(configmapName string, namespace string, data map[string]string) *core.ConfigMap {\n\treturn &core.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: core.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configmapName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: data,\n\t}\n}", "func newConfigMap(configMapName, namespace string, labels map[string]string,\n\tkibanaIndexMode, esUnicastHost, rootLogger, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount string) *v1.ConfigMap {\n\n\terr, data := renderData(kibanaIndexMode, esUnicastHost, nodeQuorum, recoverExpectedShards, primaryShardsCount, replicaShardsCount, rootLogger)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: v1.SchemeGroupVersion.String(),\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: data,\n\t}\n}", "func NewConfigFromMap(data map[string]string) (*RedisConfig, error) {\n\trc := defaultConfig()\n\tif numC, ok := data[redisConfigKey]; ok {\n\t\trc.NumConsumers = numC\n\t}\n\treturn rc, nil\n}", "func ConfigFromMap(m map[string]interface{}) (ServerConfig, error) {\n\tconfig := defaultServerConfig\n\tif err := gconv.Struct(m, &config); err != nil {\n\t\treturn config, err\n\t}\n\treturn config, nil\n}", "func newConfigmap(customConfigmap *customConfigMapv1alpha1.CustomConfigMap) *corev1.ConfigMap {\n\tlabels := map[string]string{\n\t\t\"name\": customConfigmap.Spec.ConfigMapName,\n\t\t\"customConfigName\": customConfigmap.Name,\n\t\t\"latest\": \"true\",\n\t}\n\tname := fmt.Sprintf(\"%s-%s\", customConfigmap.Spec.ConfigMapName, RandomSequence(5))\n\tconfigName := NameValidation(name)\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configName,\n\t\t\tNamespace: customConfigmap.Namespace,\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(customConfigmap, customConfigMapv1alpha1.SchemeGroupVersion.WithKind(\"CustomConfigMap\")),\n\t\t\t},\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: customConfigmap.Spec.Data,\n\t\tBinaryData: customConfigmap.Spec.BinaryData,\n\t}\n}", "func NewDefaultsConfigFromMap(data map[string]string) (*Defaults, error) {\n\tnc := &Defaults{}\n\n\t// Parse out the GCP Auth Configuration.\n\tvalue, present := data[defaulterKey]\n\tif !present || value == \"\" {\n\t\treturn nil, fmt.Errorf(\"ConfigMap is missing (or empty) key: %q : %v\", defaulterKey, data)\n\t}\n\tif err := parseEntry(value, nc); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse the entry: %s\", err)\n\t}\n\treturn nc, nil\n}", "func InitMapStorage() *MapURLStorage {\n\treturn &MapURLStorage{\n\t\tStorage: make(map[string]string),\n\t}\n}", "func NewConfigMap(namespace, cmName, originalFilename string, generatedKey string,\n\ttextData string, binaryData []byte) *corev1.ConfigMap {\n\timmutable := true\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cmName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\tConfigMapOriginalFileNameLabel: originalFilename,\n\t\t\t\tConfigMapAutogenLabel: \"true\",\n\t\t\t},\n\t\t},\n\t\tImmutable: &immutable,\n\t}\n\tif textData != \"\" {\n\t\tcm.Data = map[string]string{\n\t\t\tgeneratedKey: textData,\n\t\t}\n\t}\n\tif binaryData != nil {\n\t\tcm.BinaryData = map[string][]byte{\n\t\t\tgeneratedKey: binaryData,\n\t\t}\n\t}\n\treturn &cm\n}", "func MetaConfigFromConfigMap(cm *v1.ConfigMap) interfaces.MetaConfig {\n\treturn &metaConfig{\n\t\tmeta: cm.ObjectMeta,\n\t\ttyp: configTypeConfigMap,\n\t\tdataSha: getSha(cm.Data),\n\t}\n}", "func New(configs ...Configurator) (*Storage, error) {\n\tinstance := &Storage{}\n\tfor _, configure := range configs {\n\t\tif err := configure(instance); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn instance, nil\n}", "func (c *controller) ApplyConfigMap(namespace string, configMap *ConfigMap) error {\n\tcm := apicorev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configMap.Name,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\tconfigMap.FileName: configMap.Data,\n\t\t},\n\t}\n\t_, err := c.k8sCoreClient.ConfigMaps(namespace).Get(cm.Name, metav1.GetOptions{})\n\tif err == nil {\n\t\t// exists, we update instead\n\t\t_, err = c.k8sCoreClient.ConfigMaps(namespace).Update(&cm)\n\t\treturn err\n\t}\n\t_, err = c.k8sCoreClient.ConfigMaps(namespace).Create(&cm)\n\treturn err\n}", "func NewDefaultsFromMap(cfgMap map[string]string) (*Defaults, error) {\n\ttc := Defaults{\n\t\tDefaultCloudEventsSink: DefaultCloudEventSinkValue,\n\t}\n\n\tif defaultCloudEventsSink, ok := cfgMap[defaultCloudEventsSinkKey]; ok {\n\t\ttc.DefaultCloudEventsSink = defaultCloudEventsSink\n\t}\n\n\treturn &tc, nil\n}", "func mapToConfig(cfgMap map[string]interface{}) (*FSConfig, error) {\n\tif cfgMap == nil {\n\t\treturn DefaultFSConfig(), nil\n\t}\n\tcfg := &FSConfig{}\n\tif err := mapstructure.Decode(cfgMap, cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func NewMapStorage(name string) *MapStorage {\n\tvar storage MapStorage\n\tstorage.name = name\n\tstorage.Stations = make(map[string]Station)\n\tstorage.MonthlySeries = make(map[string]MonthlyMeasureSerie)\n\n\treturn &storage\n}", "func newConfigMapStore(c kubernetes.Interface) configMapStore {\n\treturn &APIServerconfigMapStore{\n\t\tconfigMapStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\tclient: c,\n\t}\n}", "func NewConfig(cfg map[string]interface{}) *Config {\n\tif cfg == nil {\n\t\tcfg = make(map[string]interface{})\n\t}\n\treturn &Config{\n\t\tm: cfg,\n\t}\n}", "func NewConfigMapObject(component *v3.Component, app *v3.Application) corev1.ConfigMap {\n\tvar stringmap map[string]string = make(map[string]string)\n\tfor _, i := range component.Containers {\n\t\tfor _, j := range i.Config {\n\t\t\tif j.FileName == \"\" {\n\t\t\t\tlog.Errorf(\"%s-%s's configmap configuration's filename is nil,please check configration\", component.Name, component.Version)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstringmap[j.FileName] = j.Value\n\t\t}\n\t}\n\tconfigmap := corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tOwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(app, v3.SchemeGroupVersion.WithKind(\"Application\"))},\n\t\t\tNamespace: app.Namespace,\n\t\t\tName: app.Name + \"-\" + component.Name + \"-\" + component.Version + \"-\" + \"configmap\",\n\t\t},\n\t\tData: stringmap,\n\t}\n\treturn configmap\n}", "func NewFeaturesConfigFromMap(data map[string]string) (*Features, error) {\n\tnc := defaultFeaturesConfig()\n\n\tif err := cm.Parse(data, AsFlag(\"multi-container\", &nc.MultiContainer)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn nc, nil\n}", "func NewStorageConfig() *StorageConfig {\n\tmodel := new(StorageConfig)\n\n\treturn model\n}", "func NewConfigMapFromKubeConfigMap(cm interface{}) (*ConfigMap, error) {\n\tswitch reflect.TypeOf(cm) {\n\tcase reflect.TypeOf(v1.ConfigMap{}):\n\t\tobj := cm.(v1.ConfigMap)\n\t\treturn fromKubeConfigMapV1(&obj)\n\tcase reflect.TypeOf(&v1.ConfigMap{}):\n\t\treturn fromKubeConfigMapV1(cm.(*v1.ConfigMap))\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown ConfigMap version: %s\", reflect.TypeOf(cm))\n\t}\n}", "func NewConfigMap(cr *databasev1alpha1.PostgreSQL) (*v1.ConfigMap, error) {\n\tlabels := utils.NewLabels(\"postgres\", cr.ObjectMeta.Name, \"postgres\")\n\tabsPath, _ := filepath.Abs(\"scripts/pre-stop.sh\")\n\tpreStop, err := ioutil.ReadFile(absPath)\n\n\tif err != nil {\n\t\tlog.Error(err, \"Unable to read file.\")\n\t\treturn nil, err\n\t}\n\tconfigMap := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.ObjectMeta.Name + \"-postgresql-hooks-scripts\",\n\t\t\tLabels: labels,\n\t\t\tNamespace: cr.Spec.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"pre-stop.sh\": string(preStop),\n\t\t},\n\t}\n\n\treturn configMap, nil\n}", "func ParseConfigMap(cm corev1.ConfigMap) (map[string]*CAPITemplate, error) {\n\ttm := map[string]*CAPITemplate{}\n\n\tfor k, v := range(cm.Data) {\n\t\tt, err := ParseBytes([]byte(v), k)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to unmarshal template %s from configmap %s, err: %w\", k, cm.ObjectMeta.Name, err)\n\t\t}\n\t\ttm[k] = t\n\t}\n\treturn tm, nil\n}", "func NewFeaturesConfigFromConfigMap(config *corev1.ConfigMap) (*Features, error) {\n\treturn NewFeaturesConfigFromMap(config.Data)\n}", "func NewConfigMapWatcher(logger *zap.Logger, dir string, updateConfig swappable.UpdateConfig) (*configMapWatcher, error) {\n\tconf, err := readConfigMap(logger, dir)\n\tif err != nil {\n\t\tlogger.Error(\"Unable to read configMap\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\tlogger.Info(\"Read initial configMap\", zap.Any(\"conf\", conf))\n\n\terr = updateConfig(conf)\n\tif err != nil {\n\t\tlogger.Error(\"Unable to use the initial configMap: %v\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\tcmw := &configMapWatcher{\n\t\tlogger: logger,\n\t\tdir: dir,\n\t\tconfigUpdated: updateConfig,\n\t}\n\treturn cmw, nil\n}", "func NewConfig(cfg map[string]interface{}) Config {\n\treturn Config{Data: cfg}\n}", "func NewMapStorage() *MapStorage {\n\treturn &MapStorage{store: make(map[string]int)}\n}", "func ApplyConfigMapFromFile(clientset *kubernetes.Clientset, namespace string, configmap *corev1.ConfigMap, path string) error {\n\tlog.Printf(\"📦 Reading contents of %s\", path)\n\t_, filename := filepath.Split(path)\n\tfileContents, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigMapData := make(map[string]string)\n\tconfigMapData[filename] = string(fileContents)\n\tconfigmap.Data = configMapData\n\t// Check if deployment exists\n\tdeploymentExists, err := configMapExists(clientset, namespace, configmap.Name)\n\tif deploymentExists {\n\t\tlog.Printf(\"📦 Found existing deployment. Updating %s.\", configmap.Name)\n\t\t_, err = clientset.CoreV1().ConfigMaps(namespace).Update(configmap)\n\t\treturn err\n\t}\n\t_, err = clientset.CoreV1().ConfigMaps(namespace).Create(configmap)\n\treturn err\n}", "func newMountFromConfig(mCfg *MountConfig) Mount {\n\topts := newOptionsFromConfig(mCfg)\n\treturn Mount{\n\t\tSource: mCfg.HostPath,\n\t\tDestination: mCfg.ContainerPath,\n\t\tType: newMountTypeFromConfig(mCfg),\n\t\tOptions: newMountOptions(opts),\n\t}\n}", "func ConfigMap(\n\tinCluster *v1beta1.PostgresCluster,\n\toutConfigMap *corev1.ConfigMap,\n) error {\n\tif inCluster.Spec.UserInterface == nil || inCluster.Spec.UserInterface.PGAdmin == nil {\n\t\t// pgAdmin is disabled; there is nothing to do.\n\t\treturn nil\n\t}\n\n\tinitialize.StringMap(&outConfigMap.Data)\n\n\t// To avoid spurious reconciles, the following value must not change when\n\t// the spec does not change. [json.Encoder] and [json.Marshal] do this by\n\t// emitting map keys in sorted order. Indent so the value is not rendered\n\t// as one long line by `kubectl`.\n\tbuffer := new(bytes.Buffer)\n\tencoder := json.NewEncoder(buffer)\n\tencoder.SetEscapeHTML(false)\n\tencoder.SetIndent(\"\", \" \")\n\terr := encoder.Encode(systemSettings(inCluster.Spec.UserInterface.PGAdmin))\n\tif err == nil {\n\t\toutConfigMap.Data[settingsConfigMapKey] = buffer.String()\n\t}\n\treturn err\n}", "func (h *Settings) FromMap(values map[string]interface{}) error {\n\tvar err error\n\tif h.Operation, err = coerce.ToString(values[\"operation\"]); err != nil {\n\t\treturn err\n\t}\n\tif len(h.Operation) == 0 {\n\t\th.Operation = \"LIST\"\n\t}\n\tif h.Role, err = coerce.ToString(values[\"role\"]); err != nil {\n\t\treturn err\n\t}\n\tif len(h.Role) == 0 {\n\t\th.Role = string(statebased.RoleTypeMember)\n\t}\n\treturn nil\n}", "func (c *ClusterController) createOnosConfigConfigMap() error {\n\tconfig, err := c.config.load()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Serialize the change store configuration\n\tchangeStore, err := json.Marshal(config[\"changeStore\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Serialize the network store configuration\n\tnetworkStore, err := json.Marshal(config[\"networkStore\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Serialize the device store configuration\n\tdeviceStore, err := json.Marshal(config[\"deviceStore\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Serialize the config store configuration\n\tconfigStore, err := json.Marshal(config[\"configStore\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcm := &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"onos-config\",\n\t\t\tNamespace: c.clusterID,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"changeStore.json\": string(changeStore),\n\t\t\t\"configStore.json\": string(configStore),\n\t\t\t\"deviceStore.json\": string(deviceStore),\n\t\t\t\"networkStore.json\": string(networkStore),\n\t\t},\n\t}\n\t_, err = c.kubeclient.CoreV1().ConfigMaps(c.clusterID).Create(cm)\n\treturn err\n}", "func (k *MockK8sClient) CreateConfigMap(namespace, configmap string, params map[string]string) (*v1.ConfigMap, error) {\n\tif k.CreateConfigMapFn != nil {\n\t\treturn k.CreateConfigMapFn(namespace, configmap, params)\n\t}\n\treturn nil, nil\n}", "func newStorage(account *account, prov provider.Account, cfg *config.Storage) (*storage, error) {\n\tlog.Debug(\"Initializing Storage\")\n\n\t// Validate the config.Storage object.\n\tif cfg.Buckets == nil {\n\t\treturn nil, fmt.Errorf(\"The buckets element is missing from the storage configuration\")\n\t}\n\n\ts := &storage{\n\t\tResources: resource.NewResources(),\n\t\tStorage: cfg,\n\t\taccount: account,\n\t}\n\n\tvar err error\n\ts.providerStorage, err = prov.NewStorage(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.buckets, err = newBuckets(s, prov, cfg.Buckets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Append(s.buckets)\n\treturn s, nil\n}", "func New(config *config.ConfYaml) *Storage {\n\treturn &Storage{\n\t\tconfig: config,\n\t}\n}", "func NewConfigMapScaler(kubeClient kubeclient.Interface, configNamespace, configmapName string,\n\tmaxBulkScaleUpCount int) Webhook {\n\tstopChannel := make(chan struct{})\n\tlister := kubernetes.NewConfigMapListerForNamespace(kubeClient, stopChannel, configNamespace)\n\treturn &ConfigMapScaler{client: kubeClient, namespace: configNamespace, name: configmapName,\n\t\tconfigmapLister: lister.ConfigMaps(configNamespace), maxBulkScaleUpCount: maxBulkScaleUpCount}\n}", "func NewConfig(GM *GameManager) *ConfigManager {\n\treturn &ConfigManager{\n\t\tgm: GM,\n\t\tconfig: new(sync.Map),\n\t}\n}", "func (o FioSpecVolumeVolumeSourceOutput) ConfigMap() FioSpecVolumeVolumeSourceConfigMapPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceConfigMap { return v.ConfigMap }).(FioSpecVolumeVolumeSourceConfigMapPtrOutput)\n}", "func createConfigMap() *v1.ConfigMap {\n\treturn &v1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"ConfigMap\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"descheduler-policy-configmap\",\n\t\t\tNamespace: \"kube-system\",\n\t\t},\n\t\t// strategies:\\n \\\"RemoveDuplicates\\\":\\n enabled: true\n\t\tData: map[string]string{\n\t\t\t\"policy.yaml\": \"apiVersion: \\\"descheduler/v1alpha1\\\"\\nkind: \\\"DeschedulerPolicy\\\"\\nstrategies:\\n \\\"RemoveDuplicates\\\":\\n enabled: true\\n\",\n\t\t},\n\t}\n}", "func createCustomConfigMap(c kubernetes.Interface, pluginPath string, subvolgrpInfo map[string]string) {\n\tpath := pluginPath + configMap\n\tcm := v1.ConfigMap{}\n\terr := unmarshal(path, &cm)\n\tExpect(err).Should(BeNil())\n\n\t// get mon list\n\tmons := getMons(rookNamespace, c)\n\t// get clusterIDs\n\tvar clusterID []string\n\tfor key := range subvolgrpInfo {\n\t\tclusterID = append(clusterID, key)\n\t}\n\tconmap := []util.ClusterInfo{\n\t\t{\n\t\t\tClusterID: clusterID[0],\n\t\t\tMonitors: mons,\n\t\t},\n\t\t{\n\t\t\tClusterID: clusterID[1],\n\t\t\tMonitors: mons,\n\t\t}}\n\tfor i := 0; i < len(subvolgrpInfo); i++ {\n\t\tconmap[i].CephFS.SubvolumeGroup = subvolgrpInfo[clusterID[i]]\n\t}\n\tdata, err := json.Marshal(conmap)\n\tExpect(err).Should(BeNil())\n\tcm.Data[\"config.json\"] = string(data)\n\tcm.Namespace = cephCSINamespace\n\t// since a configmap is already created, update the existing configmap\n\t_, updateErr := c.CoreV1().ConfigMaps(cephCSINamespace).Update(context.TODO(), &cm, metav1.UpdateOptions{})\n\tExpect(updateErr).Should(BeNil())\n}", "func NewPingDefaultsConfigFromMap(data map[string]string) (*PingDefaults, error) {\n\tnc := &PingDefaults{DataMaxSize: DefaultDataMaxSize}\n\n\tif err := cm.Parse(data,\n\t\t// Legacy for backwards compatibility\n\t\tcm.AsInt64(LegacyDataMaxSizeKey, &nc.DataMaxSize),\n\n\t\tcm.AsInt64(DataMaxSizeKey, &nc.DataMaxSize),\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nc, nil\n}", "func NewDefaultsConfigFromConfigMap(config *corev1.ConfigMap) (*Defaults, error) {\n\treturn NewDefaultsConfigFromMap(config.Data)\n}", "func NewStorage() SafeMap {\n\tsm := make(safeMap)\n\tgo sm.run()\n\treturn sm\n}", "func FromTieredMap(m map[string]interface{}) Config {\n\treturn tieredMap(m)\n}", "func NewStorage(s map[string]interface{}) (Storage, error) {\n\tstype, ok := s[\"Type\"].(string)\n\tif !ok || stype == \"\" {\n\t\treturn nil, errors.New(\"Template do not have Storage type\")\n\t}\n\n\tswitch stype {\n\tcase \"Local\":\n\t\treturn newStorageLocal(s), nil\n\tcase \"S3\":\n\t\treturn newStorageS3(s)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unexecepted Storage type: %v\", stype)\n\t}\n}", "func NewFakeConfigMapVault(ns, name string) *ConfigMapVault {\n\treturn &ConfigMapVault{\n\t\tconfigMapStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\tnamespace: ns,\n\t\tname: name}\n}", "func CreateConfigMap(client kubernetes.Interface, namespace string, configmapName string, data string) (core_v1.ConfigMapInterface, error) {\n\tlogrus.Infof(\"Creating configmap\")\n\tconfigmapClient := client.CoreV1().ConfigMaps(namespace)\n\t_, err := configmapClient.Create(GetConfigmap(namespace, configmapName, data))\n\ttime.Sleep(10 * time.Second)\n\treturn configmapClient, err\n}", "func (o IopingSpecVolumeVolumeSourceOutput) ConfigMap() IopingSpecVolumeVolumeSourceConfigMapPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceConfigMap { return v.ConfigMap }).(IopingSpecVolumeVolumeSourceConfigMapPtrOutput)\n}", "func NewMemConfig(files map[string][]byte) Client {\n\tif files == nil {\n\t\tfiles = make(map[string][]byte)\n\t}\n\treturn &MemConfig{files: files}\n}", "func NewQingStorageClassFromMap(opt map[string]string) (*QingStorageClass, error) {\n\tsVolType, volTypeOk := opt[StorageClassTypeName]\n\tsMaxSize, maxSizeOk := opt[StorageClassMaxSizeName]\n\tsMinSize, minSizeOk := opt[StorageClassMinSizeName]\n\tsStepSize, stepSizeOk := opt[StorageClassStepSizeName]\n\tsFsType, fsTypeOk := opt[StorageClassFsTypeName]\n\tsReplica, replicaOk := opt[StorageClassReplicaName]\n\tsTags, tagsOk := opt[StorageClassTagsName]\n\n\tsc := NewDefaultQingStorageClass()\n\n\tif volTypeOk {\n\t\t// Convert volume type to integer\n\t\tiVolType, err := strconv.Atoi(sVolType)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !VolumeType(iVolType).IsValid() {\n\t\t\treturn nil, fmt.Errorf(\"invalid volume type %d\", iVolType)\n\t\t}\n\t\tsc.DiskType = VolumeType(iVolType)\n\t}\n\n\tif maxSizeOk && minSizeOk && stepSizeOk {\n\t\t// Get volume max size\n\t\tiMaxSize, err := strconv.Atoi(sMaxSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif iMaxSize <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"max size must greater than zero\")\n\t\t}\n\t\tsc.MaxSize = iMaxSize\n\t\t// Get volume min size\n\t\tiMinSize, err := strconv.Atoi(sMinSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif iMinSize <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"min size must greater than zero\")\n\t\t}\n\t\tsc.MinSize = iMinSize\n\t\t// Ensure volume minSize less than volume maxSize\n\t\tif sc.MaxSize < sc.MinSize {\n\t\t\treturn nil, fmt.Errorf(\"max size must greater than or equal to min size\")\n\t\t}\n\t\t// Get volume step size\n\t\tiStepSize, err := strconv.Atoi(sStepSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif iStepSize <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"step size must greater than zero\")\n\t\t}\n\t\tsc.StepSize = iStepSize\n\t}\n\n\tif fsTypeOk {\n\t\tif !IsValidFileSystemType(sFsType) {\n\t\t\treturn nil, fmt.Errorf(\"unsupported filesystem type %s\", sFsType)\n\t\t}\n\t\tsc.FsType = sFsType\n\t}\n\n\t// Get volume replicas\n\tif replicaOk {\n\t\tiReplica, err := strconv.Atoi(sReplica)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !IsValidReplica(iReplica) {\n\t\t\treturn nil, fmt.Errorf(\"unsupported replica %s\", sReplica)\n\t\t}\n\t\tsc.Replica = iReplica\n\t}\n\n\tif tagsOk && len(sTags) > 0 {\n\t\tsc.Tags = strings.Split(strings.ReplaceAll(sTags, \" \", \"\"), \",\")\n\t}\n\treturn sc, nil\n}", "func (c *ContainerConfigMapSpec) Create() (client.Object, error) {\n\tcr := c.qserv\n\ttmplData := generateTemplateData(cr)\n\n\treqLogger := log.WithValues(\"Request.Namespace\", cr.Namespace, \"Request.Name\", cr.Name)\n\n\tname := c.GetName()\n\tnamespace := cr.Namespace\n\n\tlabels := util.GetContainerLabels(c.ContainerName, cr.Name)\n\troot := filepath.Join(\"/\", \"configmap\", string(c.ContainerName), c.Subdir)\n\n\tcm := &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tData: scanDir(root, reqLogger, &tmplData),\n\t}\n\treturn cm, nil\n}", "func (c *Vrouter) CreateConfigMap(configMapName string,\n\tclient client.Client,\n\tscheme *runtime.Scheme,\n\trequest reconcile.Request) (*corev1.ConfigMap, error) {\n\treturn CreateConfigMap(configMapName,\n\t\tclient,\n\t\tscheme,\n\t\trequest,\n\t\t\"vrouter\",\n\t\tc)\n}", "func NewLoggerConfig(configMap map[string]interface{}) (*LoggerConfig, error) {\n\tc := LoggerConfig{}\n\terr := hooks.Decode(configMap, &c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}", "func New[C db.Config](cfg C) db.Storage[C] {\n\treturn &MyStorage[C]{cfg: cfg}\n}", "func GetVolumeFromConfigMap(configMap *apicommonv1.ConfigMapConfig, defaultConfigMapName, volumeName string) corev1.Volume {\n\tcmName := defaultConfigMapName\n\tif configMap != nil && len(configMap.Name) > 0 {\n\t\tcmName = configMap.Name\n\t}\n\n\tcmSource := &corev1.ConfigMapVolumeSource{\n\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\tName: cmName,\n\t\t},\n\t}\n\n\tif len(configMap.Items) > 0 {\n\t\tcmSource.Items = configMap.Items\n\t}\n\n\treturn corev1.Volume{\n\t\tName: volumeName,\n\t\tVolumeSource: corev1.VolumeSource{\n\t\t\tConfigMap: cmSource,\n\t\t},\n\t}\n}", "func WithStorageConfig(c ffs.StorageConfig) PushStorageConfigOption {\n\treturn func(r *rpc.PushStorageConfigRequest) {\n\t\tr.HasConfig = true\n\t\tr.Config = &rpc.StorageConfig{\n\t\t\tRepairable: c.Repairable,\n\t\t\tHot: toRPCHotConfig(c.Hot),\n\t\t\tCold: toRPCColdConfig(c.Cold),\n\t\t}\n\t}\n}", "func CreateConfigMap(name string) *corev1.ConfigMap {\n\treturn &corev1.ConfigMap{\n\t\tTypeMeta: genTypeMeta(gvk.ConfigMap),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t}\n}", "func (r *RuleConfig) FromMap(m map[interface{}]interface{}) {\n\tfor key, value := range m {\n\t\tswitch key.(string) {\n\t\tcase \"type\":\n\t\t\tr.Type = value.(string)\n\t\t\tbreak\n\t\tcase \"method\":\n\t\t\tr.Method = InterfaceToStringSlice(value)\n\t\t\tbreak\n\t\tcase \"path\":\n\t\t\tr.Path = value.(string)\n\t\t\tbreak\n\t\tcase \"userinfo\":\n\t\t\tr.Userinfo = InterfaceToStringMap(value)\n\t\t\tbreak\n\t\tcase \"query-parameter\":\n\t\t\tr.QueryParameter = InterfaceToStringMap(value)\n\t\t\tbreak\n\t\tcase \"json-body-parameter\":\n\t\t\tr.JSONBodyParameter = InterfaceToStringMap(value)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (m *Manager) MapClientStorage(stor oauth2.ClientStore) error {\n\tif stor == nil {\n\t\treturn errors.ErrNilValue\n\t}\n\tm.injector.Map(stor)\n\treturn nil\n}", "func GetConfigmapConfig(configmap *v1.ConfigMap) Config {\n\treturn Config{\n\t\tNamespace: configmap.Namespace,\n\t\tResourceName: configmap.Name,\n\t\tResourceAnnotations: configmap.Annotations,\n\t\tAnnotation: options.ConfigmapUpdateOnChangeAnnotation,\n\t\tSHAValue: GetSHAfromConfigmap(configmap),\n\t\tType: constants.ConfigmapEnvVarPostfix,\n\t}\n}", "func (o FioSpecVolumeVolumeSourcePtrOutput) ConfigMap() FioSpecVolumeVolumeSourceConfigMapPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSource) *FioSpecVolumeVolumeSourceConfigMap {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ConfigMap\n\t}).(FioSpecVolumeVolumeSourceConfigMapPtrOutput)\n}", "func NewConfig(configFile string) (conf *Config) {\n\tc, err := os.Open(configFile)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not read config file (%s)\\n\", configFile)\n\n\t}\n\n\tjson.NewDecoder(c).Decode(&conf)\n\n\tconf.loc, err = time.LoadLocation(conf.Location)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not load (%s) location\", conf.Location)\n\t}\n\n\treturn\n}", "func (ts *tester) createConfigMap() error {\n\tts.cfg.Logger.Info(\"creating config map\")\n\n\tb, err := ioutil.ReadFile(ts.cfg.EKSConfig.KubeConfigPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\t_, err = ts.cfg.K8SClient.KubernetesClientSet().\n\t\tCoreV1().\n\t\tConfigMaps(ts.cfg.EKSConfig.AddOnStresserRemote.Namespace).\n\t\tCreate(\n\t\t\tctx,\n\t\t\t&v1.ConfigMap{\n\t\t\t\tTypeMeta: metav1.TypeMeta{\n\t\t\t\t\tAPIVersion: \"v1\",\n\t\t\t\t\tKind: \"ConfigMap\",\n\t\t\t\t},\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: stresserKubeConfigConfigMapName,\n\t\t\t\t\tNamespace: ts.cfg.EKSConfig.AddOnStresserRemote.Namespace,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": stresserKubeConfigConfigMapName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tData: map[string]string{\n\t\t\t\t\tstresserKubeConfigConfigMapFileName: string(b),\n\t\t\t\t},\n\t\t\t},\n\t\t\tmetav1.CreateOptions{},\n\t\t)\n\tcancel()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tts.cfg.Logger.Info(\"created config map\")\n\tts.cfg.EKSConfig.Sync()\n\treturn nil\n}", "func New(content map[string]interface{}) *Config {\n\treturn &Config{\n\t\tm: content,\n\t}\n}", "func (c *ConfigMapConfig) ToConfigMap() corev1.ConfigMap {\n\treturn corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: ApiVersion,\n\t\t\tKind: KindConfigMap,\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: c.Name,\n\t\t\tNamespace: c.Namespace,\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"csi.json\": c.JsonData,\n\t\t},\n\t}\n}", "func (c client) CreateConfigMap(cm corev1.ConfigMap) error {\n\treturn c.Create(context.TODO(), &cm)\n}", "func newGoogleStorageClient(config stow.Config) (*storage.Service, error) {\n\tjson, _ := config.Config(ConfigJSON)\n\tvar httpClient *http.Client\n\tscopes := []string{storage.DevstorageReadWriteScope}\n\tif s, ok := config.Config(ConfigScopes); ok && s != \"\" {\n\t\tscopes = strings.Split(s, \",\")\n\t}\n\tif json != \"\" {\n\t\tjwtConf, err := google.JWTConfigFromJSON([]byte(json), scopes...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = jwtConf.Client(context.Background())\n\n\t} else {\n\t\tcreds, err := google.FindDefaultCredentials(context.Background(), strings.Join(scopes, \",\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = oauth2.NewClient(context.Background(), creds.TokenSource)\n\t}\n\tservice, err := storage.New(httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service, nil\n}", "func NewConfig(data map[string]string) (settings *Config) {\n cfg := &Config{\n ConsumerKey: data[\"consumer_key\"],\n ConsumerSecret: data[\"consumer_secret\"],\n }\n\n // save access token if defined\n if atoken, ok := data[\"access_token\"]; ok {\n cfg.AccessToken = atoken\n }\n\n // save access token secret if defined\n if asecret, ok := data[\"access_secret\"]; ok {\n cfg.AccessSecret = asecret\n }\n\n // save debug flag if defined\n if debug, ok := data[\"debug\"]; ok && debug == \"on\" {\n cfg.Debug = true\n }\n\n return cfg\n}", "func (c newConfigMap) Delete() error {\n\treturn c.Client.Delete(c.ConfigMap.Name, &v1.DeleteOptions{})\n}", "func (s *Storage) ForConfig(path ...string) SForConfig {\n\tif len(path) == 0 {\n\t\tpanic(\"path is required\")\n\t}\n\treturn SForConfig{s, path}\n}", "func newConfigFromString(t *testing.T, configString string) (Config, func(), error) {\n\ttestFs, testFsTeardown := setupTestFs()\n\n\terr := afero.WriteFile(testFs, \"config.properties\", []byte(configString), 0644)\n\n\tif err != nil {\n\t\t// Fatal stops the goroutine before the caller can defer the teardown function\n\t\t// run it manually now\n\t\ttestFsTeardown()\n\t\tConfigViperHook = func(v *viper.Viper) {}\n\n\t\tt.Fatal(\"cannot make file\", \"config.properties\", err)\n\t}\n\n\tConfigViperHook = func(v *viper.Viper) {\n\t\tv.SetFs(GetIndexFs())\n\t}\n\n\tlog.DEBUG.Printf(\"loading config from '%s'\\n\", configString)\n\n\tc, err := NewConfig(\"config.properties\")\n\n\treturn c, func() {\n\t\ttestFsTeardown()\n\t\tConfigViperHook = func(v *viper.Viper) {}\n\t}, err\n}", "func (configMapTemplateFactory) New(def client.ResourceDefinition, c client.Interface, gc interfaces.GraphContext) interfaces.Resource {\n\tcm := parametrizeResource(def.ConfigMap, gc, configMapParamFields).(*v1.ConfigMap)\n\treturn report.SimpleReporter{BaseResource: newConfigMap{Base: Base{def.Meta}, ConfigMap: cm, Client: c.ConfigMaps()}}\n}", "func NewConfig(cfgFile string, fs filesystem.FileSystem, kubeCfg kubeconfig.KubeConfig) (Config, error) {\n\tcfg := Config{\n\t\tfilesystem: fs,\n\t\tkubeCfg: kubeCfg,\n\t}\n\n\tif err := cfg.load(cfgFile); err != nil {\n\t\treturn cfg, err\n\t}\n\n\treturn cfg, nil\n}", "func DeleteConfigMap(client kubernetes.Interface, namespace string, configmapName string) error {\n\tlogrus.Infof(\"Deleting configmap %q.\\n\", configmapName)\n\terr := client.CoreV1().ConfigMaps(namespace).Delete(configmapName, &metav1.DeleteOptions{})\n\ttime.Sleep(10 * time.Second)\n\treturn err\n}", "func NewStorage(cfg *api.Config, rootPath string, syncFrequency time.Duration) (storage.Interface, error) {\n\tcfg.WaitTime = syncFrequency\n\n\t// Get a new client\n\tclient, err := api.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating consul client\")\n\t}\n\n\treturn &Client{\n\t\tv1: &v1client{\n\t\t\tupstreams: &upstreamsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/upstreams\", client),\n\t\t\t},\n\t\t\tvirtualHosts: &virtualHostsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/virtualhosts\", client),\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func FromFile(path string) (Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, errors.New(\"config: \" + err.Error())\n\t}\n\n\ttype authYAML struct {\n\t\tUsername string `yaml:\"username\"`\n\t\tPassword string `yaml:\"password\"`\n\t\tTenantName string `yaml:\"tenant_name\"`\n\t\tTenantID string `yaml:\"tenant_id\"`\n\t\tAuthURL string `yaml:\"auth_url\"`\n\t}\n\ty := map[string]map[string]map[string]*authYAML{}\n\tif err := yaml.Unmarshal(b, y); err != nil {\n\t\treturn nil, &ParseError{path, err}\n\t}\n\tif len(y[\"clouds\"]) == 0 {\n\t\treturn nil, &ParseError{path, errors.New(\"config is empty\")}\n\t}\n\n\tclouds := map[string]gophercloud.AuthOptions{}\n\tfor k, v := range y[\"clouds\"] {\n\t\tif a, ok := v[\"auth\"]; ok {\n\t\t\tclouds[k] = gophercloud.AuthOptions{\n\t\t\t\tIdentityEndpoint: a.AuthURL,\n\t\t\t\tPassword: a.Password,\n\t\t\t\tTenantID: a.TenantID,\n\t\t\t\tTenantName: a.TenantName,\n\t\t\t\tUsername: a.Username,\n\t\t\t}\n\t\t}\n\t}\n\treturn &configImpl{clouds: clouds}, nil\n}", "func (f *ConfigMapFactory) MakeConfigMap(\n\targs *types.ConfigMapArgs, options *types.GeneratorOptions) (*corev1.ConfigMap, error) {\n\tvar all []kv.Pair\n\tvar err error\n\tcm := f.makeFreshConfigMap(args)\n\n\tpairs, err := keyValuesFromEnvFile(f.ldr, args.EnvSource)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\n\t\t\t\"env source file: %s\",\n\t\t\targs.EnvSource))\n\t}\n\tall = append(all, pairs...)\n\n\tpairs, err = keyValuesFromLiteralSources(args.LiteralSources)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\n\t\t\t\"literal sources %v\", args.LiteralSources))\n\t}\n\tall = append(all, pairs...)\n\n\tpairs, err = keyValuesFromFileSources(f.ldr, args.FileSources)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\n\t\t\t\"file sources: %v\", args.FileSources))\n\t}\n\tall = append(all, pairs...)\n\n\tfor _, p := range all {\n\t\terr = addKvToConfigMap(cm, p.Key, p.Value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif options != nil {\n\t\tcm.SetLabels(options.Labels)\n\t\tcm.SetAnnotations(options.Annotations)\n\t}\n\treturn cm, nil\n}", "func BlockStorageFromConfig(vdiskID string, cs config.Source, dialer ardb.ConnectionDialer) (BlockStorage, error) {\n\t// get configs from source\n\tvdiskConfig, err := config.ReadVdiskStaticConfig(cs, vdiskID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnbdStorageConfig, err := config.ReadNBDStorageConfig(cs, vdiskID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create primary cluster\n\tcluster, err := ardb.NewCluster(nbdStorageConfig.StorageCluster, dialer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create template cluster if needed\n\tvar templateCluster ardb.StorageCluster\n\tif vdiskConfig.Type.TemplateSupport() && nbdStorageConfig.TemplateStorageCluster != nil {\n\t\ttemplateCluster, err = ardb.NewCluster(*nbdStorageConfig.TemplateStorageCluster, dialer)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// create block storage config\n\tcfg := BlockStorageConfig{\n\t\tVdiskID: vdiskID,\n\t\tTemplateVdiskID: vdiskConfig.TemplateVdiskID,\n\t\tVdiskType: vdiskConfig.Type,\n\t\tBlockSize: int64(vdiskConfig.BlockSize),\n\t\tLBACacheLimit: ardb.DefaultLBACacheLimit,\n\t}\n\n\t// try to create actual block storage\n\treturn NewBlockStorage(cfg, cluster, templateCluster)\n}", "func ConfigMapFromTestFile(t *testing.T, name string, allowed ...string) *corev1.ConfigMap {\n\tt.Helper()\n\n\tb, err := ioutil.ReadFile(fmt.Sprintf(\"testdata/%s.yaml\", name))\n\tif err != nil {\n\t\tt.Fatalf(\"ReadFile() = %v\", err)\n\t}\n\n\tvar cm corev1.ConfigMap\n\n\t// Use github.com/ghodss/yaml since it reads json struct\n\t// tags so things unmarshal properly\n\tif err := yaml.Unmarshal(b, &cm); err != nil {\n\t\tt.Fatalf(\"yaml.Unmarshal() = %v\", err)\n\t}\n\n\tif len(cm.Data) != len(allowed) {\n\t\t// See here for why we only check in empty ConfigMaps:\n\t\t// https://github.com/knative/serving/issues/2668\n\t\tt.Errorf(\"Data = %v, wanted allowed\", cm.Data)\n\t}\n\tallow := sets.NewString(allowed...)\n\tfor key := range cm.Data {\n\t\tif !allow.Has(key) {\n\t\t\tt.Errorf(\"Encountered key %q in %q that wasn't on the allowed list\", key, name)\n\t\t}\n\t}\n\n\t// If the ConfigMap has no data entries, then make sure we don't have\n\t// a `data:` key, or it will undo the whole motivation for leaving the\n\t// data empty: https://github.com/knative/serving/issues/2668\n\tif len(cm.Data) == 0 {\n\t\tvar u unstructured.Unstructured\n\t\tif err := yaml.Unmarshal(b, &u); err != nil {\n\t\t\tt.Errorf(\"yaml.Unmarshal(%q) = %v\", name, err)\n\t\t}\n\t\tif _, ok := u.Object[\"data\"]; ok {\n\t\t\tt.Errorf(\"%q should omit its empty `data:` section.\", name)\n\t\t}\n\t}\n\n\treturn &cm\n}", "func NewConfig(configFile string) Config {\n\tdata, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar config Config\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn config\n}", "func NewMemoryConfig(c map[string]interface{}) *MemoryConfig {\n if c == nil {\n c = make(map[string]interface{})\n }\n return &MemoryConfig{c}\n}", "func NewConfig() *Config {\n\treturn &Config{v: make(map[string]string)}\n}", "func GetConfigmap(namespace string, configmapName string, testData string) *v1.ConfigMap {\n\treturn &v1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: configmapName,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{\"firstLabel\": \"temp\"},\n\t\t},\n\t\tData: map[string]string{\"test.url\": testData},\n\t}\n}", "func NewIngestedFSFromConfig(ctx context.Context, _ *config.InstanceConfig, local bool) (fs.FS, error) {\n\t// We currently default to Google Cloud Storage, but Config options could be\n\t// added to use other systems, such as S3.\n\treturn gcs.New(ctx, local)\n}", "func RemoveConfigMap(namespace string, configmapName string) error {\n\n\tconfigMap := NewConfigMap(\n\t\tconfigmapName,\n\t\tnamespace,\n\t\tmap[string]string{},\n\t)\n\n\terr := sdk.Delete(configMap)\n\tif err != nil && !errors.IsNotFound(err) {\n\t\treturn fmt.Errorf(\"Failure deleting %v configmap: %v\", configmapName, err)\n\t}\n\n\treturn nil\n}", "func persistDecryptedConfigMap(decryptedConfigMap []byte) error {\n\n\terr := os.MkdirAll(rakshSecretVMTEEMountPoint, os.ModeDir)\n\tif err != nil {\n\t\tlog.Debug(\"Unable to create directory for storing decrypted configMap\")\n\t\treturn err\n\t}\n\tdecryptCMFile := filepath.Join(rakshSecretVMTEEMountPoint, \"decryptedConfigMap\")\n\tlog.Debug(\"Write decrypted configmap into: \", decryptCMFile)\n\terr = ioutil.WriteFile(decryptCMFile, decryptedConfigMap, 0644)\n\treturn err\n}", "func ExportStorageConfFromURI(path string) (roachpb.ExportStorage, error) {\n\tconf := roachpb.ExportStorage{}\n\turi, err := url.Parse(path)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\tswitch uri.Scheme {\n\tcase \"s3\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_S3\n\t\tconf.S3Config = &roachpb.ExportStorage_S3{\n\t\t\tBucket: uri.Host,\n\t\t\tPrefix: uri.Path,\n\t\t\tAccessKey: uri.Query().Get(S3AccessKeyParam),\n\t\t\tSecret: uri.Query().Get(S3SecretParam),\n\t\t\tEndpoint: uri.Query().Get(S3EndpointParam),\n\t\t\tRegion: uri.Query().Get(S3RegionParam),\n\t\t}\n\t\tif conf.S3Config.AccessKey == \"\" {\n\t\t\treturn conf, errors.Errorf(\"s3 uri missing %q parameter\", S3AccessKeyParam)\n\t\t}\n\t\tif conf.S3Config.Secret == \"\" {\n\t\t\treturn conf, errors.Errorf(\"s3 uri missing %q parameter\", S3SecretParam)\n\t\t}\n\t\tconf.S3Config.Prefix = strings.TrimLeft(conf.S3Config.Prefix, \"/\")\n\t\t// AWS secrets often contain + characters, which must be escaped when\n\t\t// included in a query string; otherwise, they represent a space character.\n\t\t// More than a few users have been bitten by this.\n\t\t//\n\t\t// Luckily, AWS secrets are base64-encoded data and thus will never actually\n\t\t// contain spaces. We can convert any space characters we see to +\n\t\t// characters to recover the original secret.\n\t\tconf.S3Config.Secret = strings.Replace(conf.S3Config.Secret, \" \", \"+\", -1)\n\tcase \"gs\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_GoogleCloud\n\t\tconf.GoogleCloudConfig = &roachpb.ExportStorage_GCS{\n\t\t\tBucket: uri.Host,\n\t\t\tPrefix: uri.Path,\n\t\t\tAuth: uri.Query().Get(AuthParam),\n\t\t}\n\t\tconf.GoogleCloudConfig.Prefix = strings.TrimLeft(conf.GoogleCloudConfig.Prefix, \"/\")\n\tcase \"azure\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_Azure\n\t\tconf.AzureConfig = &roachpb.ExportStorage_Azure{\n\t\t\tContainer: uri.Host,\n\t\t\tPrefix: uri.Path,\n\t\t\tAccountName: uri.Query().Get(AzureAccountNameParam),\n\t\t\tAccountKey: uri.Query().Get(AzureAccountKeyParam),\n\t\t}\n\t\tif conf.AzureConfig.AccountName == \"\" {\n\t\t\treturn conf, errors.Errorf(\"azure uri missing %q parameter\", AzureAccountNameParam)\n\t\t}\n\t\tif conf.AzureConfig.AccountKey == \"\" {\n\t\t\treturn conf, errors.Errorf(\"azure uri missing %q parameter\", AzureAccountKeyParam)\n\t\t}\n\t\tconf.AzureConfig.Prefix = strings.TrimLeft(conf.AzureConfig.Prefix, \"/\")\n\tcase \"http\", \"https\":\n\t\tconf.Provider = roachpb.ExportStorageProvider_Http\n\t\tconf.HttpPath.BaseUri = path\n\tcase \"nodelocal\":\n\t\tif uri.Host != \"\" {\n\t\t\treturn conf, errors.Errorf(\"nodelocal does not support hosts: %s\", path)\n\t\t}\n\t\tconf.Provider = roachpb.ExportStorageProvider_LocalFile\n\t\tconf.LocalFile.Path = uri.Path\n\tdefault:\n\t\treturn conf, errors.Errorf(\"unsupported storage scheme: %q\", uri.Scheme)\n\t}\n\treturn conf, nil\n}", "func (o IopingSpecVolumeVolumeSourcePtrOutput) ConfigMap() IopingSpecVolumeVolumeSourceConfigMapPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSource) *IopingSpecVolumeVolumeSourceConfigMap {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ConfigMap\n\t}).(IopingSpecVolumeVolumeSourceConfigMapPtrOutput)\n}", "func NewStorage(config StorageConfig) (spec.Storage, error) {\n\tnewStorage := &storage{\n\t\tStorageConfig: config,\n\n\t\tID: id.MustNew(),\n\t\tShutdownOnce: sync.Once{},\n\t\tType: ObjectType,\n\t}\n\n\t// Dependencies.\n\tif newStorage.Log == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"logger must not be empty\")\n\t}\n\tif newStorage.Pool == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"connection pool must not be empty\")\n\t}\n\t// Settings.\n\tif newStorage.BackOffFactory == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"backoff factory must not be empty\")\n\t}\n\tif newStorage.Prefix == \"\" {\n\t\treturn nil, maskAnyf(invalidConfigError, \"prefix must not be empty\")\n\t}\n\n\tnewStorage.Log.Register(newStorage.GetType())\n\n\treturn newStorage, nil\n}", "func addConfigMap(\n\tldr ifc.KvLoader,\n\tk *types.Kustomization,\n\tflags flagsAndArgs, rf *resource.Factory) error {\n\targs := findOrMakeConfigMapArgs(k, flags.Name)\n\tmergeFlagsIntoCmArgs(args, flags)\n\t// Validate by trying to create corev1.configmap.\n\targs.Options = types.MergeGlobalOptionsIntoLocal(\n\t\targs.Options, k.GeneratorOptions)\n\t_, err := rf.MakeConfigMap(ldr, args)\n\treturn err\n}" ]
[ "0.6375633", "0.6281944", "0.6112564", "0.6053278", "0.5994375", "0.5984264", "0.58559567", "0.583777", "0.58275783", "0.58275783", "0.58275783", "0.5785979", "0.5637561", "0.560425", "0.5552387", "0.5518179", "0.5495444", "0.54701823", "0.5440394", "0.5195264", "0.51931673", "0.5182288", "0.5077997", "0.5064429", "0.5040116", "0.50224197", "0.5016895", "0.5008437", "0.4971331", "0.49516028", "0.49456573", "0.4935364", "0.49336165", "0.49330786", "0.48839644", "0.48715654", "0.48563305", "0.48557007", "0.48520848", "0.48473486", "0.484051", "0.48377982", "0.482482", "0.48235625", "0.48122448", "0.4808947", "0.4808494", "0.48052263", "0.47993487", "0.47978368", "0.476478", "0.47614756", "0.47611937", "0.4743925", "0.47404036", "0.47376084", "0.4732293", "0.46973166", "0.46946904", "0.46913445", "0.46902347", "0.4683699", "0.46796197", "0.46684182", "0.466613", "0.4658605", "0.4649999", "0.46408755", "0.46395326", "0.46320334", "0.46177548", "0.46174508", "0.46086138", "0.46083227", "0.46060836", "0.46043822", "0.46030316", "0.45977938", "0.45954958", "0.4591161", "0.45722294", "0.4571784", "0.45646167", "0.45508245", "0.45477253", "0.45448235", "0.45435515", "0.45424944", "0.45394674", "0.45348448", "0.45181027", "0.45164922", "0.45119888", "0.45117682", "0.45067364", "0.45064622", "0.4501555", "0.44920632", "0.4489431", "0.448833" ]
0.7016705
0
fixEndpoint removes the scheme from the endpoint
func (bc *BucketConfig) fixEndpoint() { if u, err := url.Parse(bc.Endpoint); err == nil { bc.Endpoint = u.Host if strings.ToLower(u.Scheme) == "https" { bc.Secure = true } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func normEndpoint(url string) string {\n\tif len(url) > 0 {\n\t\tif url[len(url)-1] != '/' {\n\t\t\turl += \"/\"\n\t\t}\n\t\treturn url\n\t}\n\tpanic(\"az: invalid endpoint\")\n}", "func stripProtocol(ref string) string {\n\tif strings.HasPrefix(ref, \"/ipfs/\") {\n\t\treturn ref[len(\"/ipfs/\"):]\n\t}\n\treturn ref\n}", "func sanitizeAdaptorEndpoint(endp string) string {\n\tendp = strings.Trim(endp, \"/\")\n\n\tif strings.HasPrefix(endp, \"localhost\") {\n\t\t// Replace localhost in case we are running insde docker\n\t\tif mode := os.Getenv(\"MODE\"); len(mode) > 0 && mode == \"docker\" {\n\t\t\treturn strings.Replace(endp, \"localhost\", \"host.docker.internal\", 1)\n\t\t}\n\t}\n\n\treturn endp\n}", "func stripPort(rawurl string) string {\n\tu, err := url.Parse(rawurl)\n\tif err != nil {\n\t\treturn rawurl\n\t}\n\tu.Host = u.Hostname()\n\treturn u.String()\n}", "func TestStripStandardPorts(t *testing.T) {\n\tapiEndpoints := []string{\"http://127.0.0.1:9000\", \"http://127.0.0.2:80\", \"https://127.0.0.3:443\"}\n\texpectedAPIEndpoints := []string{\"http://127.0.0.1:9000\", \"http://127.0.0.2\", \"https://127.0.0.3\"}\n\tnewAPIEndpoints := stripStandardPorts(apiEndpoints)\n\n\tif !reflect.DeepEqual(expectedAPIEndpoints, newAPIEndpoints) {\n\t\tt.Fatalf(\"Expected %#v, got %#v\", expectedAPIEndpoints, newAPIEndpoints)\n\t}\n\n\tapiEndpoints = []string{\"http://%%%%%:9000\"}\n\tnewAPIEndpoints = stripStandardPorts(apiEndpoints)\n\tif !reflect.DeepEqual(apiEndpoints, newAPIEndpoints) {\n\t\tt.Fatalf(\"Expected %#v, got %#v\", apiEndpoints, newAPIEndpoints)\n\t}\n\n\tapiEndpoints = []string{\"http://127.0.0.1:443\", \"https://127.0.0.1:80\"}\n\tnewAPIEndpoints = stripStandardPorts(apiEndpoints)\n\tif !reflect.DeepEqual(apiEndpoints, newAPIEndpoints) {\n\t\tt.Fatalf(\"Expected %#v, got %#v\", apiEndpoints, newAPIEndpoints)\n\t}\n}", "func (ec *ExtensionClient) UpdateEndpoint(endpoint *extension.ExtensionEndpoint) (res *extension.ExtensionEndpoint, err error) {\n\n\turl := url.QueryEscape(*endpoint.URL)\n\tendpoint.URL = &url\n\tresponse, err := ec.c.UpdateEndpoint()(context.Background(), endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response.(*extension.ExtensionEndpoint), nil\n}", "func ParseEndpoint(\n\tscheme, host string,\n\tdoer goahttp.Doer,\n\tenc func(*http.Request) goahttp.Encoder,\n\tdec func(*http.Response) goahttp.Decoder,\n\trestore bool,\n) (goa.Endpoint, interface{}, error) {\n\tvar (\n\t\tfooFlags = flag.NewFlagSet(\"foo\", flag.ContinueOnError)\n\n\t\tfooFoo1Flags = flag.NewFlagSet(\"foo1\", flag.ExitOnError)\n\t\tfooFoo1PFlag = fooFoo1Flags.String(\"p\", \"REQUIRED\", \"int is the payload type of the foo service foo1 method.\")\n\n\t\tfooFoo2Flags = flag.NewFlagSet(\"foo2\", flag.ExitOnError)\n\t\tfooFoo2PFlag = fooFoo2Flags.String(\"p\", \"REQUIRED\", \"int is the payload type of the foo service foo2 method.\")\n\n\t\tfooFoo3Flags = flag.NewFlagSet(\"foo3\", flag.ExitOnError)\n\t\tfooFoo3PFlag = fooFoo3Flags.String(\"p\", \"REQUIRED\", \"int is the payload type of the foo service foo3 method.\")\n\n\t\tfooFooOptionsFlags = flag.NewFlagSet(\"foo-options\", flag.ExitOnError)\n\t)\n\tfooFlags.Usage = fooUsage\n\tfooFoo1Flags.Usage = fooFoo1Usage\n\tfooFoo2Flags.Usage = fooFoo2Usage\n\tfooFoo3Flags.Usage = fooFoo3Usage\n\tfooFooOptionsFlags.Usage = fooFooOptionsUsage\n\n\tif err := flag.CommandLine.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif flag.NArg() < 2 { // two non flag args are required: SERVICE and ENDPOINT (aka COMMAND)\n\t\treturn nil, nil, fmt.Errorf(\"not enough arguments\")\n\t}\n\n\tvar (\n\t\tsvcn string\n\t\tsvcf *flag.FlagSet\n\t)\n\t{\n\t\tsvcn = flag.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"foo\":\n\t\t\tsvcf = fooFlags\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown service %q\", svcn)\n\t\t}\n\t}\n\tif err := svcf.Parse(flag.Args()[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tepn string\n\t\tepf *flag.FlagSet\n\t)\n\t{\n\t\tepn = svcf.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"foo\":\n\t\t\tswitch epn {\n\t\t\tcase \"foo1\":\n\t\t\t\tepf = fooFoo1Flags\n\n\t\t\tcase \"foo2\":\n\t\t\t\tepf = fooFoo2Flags\n\n\t\t\tcase \"foo3\":\n\t\t\t\tepf = fooFoo3Flags\n\n\t\t\tcase \"foo-options\":\n\t\t\t\tepf = fooFooOptionsFlags\n\n\t\t\t}\n\n\t\t}\n\t}\n\tif epf == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unknown %q endpoint %q\", svcn, epn)\n\t}\n\n\t// Parse endpoint flags if any\n\tif svcf.NArg() > 1 {\n\t\tif err := epf.Parse(svcf.Args()[1:]); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tdata interface{}\n\t\tendpoint goa.Endpoint\n\t\terr error\n\t)\n\t{\n\t\tswitch svcn {\n\t\tcase \"foo\":\n\t\t\tc := fooc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"foo1\":\n\t\t\t\tendpoint = c.Foo1()\n\t\t\t\tvar err error\n\t\t\t\tvar v int64\n\t\t\t\tv, err = strconv.ParseInt(*fooFoo1PFlag, 10, 64)\n\t\t\t\tdata = int(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid value for fooFoo1PFlag, must be INT\")\n\t\t\t\t}\n\t\t\tcase \"foo2\":\n\t\t\t\tendpoint = c.Foo2()\n\t\t\t\tvar err error\n\t\t\t\tvar v int64\n\t\t\t\tv, err = strconv.ParseInt(*fooFoo2PFlag, 10, 64)\n\t\t\t\tdata = int(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid value for fooFoo2PFlag, must be INT\")\n\t\t\t\t}\n\t\t\tcase \"foo3\":\n\t\t\t\tendpoint = c.Foo3()\n\t\t\t\tvar err error\n\t\t\t\tvar v int64\n\t\t\t\tv, err = strconv.ParseInt(*fooFoo3PFlag, 10, 64)\n\t\t\t\tdata = int(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"invalid value for fooFoo3PFlag, must be INT\")\n\t\t\t\t}\n\t\t\tcase \"foo-options\":\n\t\t\t\tendpoint = c.FooOptions()\n\t\t\t\tdata = nil\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn endpoint, data, nil\n}", "func TestStripStandardPorts(t *testing.T) {\n\tapiEndpoints := []string{\"http://127.0.0.1:9000\", \"http://127.0.0.2:80\", \"https://127.0.0.3:443\"}\n\texpectedAPIEndpoints := []string{\"http://127.0.0.1:9000\", \"http://127.0.0.2\", \"https://127.0.0.3\"}\n\tnewAPIEndpoints := stripStandardPorts(apiEndpoints, \"\")\n\n\tif !reflect.DeepEqual(expectedAPIEndpoints, newAPIEndpoints) {\n\t\tt.Fatalf(\"Expected %#v, got %#v\", expectedAPIEndpoints, newAPIEndpoints)\n\t}\n\n\tapiEndpoints = []string{\"http://%%%%%:9000\"}\n\tnewAPIEndpoints = stripStandardPorts(apiEndpoints, \"\")\n\tif !reflect.DeepEqual([]string{\"\"}, newAPIEndpoints) {\n\t\tt.Fatalf(\"Expected %#v, got %#v\", apiEndpoints, newAPIEndpoints)\n\t}\n\n\tapiEndpoints = []string{\"http://127.0.0.1:443\", \"https://127.0.0.1:80\"}\n\tnewAPIEndpoints = stripStandardPorts(apiEndpoints, \"\")\n\tif !reflect.DeepEqual(apiEndpoints, newAPIEndpoints) {\n\t\tt.Fatalf(\"Expected %#v, got %#v\", apiEndpoints, newAPIEndpoints)\n\t}\n}", "func (options *UpdateNotificationChannelOptions) SetEndpoint(endpoint string) *UpdateNotificationChannelOptions {\n\toptions.Endpoint = core.StringPtr(endpoint)\n\treturn options\n}", "func (sp *SessionProxy) DelEndpoint(sid string) { sp.GetSession().DelEndpoint(sid) }", "func ParseEndpoint(\n\tscheme, host string,\n\tdoer goahttp.Doer,\n\tenc func(*http.Request) goahttp.Encoder,\n\tdec func(*http.Response) goahttp.Decoder,\n\trestore bool,\n) (goa.Endpoint, interface{}, error) {\n\tvar (\n\t\tneatThingFlags = flag.NewFlagSet(\"neat-thing\", flag.ContinueOnError)\n\n\t\tneatThingNeatThingTodayFlags = flag.NewFlagSet(\"neat-thing-today\", flag.ExitOnError)\n\n\t\tneatThingNewNeatThingFlags = flag.NewFlagSet(\"new-neat-thing\", flag.ExitOnError)\n\t\tneatThingNewNeatThingBodyFlag = neatThingNewNeatThingFlags.String(\"body\", \"REQUIRED\", \"\")\n\t)\n\tneatThingFlags.Usage = neatThingUsage\n\tneatThingNeatThingTodayFlags.Usage = neatThingNeatThingTodayUsage\n\tneatThingNewNeatThingFlags.Usage = neatThingNewNeatThingUsage\n\n\tif err := flag.CommandLine.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif flag.NArg() < 2 { // two non flag args are required: SERVICE and ENDPOINT (aka COMMAND)\n\t\treturn nil, nil, fmt.Errorf(\"not enough arguments\")\n\t}\n\n\tvar (\n\t\tsvcn string\n\t\tsvcf *flag.FlagSet\n\t)\n\t{\n\t\tsvcn = flag.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"neat-thing\":\n\t\t\tsvcf = neatThingFlags\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown service %q\", svcn)\n\t\t}\n\t}\n\tif err := svcf.Parse(flag.Args()[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tepn string\n\t\tepf *flag.FlagSet\n\t)\n\t{\n\t\tepn = svcf.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"neat-thing\":\n\t\t\tswitch epn {\n\t\t\tcase \"neat-thing-today\":\n\t\t\t\tepf = neatThingNeatThingTodayFlags\n\n\t\t\tcase \"new-neat-thing\":\n\t\t\t\tepf = neatThingNewNeatThingFlags\n\n\t\t\t}\n\n\t\t}\n\t}\n\tif epf == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unknown %q endpoint %q\", svcn, epn)\n\t}\n\n\t// Parse endpoint flags if any\n\tif svcf.NArg() > 1 {\n\t\tif err := epf.Parse(svcf.Args()[1:]); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tdata interface{}\n\t\tendpoint goa.Endpoint\n\t\terr error\n\t)\n\t{\n\t\tswitch svcn {\n\t\tcase \"neat-thing\":\n\t\t\tc := neatthingc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"neat-thing-today\":\n\t\t\t\tendpoint = c.NeatThingToday()\n\t\t\t\tdata = nil\n\t\t\tcase \"new-neat-thing\":\n\t\t\t\tendpoint = c.NewNeatThing()\n\t\t\t\tdata, err = neatthingc.BuildNewNeatThingPayload(*neatThingNewNeatThingBodyFlag)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn endpoint, data, nil\n}", "func WithEndpoint(endpoint string) {\n\tcfg.endpoint = strings.TrimRight(endpoint, \"/\")\n}", "func (options *CreateNotificationChannelOptions) SetEndpoint(endpoint string) *CreateNotificationChannelOptions {\n\toptions.Endpoint = core.StringPtr(endpoint)\n\treturn options\n}", "func TestEndpointCase46(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(true),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: FIPS and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func TestEndpointCase45(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func delEndpoint(domain string, addr string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tservice, ok := registryMap[domain]\n\tif ok == false {\n\t\treturn ErrServiceNotFound\n\t}\n\tfor k, item := range service.Items {\n\t\tif item.Endpoint == addr {\n\t\t\tendpoints := append(service.Items[:k], service.Items[k+1:]...)\n\t\t\tservice.Items = endpoints\n\t\t\tbreak\n\t\t}\n\t}\n\tregistryMap[domain] = service\n\treturn nil\n}", "func (s *sanitizer) forceHttpScheme(l string) string {\n\tfor _, sch := range s.URISchemes {\n\t\tif strings.HasPrefix(l, sch) {\n\t\t\treturn l\n\t\t}\n\t}\n\treturn \"http://\" + l\n}", "func NormalizeGatewayURL(urlstr string) string {\n\tif !strings.HasPrefix(urlstr, \"http\") {\n\t\turlstr = \"http://\" + urlstr\n\t}\n\tu, err := url.Parse(urlstr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tscheme := u.Scheme\n\tif u.Scheme != \"\" {\n\t\tscheme = \"http\"\n\t}\n\n\thost := u.Hostname()\n\tif host == \"\" {\n\t\thost = \"ipfs.io\"\n\t}\n\n\tvar user string\n\tif u.User != nil {\n\t\tuser = u.User.String() + \"@\"\n\t}\n\n\tport := u.Port()\n\tif port != \"\" {\n\t\tport = \":\" + port\n\t}\n\n\treturn fmt.Sprintf(\"%s://%s%s%s\", scheme, user, host, port)\n}", "func (p *fullEndpoint) replace(newValue *Endpoint, self wire.Address, dialer bool) (updated *Endpoint, closed bool) {\n\t// If there was no previous endpoint, just set the new one.\n\twasNil := atomic.CompareAndSwapPointer(&p.endpoint, nil, unsafe.Pointer(newValue))\n\tif wasNil {\n\t\treturn newValue, false\n\t}\n\n\t// If an endpoint already exists, we are in a race where both parties dialed\n\t// each other concurrently. Deterministically select the same connection to\n\t// close on both sides. Close the endpoint that is created by the dialer\n\t// with the lesser Perun address and return the previously existing\n\t// endpoint.\n\tif dialer == (self.Cmp(newValue.Address) < 0) {\n\t\tif err := newValue.Close(); err != nil {\n\t\t\tlog.Warn(\"newValue dialer already closed\")\n\t\t}\n\t\treturn p.Endpoint(), true\n\t}\n\n\t// Otherwise, install the new endpoint and close the old endpoint.\n\told := atomic.SwapPointer(&p.endpoint, unsafe.Pointer(newValue))\n\tif old != nil {\n\t\t// It may be possible that in the meanwhile, the peer might have been\n\t\t// replaced by another goroutine.\n\t\tif err := (*Endpoint)(old).Close(); err != nil {\n\t\t\tlog.Warn(\"Old Endpoint was already closed\")\n\t\t}\n\t}\n\n\treturn newValue, false\n}", "func ParseEndpoint(\n\tscheme, host string,\n\tdoer goahttp.Doer,\n\tenc func(*http.Request) goahttp.Encoder,\n\tdec func(*http.Response) goahttp.Decoder,\n\trestore bool,\n) (goa.Endpoint, interface{}, error) {\n\tvar (\n\t\tuserServiceFlags = flag.NewFlagSet(\"user-service\", flag.ContinueOnError)\n\n\t\tuserServiceSignupFlags = flag.NewFlagSet(\"signup\", flag.ExitOnError)\n\t\tuserServiceSignupBodyFlag = userServiceSignupFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceSignupTenantFlag = userServiceSignupFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\n\t\tuserServiceVerifyConfirmationTokenFlags = flag.NewFlagSet(\"verify-confirmation-token\", flag.ExitOnError)\n\t\tuserServiceVerifyConfirmationTokenBodyFlag = userServiceVerifyConfirmationTokenFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceVerifyConfirmationTokenTenantFlag = userServiceVerifyConfirmationTokenFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\n\t\tuserServiceUpdateUsernameFlags = flag.NewFlagSet(\"update-username\", flag.ExitOnError)\n\t\tuserServiceUpdateUsernameBodyFlag = userServiceUpdateUsernameFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceUpdateUsernameTenantFlag = userServiceUpdateUsernameFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\t\tuserServiceUpdateUsernameTokenFlag = userServiceUpdateUsernameFlags.String(\"token\", \"REQUIRED\", \"\")\n\n\t\tuserServiceVerifyPasswordResetTokenFlags = flag.NewFlagSet(\"verify-password-reset-token\", flag.ExitOnError)\n\t\tuserServiceVerifyPasswordResetTokenBodyFlag = userServiceVerifyPasswordResetTokenFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceVerifyPasswordResetTokenTenantFlag = userServiceVerifyPasswordResetTokenFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\n\t\tuserServiceResetPasswordFlags = flag.NewFlagSet(\"reset-password\", flag.ExitOnError)\n\t\tuserServiceResetPasswordBodyFlag = userServiceResetPasswordFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceResetPasswordTenantFlag = userServiceResetPasswordFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\n\t\tuserServiceChangePasswordFlags = flag.NewFlagSet(\"change-password\", flag.ExitOnError)\n\t\tuserServiceChangePasswordBodyFlag = userServiceChangePasswordFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceChangePasswordTenantFlag = userServiceChangePasswordFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\t\tuserServiceChangePasswordTokenFlag = userServiceChangePasswordFlags.String(\"token\", \"REQUIRED\", \"\")\n\n\t\tuserServiceLoginFlags = flag.NewFlagSet(\"login\", flag.ExitOnError)\n\t\tuserServiceLoginBodyFlag = userServiceLoginFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceLoginTenantFlag = userServiceLoginFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\n\t\tuserServiceRefreshAccessTokenFlags = flag.NewFlagSet(\"refresh-access-token\", flag.ExitOnError)\n\t\tuserServiceRefreshAccessTokenTenantFlag = userServiceRefreshAccessTokenFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\t\tuserServiceRefreshAccessTokenTokenFlag = userServiceRefreshAccessTokenFlags.String(\"token\", \"REQUIRED\", \"\")\n\n\t\tuserServiceLogoutFlags = flag.NewFlagSet(\"logout\", flag.ExitOnError)\n\t\tuserServiceLogoutTenantFlag = userServiceLogoutFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\t\tuserServiceLogoutTokenFlag = userServiceLogoutFlags.String(\"token\", \"REQUIRED\", \"\")\n\n\t\tuserServiceListUsersFlags = flag.NewFlagSet(\"list-users\", flag.ExitOnError)\n\t\tuserServiceListUsersBodyFlag = userServiceListUsersFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\tuserServiceListUsersTenantFlag = userServiceListUsersFlags.String(\"tenant\", \"REQUIRED\", \"\")\n\t\tuserServiceListUsersTokenFlag = userServiceListUsersFlags.String(\"token\", \"REQUIRED\", \"\")\n\t)\n\tuserServiceFlags.Usage = userServiceUsage\n\tuserServiceSignupFlags.Usage = userServiceSignupUsage\n\tuserServiceVerifyConfirmationTokenFlags.Usage = userServiceVerifyConfirmationTokenUsage\n\tuserServiceUpdateUsernameFlags.Usage = userServiceUpdateUsernameUsage\n\tuserServiceVerifyPasswordResetTokenFlags.Usage = userServiceVerifyPasswordResetTokenUsage\n\tuserServiceResetPasswordFlags.Usage = userServiceResetPasswordUsage\n\tuserServiceChangePasswordFlags.Usage = userServiceChangePasswordUsage\n\tuserServiceLoginFlags.Usage = userServiceLoginUsage\n\tuserServiceRefreshAccessTokenFlags.Usage = userServiceRefreshAccessTokenUsage\n\tuserServiceLogoutFlags.Usage = userServiceLogoutUsage\n\tuserServiceListUsersFlags.Usage = userServiceListUsersUsage\n\n\tif err := flag.CommandLine.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif flag.NArg() < 2 { // two non flag args are required: SERVICE and ENDPOINT (aka COMMAND)\n\t\treturn nil, nil, fmt.Errorf(\"not enough arguments\")\n\t}\n\n\tvar (\n\t\tsvcn string\n\t\tsvcf *flag.FlagSet\n\t)\n\t{\n\t\tsvcn = flag.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"user-service\":\n\t\t\tsvcf = userServiceFlags\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown service %q\", svcn)\n\t\t}\n\t}\n\tif err := svcf.Parse(flag.Args()[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tepn string\n\t\tepf *flag.FlagSet\n\t)\n\t{\n\t\tepn = svcf.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"user-service\":\n\t\t\tswitch epn {\n\t\t\tcase \"signup\":\n\t\t\t\tepf = userServiceSignupFlags\n\n\t\t\tcase \"verify-confirmation-token\":\n\t\t\t\tepf = userServiceVerifyConfirmationTokenFlags\n\n\t\t\tcase \"update-username\":\n\t\t\t\tepf = userServiceUpdateUsernameFlags\n\n\t\t\tcase \"verify-password-reset-token\":\n\t\t\t\tepf = userServiceVerifyPasswordResetTokenFlags\n\n\t\t\tcase \"reset-password\":\n\t\t\t\tepf = userServiceResetPasswordFlags\n\n\t\t\tcase \"change-password\":\n\t\t\t\tepf = userServiceChangePasswordFlags\n\n\t\t\tcase \"login\":\n\t\t\t\tepf = userServiceLoginFlags\n\n\t\t\tcase \"refresh-access-token\":\n\t\t\t\tepf = userServiceRefreshAccessTokenFlags\n\n\t\t\tcase \"logout\":\n\t\t\t\tepf = userServiceLogoutFlags\n\n\t\t\tcase \"list-users\":\n\t\t\t\tepf = userServiceListUsersFlags\n\n\t\t\t}\n\n\t\t}\n\t}\n\tif epf == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unknown %q endpoint %q\", svcn, epn)\n\t}\n\n\t// Parse endpoint flags if any\n\tif svcf.NArg() > 1 {\n\t\tif err := epf.Parse(svcf.Args()[1:]); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tdata interface{}\n\t\tendpoint goa.Endpoint\n\t\terr error\n\t)\n\t{\n\t\tswitch svcn {\n\t\tcase \"user-service\":\n\t\t\tc := userservicec.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"signup\":\n\t\t\t\tendpoint = c.Signup()\n\t\t\t\tdata, err = userservicec.BuildSignupPayload(*userServiceSignupBodyFlag, *userServiceSignupTenantFlag)\n\t\t\tcase \"verify-confirmation-token\":\n\t\t\t\tendpoint = c.VerifyConfirmationToken()\n\t\t\t\tdata, err = userservicec.BuildVerifyConfirmationTokenPayload(*userServiceVerifyConfirmationTokenBodyFlag, *userServiceVerifyConfirmationTokenTenantFlag)\n\t\t\tcase \"update-username\":\n\t\t\t\tendpoint = c.UpdateUsername()\n\t\t\t\tdata, err = userservicec.BuildUpdateUsernamePayload(*userServiceUpdateUsernameBodyFlag, *userServiceUpdateUsernameTenantFlag, *userServiceUpdateUsernameTokenFlag)\n\t\t\tcase \"verify-password-reset-token\":\n\t\t\t\tendpoint = c.VerifyPasswordResetToken()\n\t\t\t\tdata, err = userservicec.BuildVerifyPasswordResetTokenPayload(*userServiceVerifyPasswordResetTokenBodyFlag, *userServiceVerifyPasswordResetTokenTenantFlag)\n\t\t\tcase \"reset-password\":\n\t\t\t\tendpoint = c.ResetPassword()\n\t\t\t\tdata, err = userservicec.BuildResetPasswordPayload(*userServiceResetPasswordBodyFlag, *userServiceResetPasswordTenantFlag)\n\t\t\tcase \"change-password\":\n\t\t\t\tendpoint = c.ChangePassword()\n\t\t\t\tdata, err = userservicec.BuildChangePasswordPayload(*userServiceChangePasswordBodyFlag, *userServiceChangePasswordTenantFlag, *userServiceChangePasswordTokenFlag)\n\t\t\tcase \"login\":\n\t\t\t\tendpoint = c.Login()\n\t\t\t\tdata, err = userservicec.BuildLoginPayload(*userServiceLoginBodyFlag, *userServiceLoginTenantFlag)\n\t\t\tcase \"refresh-access-token\":\n\t\t\t\tendpoint = c.RefreshAccessToken()\n\t\t\t\tdata, err = userservicec.BuildRefreshAccessTokenPayload(*userServiceRefreshAccessTokenTenantFlag, *userServiceRefreshAccessTokenTokenFlag)\n\t\t\tcase \"logout\":\n\t\t\t\tendpoint = c.Logout()\n\t\t\t\tdata, err = userservicec.BuildLogoutPayload(*userServiceLogoutTenantFlag, *userServiceLogoutTokenFlag)\n\t\t\tcase \"list-users\":\n\t\t\t\tendpoint = c.ListUsers()\n\t\t\t\tdata, err = userservicec.BuildListUsersPayload(*userServiceListUsersBodyFlag, *userServiceListUsersTenantFlag, *userServiceListUsersTokenFlag)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn endpoint, data, nil\n}", "func (op *OperationRequest) setEndpoint(endpoint string) *OperationRequest {\n\tif endpoint == \"payments\" {\n\t\top.endpoint = endpoint\n\t} else {\n\t\t// default to operations\n\t\top.endpoint = \"operations\"\n\t}\n\treturn op\n}", "func fixURL(href, base string) string {\n\turi, err := url.Parse(href)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tbaseURL, err := url.Parse(base)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\turi = baseURL.ResolveReference(uri)\n\treturn uri.String()\n}", "func (s *nameServerScraper) RemoveEndpoint(domain string) {\n\ts.mux.Lock()\n\tdefer s.mux.Unlock()\n\t_, nsMap := s.rootDomainNameServers(domain)\n\tdelete(nsMap, domain)\n}", "func (ep *Endpoint_DEPRECATED) URI() string {\n\tif ep.IsS3() {\n\t\treturn \"s3://\" + ep.S3Bucket + \"/\" + ep.S3Subfolder\n\t} else if ep.IsSFTP() {\n\t\treturn \"sftp://\" + ep.SFTPHostname + \"/\" + ep.SFTPDirectory\n\t}\n\tpanic(\"endpoint type not supported\")\n}", "func Endpoint(rawurl string) Opt {\n\treturn func(c *Client) Opt {\n\t\told := c.url\n\t\tc.url = rawurl\n\t\treturn Endpoint(old)\n\t}\n}", "func (s *HTTPSet) replaceHost(rawurl string) (string, error) {\n\tu, err := url.Parse(rawurl)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thost, err := s.RotateEndpoint()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tu.Host = host\n\tif u.Scheme == \"\" {\n\t\tif s.UseHTTPS {\n\t\t\tu.Scheme = \"https\"\n\t\t} else {\n\t\t\tu.Scheme = \"http\"\n\t\t}\n\t}\n\n\treturn u.String(), nil\n}", "func (s *ServerConfig) SchemaVersioningEndpoint(path string) string {\n\t// if s.Port == \"80\" {\n\t// \treturn s.URISchema + s.Host + \"/\" + s.ApiVer + path\n\t// }\n\treturn s.URISchema + s.Host + \":\" + s.Port + \"/api/\" + s.ApiVer + path\n}", "func TestEndpointCase47(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(true),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid Configuration: Dualstack and custom endpoint are not supported\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func fixURL(href, base string) (string, error) {\n\turi, err := url.Parse(href)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbaseURL, err := url.Parse(base)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\turi = baseURL.ResolveReference(uri)\n\n\treturn uri.String(), err\n}", "func fixUrl(url string) string {\n\turlParts := strings.SplitN(url, \"/\", 2)\n\tif len(urlParts) < 2 {\n\t\treturn \"\"\n\t}\n\n\treturn urlParts[0] + \":\" + urlParts[1]\n}", "func (m *peerMap) deleteEndpoint(ep *endpoint) {\n\tif ep == nil {\n\t\treturn\n\t}\n\tep.stopAndReset()\n\n\tepDisco := ep.disco.Load()\n\n\tpi := m.byNodeKey[ep.publicKey]\n\tif epDisco != nil {\n\t\tdelete(m.nodesOfDisco[epDisco.key], ep.publicKey)\n\t}\n\tdelete(m.byNodeKey, ep.publicKey)\n\tif pi == nil {\n\t\t// Kneejerk paranoia from earlier issue 2801.\n\t\t// Unexpected. But no logger plumbed here to log so.\n\t\treturn\n\t}\n\tfor ip := range pi.ipPorts {\n\t\tdelete(m.byIPPort, ip)\n\t}\n}", "func TestEndpointCase44(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tEndpoint: ptr.String(\"https://example.com\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err != nil {\n\t\tt.Fatalf(\"expect no error, got %v\", err)\n\t}\n\n\turi, _ := url.Parse(\"https://example.com\")\n\n\texpectEndpoint := smithyendpoints.Endpoint{\n\t\tURI: *uri,\n\t\tHeaders: http.Header{},\n\t\tProperties: smithy.Properties{},\n\t}\n\n\tif e, a := expectEndpoint.URI, result.URI; e != a {\n\t\tt.Errorf(\"expect %v URI, got %v\", e, a)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Headers, result.Headers); diff != \"\" {\n\t\tt.Errorf(\"expect headers to match\\n%s\", diff)\n\t}\n\n\tif diff := cmp.Diff(expectEndpoint.Properties, result.Properties,\n\t\tcmp.AllowUnexported(smithy.Properties{}),\n\t); diff != \"\" {\n\t\tt.Errorf(\"expect properties to match\\n%s\", diff)\n\t}\n}", "func (h *HTTPTransport) SetScheme(req *http.Request) {\n\tif req.URL.Scheme != \"\" {\n\t\treturn\n\t}\n\tif h.shouldUseTLS(req) {\n\t\treq.URL.Scheme = \"https\"\n\t} else {\n\t\treq.URL.Scheme = \"http\"\n\t}\n}", "func TrimProtocol(targetURL string, addDefaultPort bool) string {\n\tURL := strings.TrimSpace(targetURL)\n\tif strings.HasPrefix(strings.ToLower(URL), \"http://\") || strings.HasPrefix(strings.ToLower(URL), \"https://\") {\n\t\tif addDefaultPort {\n\t\t\tURL = AddURLDefaultPort(URL)\n\t\t\tURL = URL[strings.Index(URL, \"//\")+2:]\n\t\t}\n\t}\n\n\treturn URL\n}", "func UnmarshalEndpoint(reader io.Reader, consumer runtime.Consumer) (Endpoint, error) {\n\t// we need to read this twice, so first into a buffer\n\tdata, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unmarshalEndpoint(data, consumer)\n}", "func obfuscateEndpoint(endpoint string) string {\n\tres, err := url.Parse(endpoint)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar obfuscatedEndpoint = res.String()\n\n\t// If the user is defined, we try to get the username and password, if defined.\n\t// Then, we update the user with the obfuscated version.\n\tif res.User != nil {\n\t\tif password, ok := res.User.Password(); ok {\n\t\t\tobfuscatedEndpoint = strings.Replace(obfuscatedEndpoint, password, awsSNSPasswordObfuscationPattern, 1)\n\t\t}\n\t}\n\treturn obfuscatedEndpoint\n}", "func (p *Projector) doRepairEndpoints(request *protobuf.RepairDownstreamEndpoints) ap.MessageMarshaller {\n\tc.Debugf(\"%v doRepairEndpoints()\\n\", p.logPrefix)\n\ttopic := request.GetTopic()\n\n\tfeed, err := p.GetFeed(topic)\n\tif err == nil { // only existing feed\n\t\terr = feed.RepairEndpoints(request.GetEndpoints())\n\t} else {\n\t\tc.Errorf(\"%v %v\\n\", p.logPrefix, err)\n\t}\n\treturn protobuf.NewError(err)\n}", "func NormalizeToURI(kind knativev1.CamelServiceType, uriOrString string) string {\n\tif plainNameRegexp.MatchString(uriOrString) {\n\t\treturn fmt.Sprintf(\"knative://%s/%s\", string(kind), uriOrString)\n\t}\n\treturn uriOrString\n}", "func (policy *PolicySvc) augmentEndpoint(endpoint *common.Endpoint) error {\n\ttenantSvcUrl, err := policy.client.GetServiceUrl(\"tenant\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif endpoint.Peer == common.Wildcard {\n\t\t// If a wildcard is specfied, there is nothing to augment\n\t\treturn nil\n\t}\n\tlog.Printf(\"Policy: Augmenting %#v\", endpoint)\n\n\t// Code below tries to resolve tenant name into tenant_network_id if possible.\n\t//\n\t// TODO this will have to be changed once we implement\n\t// https://paninetworks.kanbanize.com/ctrl_board/3/cards/319/details\n\tten := &tenant.Tenant{}\n\tif endpoint.TenantNetworkID == nil {\n\t\tif endpoint.TenantID != 0 {\n\t\t\ttenantIDToUse := strconv.FormatUint(endpoint.TenantID, 10)\n\t\t\ttenantsUrl := fmt.Sprintf(\"%s/tenants/%s\", tenantSvcUrl, tenantIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking tenant up at %s\", tenantsUrl)\n\t\t\terr = policy.client.Get(tenantsUrl, ten)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\n\t\t} else if endpoint.TenantExternalID != \"\" || endpoint.TenantName != \"\" {\n\t\t\tif endpoint.TenantExternalID != \"\" {\n\t\t\t\tten.ExternalID = endpoint.TenantExternalID\n\t\t\t}\n\t\t\tif endpoint.TenantName != \"\" {\n\t\t\t\tten.Name = endpoint.TenantName\n\t\t\t}\n\t\t\terr = policy.client.Find(ten, common.FindLast)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tendpoint.TenantNetworkID = &ten.NetworkID\n\t\t}\n\t}\n\n\tif endpoint.SegmentNetworkID == nil {\n\t\tif ten == nil && (endpoint.SegmentID != 0 || endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\") {\n\t\t\treturn common.NewError400(\"No tenant information specified, cannot look up segment.\")\n\t\t}\n\t\tsegment := &tenant.Segment{}\n\t\tif endpoint.SegmentID != 0 {\n\t\t\tsegmentIDToUse := strconv.FormatUint(endpoint.SegmentID, 10)\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/tenants/%d/segments/%s\", tenantSvcUrl, ten.ID, segmentIDToUse)\n\t\t\tlog.Printf(\"Policy: Looking segment up at %s for %#v\", segmentsUrl, endpoint)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t} else if endpoint.SegmentExternalID != \"\" || endpoint.SegmentName != \"\" {\n\t\t\tsegmentsUrl := fmt.Sprintf(\"%s/findLast/segments?tenant_id=%d&\", tenantSvcUrl, ten.ID)\n\t\t\tif endpoint.SegmentExternalID != \"\" {\n\t\t\t\tsegmentsUrl += \"external_id=\" + endpoint.TenantExternalID + \"&\"\n\t\t\t}\n\t\t\tif endpoint.SegmentName != \"\" {\n\t\t\t\tsegmentsUrl += \"name=\" + endpoint.SegmentName\n\t\t\t}\n\t\t\tlog.Printf(\"Policy: Finding segments at %s for %#v (Tenant %#v %t)\", segmentsUrl, endpoint, ten, ten == nil)\n\t\t\terr = policy.client.Get(segmentsUrl, &segment)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tendpoint.SegmentNetworkID = &segment.NetworkID\n\t\t}\n\t}\n\treturn nil\n}", "func (a *DefaultApiService) DeleteEndpoint(ctx _context.Context, id string) ApiDeleteEndpointRequest {\n\treturn ApiDeleteEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func validateEndPoint(endPointPointer *string) error {\n\tendPoint := *endPointPointer\n\n\tif endPoint == \"\" {\n\t\tendPoint = defaultEndPointURI\n\t}\n\n\tmatch, err := regexp.MatchString(`^\\w+://`, endPoint)\n\tif err != nil {\n\t\treturn util.NewPersistentError(\"InvalidEndpoint\",\n\t\t\tfmt.Sprintf(\"Invalid endpoint url %q: %v\", endPoint, err))\n\t}\n\tif !match {\n\t\tendPoint = \"https://\" + endPoint\n\t}\n\tu, err := url.Parse(endPoint)\n\tif err != nil {\n\t\treturn util.NewPersistentError(\"InvalidEndpoint\",\n\t\t\tfmt.Sprintf(\"Invalid endpoint url %q: %v\", endPoint, err))\n\t}\n\tif u.Scheme == \"\" {\n\t\tu.Scheme = \"https\"\n\t}\n\n\t*endPointPointer = u.String()\n\n\treturn nil\n}", "func (fh *serviceTopologyFilterHandler) reassembleEndpointSlice(endpointSlice *discovery.EndpointSlice) *discovery.EndpointSlice {\n\tvar serviceTopologyType string\n\t// get the service Topology type\n\tif svcName, ok := endpointSlice.Labels[discovery.LabelServiceName]; ok {\n\t\tsvc, err := fh.serviceLister.Services(endpointSlice.Namespace).Get(svcName)\n\t\tif err != nil {\n\t\t\tklog.Infof(\"skip reassemble endpointSlice, failed to get service %s/%s, err: %v\", endpointSlice.Namespace, svcName, err)\n\t\t\treturn endpointSlice\n\t\t}\n\n\t\tif serviceTopologyType, ok = svc.Annotations[AnnotationServiceTopologyKey]; !ok {\n\t\t\tklog.Infof(\"skip reassemble endpointSlice, service %s/%s has no annotation %s\", endpointSlice.Namespace, svcName, AnnotationServiceTopologyKey)\n\t\t\treturn endpointSlice\n\t\t}\n\t}\n\n\tvar newEps []discovery.Endpoint\n\t// if type of service Topology is 'kubernetes.io/hostname'\n\t// filter the endpoint just on the local host\n\tif serviceTopologyType == AnnotationServiceTopologyValueNode {\n\t\tfor i := range endpointSlice.Endpoints {\n\t\t\tif endpointSlice.Endpoints[i].Topology[v1.LabelHostname] == fh.nodeName {\n\t\t\t\tnewEps = append(newEps, endpointSlice.Endpoints[i])\n\t\t\t}\n\t\t}\n\t\tendpointSlice.Endpoints = newEps\n\t} else if serviceTopologyType == AnnotationServiceTopologyValueNodePool || serviceTopologyType == AnnotationServiceTopologyValueZone {\n\t\t// if type of service Topology is openyurt.io/nodepool\n\t\t// filter the endpoint just on the node which is in the same nodepool with current node\n\t\tcurrentNode, err := fh.nodeGetter()\n\t\tif err != nil {\n\t\t\tklog.Infof(\"skip reassemble endpointSlice, failed to get current node %s, err: %v\", fh.nodeName, err)\n\t\t\treturn endpointSlice\n\t\t}\n\t\tif nodePoolName, ok := currentNode.Labels[nodepoolv1alpha1.LabelCurrentNodePool]; ok {\n\t\t\tnodePool, err := fh.nodePoolLister.Get(nodePoolName)\n\t\t\tif err != nil {\n\t\t\t\tklog.Infof(\"skip reassemble endpointSlice, failed to get nodepool %s, err: %v\", nodePoolName, err)\n\t\t\t\treturn endpointSlice\n\t\t\t}\n\t\t\tfor i := range endpointSlice.Endpoints {\n\t\t\t\tif inSameNodePool(endpointSlice.Endpoints[i].Topology[v1.LabelHostname], nodePool.Status.Nodes) {\n\t\t\t\t\tnewEps = append(newEps, endpointSlice.Endpoints[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\tendpointSlice.Endpoints = newEps\n\t\t}\n\t}\n\treturn endpointSlice\n}", "func ParseEndpoint(\n\tscheme, host string,\n\tdoer goahttp.Doer,\n\tenc func(*http.Request) goahttp.Encoder,\n\tdec func(*http.Response) goahttp.Decoder,\n\trestore bool,\n) (goa.Endpoint, interface{}, error) {\n\tvar (\n\t\trecorderFlags = flag.NewFlagSet(\"recorder\", flag.ContinueOnError)\n\n\t\trecorderRecordDataFlags = flag.NewFlagSet(\"record-data\", flag.ExitOnError)\n\t\trecorderRecordDataBodyFlag = recorderRecordDataFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\trecorderListFlags = flag.NewFlagSet(\"list\", flag.ExitOnError)\n\t\trecorderListServiceFlag = recorderListFlags.String(\"service\", \"REQUIRED\", \"\")\n\t\trecorderListNameFlag = recorderListFlags.String(\"name\", \"REQUIRED\", \"\")\n\t)\n\trecorderFlags.Usage = recorderUsage\n\trecorderRecordDataFlags.Usage = recorderRecordDataUsage\n\trecorderListFlags.Usage = recorderListUsage\n\n\tif err := flag.CommandLine.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(os.Args) < flag.NFlag()+3 {\n\t\treturn nil, nil, fmt.Errorf(\"not enough arguments\")\n\t}\n\n\tvar (\n\t\tsvcn string\n\t\tsvcf *flag.FlagSet\n\t)\n\t{\n\t\tsvcn = os.Args[1+flag.NFlag()]\n\t\tswitch svcn {\n\t\tcase \"recorder\":\n\t\t\tsvcf = recorderFlags\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown service %q\", svcn)\n\t\t}\n\t}\n\tif err := svcf.Parse(os.Args[2+flag.NFlag():]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tepn string\n\t\tepf *flag.FlagSet\n\t)\n\t{\n\t\tepn = os.Args[2+flag.NFlag()+svcf.NFlag()]\n\t\tswitch svcn {\n\t\tcase \"recorder\":\n\t\t\tswitch epn {\n\t\t\tcase \"record-data\":\n\t\t\t\tepf = recorderRecordDataFlags\n\n\t\t\tcase \"list\":\n\t\t\t\tepf = recorderListFlags\n\n\t\t\t}\n\n\t\t}\n\t}\n\tif epf == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unknown %q endpoint %q\", svcn, epn)\n\t}\n\n\t// Parse endpoint flags if any\n\tif len(os.Args) > 2+flag.NFlag()+svcf.NFlag() {\n\t\tif err := epf.Parse(os.Args[3+flag.NFlag()+svcf.NFlag():]); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tdata interface{}\n\t\tendpoint goa.Endpoint\n\t\terr error\n\t)\n\t{\n\t\tswitch svcn {\n\t\tcase \"recorder\":\n\t\t\tc := recordersvcc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"record-data\":\n\t\t\t\tendpoint = c.RecordData()\n\t\t\t\tdata, err = recordersvcc.BuildRecordDataPayload(*recorderRecordDataBodyFlag)\n\t\t\tcase \"list\":\n\t\t\t\tendpoint = c.List()\n\t\t\t\tdata, err = recordersvcc.BuildListPayload(*recorderListServiceFlag, *recorderListNameFlag)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn endpoint, data, nil\n}", "func (handler *Handler) endpointUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {\n\tif !handler.authorizeEndpointManagement {\n\t\treturn &httperror.HandlerError{http.StatusServiceUnavailable, \"Endpoint management is disabled\", ErrEndpointManagementDisabled}\n\t}\n\n\tendpointID, err := request.RetrieveNumericRouteVariableValue(r, \"id\")\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid endpoint identifier route variable\", err}\n\t}\n\n\tvar payload endpointUpdatePayload\n\terr = request.DecodeAndValidateJSONPayload(r, &payload)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusBadRequest, \"Invalid request payload\", err}\n\t}\n\n\tendpoint, err := handler.EndpointService.Endpoint(portainer.EndpointID(endpointID))\n\tif err == portainer.ErrObjectNotFound {\n\t\treturn &httperror.HandlerError{http.StatusNotFound, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t} else if err != nil {\n\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to find an endpoint with the specified identifier inside the database\", err}\n\t}\n\n\tif payload.Name != nil {\n\t\tendpoint.Name = *payload.Name\n\t}\n\n\tif payload.URL != nil {\n\t\tendpoint.URL = *payload.URL\n\t}\n\n\tif payload.PublicURL != nil {\n\t\tendpoint.PublicURL = *payload.PublicURL\n\t}\n\n\tif payload.GroupID != nil {\n\t\tendpoint.GroupID = portainer.EndpointGroupID(*payload.GroupID)\n\t}\n\n\tif payload.Tags != nil {\n\t\tendpoint.Tags = payload.Tags\n\t}\n\n\tif payload.Status != nil {\n\t\tswitch *payload.Status {\n\t\tcase 1:\n\t\t\tendpoint.Status = portainer.EndpointStatusUp\n\t\t\tbreak\n\t\tcase 2:\n\t\t\tendpoint.Status = portainer.EndpointStatusDown\n\t\t\tbreak\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif endpoint.Type == portainer.AzureEnvironment {\n\t\tcredentials := endpoint.AzureCredentials\n\t\tif payload.AzureApplicationID != nil {\n\t\t\tcredentials.ApplicationID = *payload.AzureApplicationID\n\t\t}\n\t\tif payload.AzureTenantID != nil {\n\t\t\tcredentials.TenantID = *payload.AzureTenantID\n\t\t}\n\t\tif payload.AzureAuthenticationKey != nil {\n\t\t\tcredentials.AuthenticationKey = *payload.AzureAuthenticationKey\n\t\t}\n\n\t\thttpClient := client.NewHTTPClient()\n\t\t_, authErr := httpClient.ExecuteAzureAuthenticationRequest(&credentials)\n\t\tif authErr != nil {\n\t\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to authenticate against Azure\", authErr}\n\t\t}\n\t\tendpoint.AzureCredentials = credentials\n\t}\n\n\tif payload.TLS != nil {\n\t\tfolder := strconv.Itoa(endpointID)\n\n\t\tif *payload.TLS {\n\t\t\tendpoint.TLSConfig.TLS = true\n\t\t\tif payload.TLSSkipVerify != nil {\n\t\t\t\tendpoint.TLSConfig.TLSSkipVerify = *payload.TLSSkipVerify\n\n\t\t\t\tif !*payload.TLSSkipVerify {\n\t\t\t\t\tcaCertPath, _ := handler.FileService.GetPathForTLSFile(folder, portainer.TLSFileCA)\n\t\t\t\t\tendpoint.TLSConfig.TLSCACertPath = caCertPath\n\t\t\t\t} else {\n\t\t\t\t\tendpoint.TLSConfig.TLSCACertPath = \"\"\n\t\t\t\t\thandler.FileService.DeleteTLSFile(folder, portainer.TLSFileCA)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif payload.TLSSkipClientVerify != nil {\n\t\t\t\tif !*payload.TLSSkipClientVerify {\n\t\t\t\t\tcertPath, _ := handler.FileService.GetPathForTLSFile(folder, portainer.TLSFileCert)\n\t\t\t\t\tendpoint.TLSConfig.TLSCertPath = certPath\n\t\t\t\t\tkeyPath, _ := handler.FileService.GetPathForTLSFile(folder, portainer.TLSFileKey)\n\t\t\t\t\tendpoint.TLSConfig.TLSKeyPath = keyPath\n\t\t\t\t} else {\n\t\t\t\t\tendpoint.TLSConfig.TLSCertPath = \"\"\n\t\t\t\t\thandler.FileService.DeleteTLSFile(folder, portainer.TLSFileCert)\n\t\t\t\t\tendpoint.TLSConfig.TLSKeyPath = \"\"\n\t\t\t\t\thandler.FileService.DeleteTLSFile(folder, portainer.TLSFileKey)\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tendpoint.TLSConfig.TLS = false\n\t\t\tendpoint.TLSConfig.TLSSkipVerify = false\n\t\t\tendpoint.TLSConfig.TLSCACertPath = \"\"\n\t\t\tendpoint.TLSConfig.TLSCertPath = \"\"\n\t\t\tendpoint.TLSConfig.TLSKeyPath = \"\"\n\t\t\terr = handler.FileService.DeleteTLSFiles(folder)\n\t\t\tif err != nil {\n\t\t\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to remove TLS files from disk\", err}\n\t\t\t}\n\t\t}\n\t}\n\n\tif payload.URL != nil || payload.TLS != nil || endpoint.Type == portainer.AzureEnvironment {\n\t\t_, err = handler.ProxyManager.CreateAndRegisterProxy(endpoint)\n\t\tif err != nil {\n\t\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to register HTTP proxy for the endpoint\", err}\n\t\t}\n\t}\n\n\terr = handler.EndpointService.UpdateEndpoint(endpoint.ID, endpoint)\n\tif err != nil {\n\t\treturn &httperror.HandlerError{http.StatusInternalServerError, \"Unable to persist endpoint changes inside the database\", err}\n\t}\n\n\treturn response.JSON(w, endpoint)\n}", "func (x *XVerify) SetEndpoint(e string) {\n\tendpoint = e\n}", "func adjustScheme(scheme string) (string, bool) {\n\tswitch scheme {\n\tcase \"ksi\", \"ksi+http\":\n\t\treturn \"http\", true\n\tcase \"ksi+https\":\n\t\treturn \"https\", true\n\tcase \"ksi+tcp\":\n\t\treturn \"tcp\", true\n\t}\n\treturn scheme, false\n}", "func (plugin) WrapEndpoint(edp muxrpc.Endpoint) interface{} {\n\treturn endpoint{edp}\n}", "func (fw *IPtables) SetEndpoint(netif FirewallEndpoint) error {\n\terr := fw.makeRules(netif)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"In Firewall.Init() error %s\", err)\n\t}\n\n\tfw.initialized = true\n\treturn err\n}", "func ParseEndpoint(\n\tscheme, host string,\n\tdoer goahttp.Doer,\n\tenc func(*http.Request) goahttp.Encoder,\n\tdec func(*http.Response) goahttp.Decoder,\n\trestore bool,\n) (goa.Endpoint, interface{}, error) {\n\tvar (\n\t\torganizationFlags = flag.NewFlagSet(\"organization\", flag.ContinueOnError)\n\n\t\torganizationListFlags = flag.NewFlagSet(\"list\", flag.ExitOnError)\n\n\t\torganizationShowFlags = flag.NewFlagSet(\"show\", flag.ExitOnError)\n\t\torganizationShowIDFlag = organizationShowFlags.String(\"id\", \"REQUIRED\", \"ID of the Organization to show\")\n\t\torganizationShowViewFlag = organizationShowFlags.String(\"view\", \"\", \"\")\n\n\t\torganizationAddFlags = flag.NewFlagSet(\"add\", flag.ExitOnError)\n\t\torganizationAddBodyFlag = organizationAddFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\torganizationRemoveFlags = flag.NewFlagSet(\"remove\", flag.ExitOnError)\n\t\torganizationRemoveIDFlag = organizationRemoveFlags.String(\"id\", \"REQUIRED\", \"ID of Organization to remove\")\n\n\t\torganizationUpdateFlags = flag.NewFlagSet(\"update\", flag.ExitOnError)\n\t\torganizationUpdateBodyFlag = organizationUpdateFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\tstepFlags = flag.NewFlagSet(\"step\", flag.ContinueOnError)\n\n\t\tstepListFlags = flag.NewFlagSet(\"list\", flag.ExitOnError)\n\t\tstepListIDFlag = stepListFlags.String(\"id\", \"REQUIRED\", \"ID of Walkthrough to search for steps \")\n\n\t\tstepAddFlags = flag.NewFlagSet(\"add\", flag.ExitOnError)\n\t\tstepAddBodyFlag = stepAddFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\tstepRemoveFlags = flag.NewFlagSet(\"remove\", flag.ExitOnError)\n\t\tstepRemoveBodyFlag = stepRemoveFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\tstepUpdateFlags = flag.NewFlagSet(\"update\", flag.ExitOnError)\n\t\tstepUpdateBodyFlag = stepUpdateFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\twalkthroughFlags = flag.NewFlagSet(\"walkthrough\", flag.ContinueOnError)\n\n\t\twalkthroughListFlags = flag.NewFlagSet(\"list\", flag.ExitOnError)\n\t\twalkthroughListIDFlag = walkthroughListFlags.String(\"id\", \"REQUIRED\", \"ID of Organization to search for \")\n\n\t\twalkthroughShowFlags = flag.NewFlagSet(\"show\", flag.ExitOnError)\n\t\twalkthroughShowIDFlag = walkthroughShowFlags.String(\"id\", \"REQUIRED\", \"ID of the Walkthrough to show\")\n\t\twalkthroughShowViewFlag = walkthroughShowFlags.String(\"view\", \"\", \"\")\n\n\t\twalkthroughAddFlags = flag.NewFlagSet(\"add\", flag.ExitOnError)\n\t\twalkthroughAddBodyFlag = walkthroughAddFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\twalkthroughRemoveFlags = flag.NewFlagSet(\"remove\", flag.ExitOnError)\n\t\twalkthroughRemoveIDFlag = walkthroughRemoveFlags.String(\"id\", \"REQUIRED\", \"ID of Walkthrough to remove\")\n\n\t\twalkthroughUpdateFlags = flag.NewFlagSet(\"update\", flag.ExitOnError)\n\t\twalkthroughUpdateBodyFlag = walkthroughUpdateFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\twalkthroughRenameFlags = flag.NewFlagSet(\"rename\", flag.ExitOnError)\n\t\twalkthroughRenameBodyFlag = walkthroughRenameFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\twalkthroughPublishFlags = flag.NewFlagSet(\"publish\", flag.ExitOnError)\n\t\twalkthroughPublishIDFlag = walkthroughPublishFlags.String(\"id\", \"REQUIRED\", \"ID of Walkthrough to be published\")\n\t)\n\torganizationFlags.Usage = organizationUsage\n\torganizationListFlags.Usage = organizationListUsage\n\torganizationShowFlags.Usage = organizationShowUsage\n\torganizationAddFlags.Usage = organizationAddUsage\n\torganizationRemoveFlags.Usage = organizationRemoveUsage\n\torganizationUpdateFlags.Usage = organizationUpdateUsage\n\n\tstepFlags.Usage = stepUsage\n\tstepListFlags.Usage = stepListUsage\n\tstepAddFlags.Usage = stepAddUsage\n\tstepRemoveFlags.Usage = stepRemoveUsage\n\tstepUpdateFlags.Usage = stepUpdateUsage\n\n\twalkthroughFlags.Usage = walkthroughUsage\n\twalkthroughListFlags.Usage = walkthroughListUsage\n\twalkthroughShowFlags.Usage = walkthroughShowUsage\n\twalkthroughAddFlags.Usage = walkthroughAddUsage\n\twalkthroughRemoveFlags.Usage = walkthroughRemoveUsage\n\twalkthroughUpdateFlags.Usage = walkthroughUpdateUsage\n\twalkthroughRenameFlags.Usage = walkthroughRenameUsage\n\twalkthroughPublishFlags.Usage = walkthroughPublishUsage\n\n\tif err := flag.CommandLine.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif flag.NArg() < 2 { // two non flag args are required: SERVICE and ENDPOINT (aka COMMAND)\n\t\treturn nil, nil, fmt.Errorf(\"not enough arguments\")\n\t}\n\n\tvar (\n\t\tsvcn string\n\t\tsvcf *flag.FlagSet\n\t)\n\t{\n\t\tsvcn = flag.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"organization\":\n\t\t\tsvcf = organizationFlags\n\t\tcase \"step\":\n\t\t\tsvcf = stepFlags\n\t\tcase \"walkthrough\":\n\t\t\tsvcf = walkthroughFlags\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown service %q\", svcn)\n\t\t}\n\t}\n\tif err := svcf.Parse(flag.Args()[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tepn string\n\t\tepf *flag.FlagSet\n\t)\n\t{\n\t\tepn = svcf.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"organization\":\n\t\t\tswitch epn {\n\t\t\tcase \"list\":\n\t\t\t\tepf = organizationListFlags\n\n\t\t\tcase \"show\":\n\t\t\t\tepf = organizationShowFlags\n\n\t\t\tcase \"add\":\n\t\t\t\tepf = organizationAddFlags\n\n\t\t\tcase \"remove\":\n\t\t\t\tepf = organizationRemoveFlags\n\n\t\t\tcase \"update\":\n\t\t\t\tepf = organizationUpdateFlags\n\n\t\t\t}\n\n\t\tcase \"step\":\n\t\t\tswitch epn {\n\t\t\tcase \"list\":\n\t\t\t\tepf = stepListFlags\n\n\t\t\tcase \"add\":\n\t\t\t\tepf = stepAddFlags\n\n\t\t\tcase \"remove\":\n\t\t\t\tepf = stepRemoveFlags\n\n\t\t\tcase \"update\":\n\t\t\t\tepf = stepUpdateFlags\n\n\t\t\t}\n\n\t\tcase \"walkthrough\":\n\t\t\tswitch epn {\n\t\t\tcase \"list\":\n\t\t\t\tepf = walkthroughListFlags\n\n\t\t\tcase \"show\":\n\t\t\t\tepf = walkthroughShowFlags\n\n\t\t\tcase \"add\":\n\t\t\t\tepf = walkthroughAddFlags\n\n\t\t\tcase \"remove\":\n\t\t\t\tepf = walkthroughRemoveFlags\n\n\t\t\tcase \"update\":\n\t\t\t\tepf = walkthroughUpdateFlags\n\n\t\t\tcase \"rename\":\n\t\t\t\tepf = walkthroughRenameFlags\n\n\t\t\tcase \"publish\":\n\t\t\t\tepf = walkthroughPublishFlags\n\n\t\t\t}\n\n\t\t}\n\t}\n\tif epf == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unknown %q endpoint %q\", svcn, epn)\n\t}\n\n\t// Parse endpoint flags if any\n\tif svcf.NArg() > 1 {\n\t\tif err := epf.Parse(svcf.Args()[1:]); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tdata interface{}\n\t\tendpoint goa.Endpoint\n\t\terr error\n\t)\n\t{\n\t\tswitch svcn {\n\t\tcase \"organization\":\n\t\t\tc := organizationc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"list\":\n\t\t\t\tendpoint = c.List()\n\t\t\t\tdata = nil\n\t\t\tcase \"show\":\n\t\t\t\tendpoint = c.Show()\n\t\t\t\tdata, err = organizationc.BuildShowPayload(*organizationShowIDFlag, *organizationShowViewFlag)\n\t\t\tcase \"add\":\n\t\t\t\tendpoint = c.Add()\n\t\t\t\tdata, err = organizationc.BuildAddPayload(*organizationAddBodyFlag)\n\t\t\tcase \"remove\":\n\t\t\t\tendpoint = c.Remove()\n\t\t\t\tdata, err = organizationc.BuildRemovePayload(*organizationRemoveIDFlag)\n\t\t\tcase \"update\":\n\t\t\t\tendpoint = c.Update()\n\t\t\t\tdata, err = organizationc.BuildUpdatePayload(*organizationUpdateBodyFlag)\n\t\t\t}\n\t\tcase \"step\":\n\t\t\tc := stepc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"list\":\n\t\t\t\tendpoint = c.List()\n\t\t\t\tdata, err = stepc.BuildListPayload(*stepListIDFlag)\n\t\t\tcase \"add\":\n\t\t\t\tendpoint = c.Add()\n\t\t\t\tdata, err = stepc.BuildAddPayload(*stepAddBodyFlag)\n\t\t\tcase \"remove\":\n\t\t\t\tendpoint = c.Remove()\n\t\t\t\tdata, err = stepc.BuildRemovePayload(*stepRemoveBodyFlag)\n\t\t\tcase \"update\":\n\t\t\t\tendpoint = c.Update()\n\t\t\t\tdata, err = stepc.BuildUpdatePayload(*stepUpdateBodyFlag)\n\t\t\t}\n\t\tcase \"walkthrough\":\n\t\t\tc := walkthroughc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"list\":\n\t\t\t\tendpoint = c.List()\n\t\t\t\tdata, err = walkthroughc.BuildListPayload(*walkthroughListIDFlag)\n\t\t\tcase \"show\":\n\t\t\t\tendpoint = c.Show()\n\t\t\t\tdata, err = walkthroughc.BuildShowPayload(*walkthroughShowIDFlag, *walkthroughShowViewFlag)\n\t\t\tcase \"add\":\n\t\t\t\tendpoint = c.Add()\n\t\t\t\tdata, err = walkthroughc.BuildAddPayload(*walkthroughAddBodyFlag)\n\t\t\tcase \"remove\":\n\t\t\t\tendpoint = c.Remove()\n\t\t\t\tdata, err = walkthroughc.BuildRemovePayload(*walkthroughRemoveIDFlag)\n\t\t\tcase \"update\":\n\t\t\t\tendpoint = c.Update()\n\t\t\t\tdata, err = walkthroughc.BuildUpdatePayload(*walkthroughUpdateBodyFlag)\n\t\t\tcase \"rename\":\n\t\t\t\tendpoint = c.Rename()\n\t\t\t\tdata, err = walkthroughc.BuildRenamePayload(*walkthroughRenameBodyFlag)\n\t\t\tcase \"publish\":\n\t\t\t\tendpoint = c.Publish()\n\t\t\t\tdata, err = walkthroughc.BuildPublishPayload(*walkthroughPublishIDFlag)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn endpoint, data, nil\n}", "func (p *Parser) validateEndpoint(endpoint string) (string, error) {\n\t// We need the endpoint to begin with a forward slash '/'\n\t// Note: Not sure if we want to add a leading slash if the slash is missing\n\tif len(endpoint) == 0 {\n\t\treturn DefaultEndpoint, nil\n\t}\n\n\tif string(endpoint[0]) != \"/\" {\n\t\treturn endpoint, fmt.Errorf(\"provided endpoint must begin witha '/'. Found: %v.\", endpoint[0])\n\t}\n\n\treturn endpoint, nil\n}", "func buildLoopbackEndpoint(err error) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\treturn request, err\n\t}\n}", "func deleteHCNEndpoint(ep *hcn.HostComputeEndpoint, netns string) (string, error) {\n\tdefer func() { _ = recover() }()\n\tif ep == nil {\n\t\treturn \"\", nil\n\t}\n\n\t// remove endpoint from namespace\n\tif netns == \"\" {\n\t\tnetns = ep.HostComputeNamespace\n\t}\n\t_ = hcn.RemoveNamespaceEndpoint(netns, ep.Id)\n\n\t// delete endpoint\n\tif err := ep.Delete(); err != nil {\n\t\tif !hcn.IsNotFoundError(err) {\n\t\t\treturn ep.HostComputeNetwork, err\n\t\t}\n\t}\n\treturn ep.HostComputeNetwork, nil\n}", "func removeServiceNameFromJWTURI(uri string) (string, error) {\n\tparsed, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tparsed.Path = \"/\"\n\treturn parsed.String(), nil\n}", "func Fix(cfg *rest.Config) *rest.Config {\n\tif cfg == nil || !fixAKS {\n\t\treturn cfg\n\t}\n\n\t// ref: https://github.com/kubernetes/client-go/blob/kubernetes-1.11.3/rest/config.go#L309\n\thost, port := os.Getenv(\"KUBERNETES_SERVICE_HOST\"), os.Getenv(\"KUBERNETES_SERVICE_PORT\")\n\tif len(host) > 0 &&\n\t\tlen(port) > 0 &&\n\t\tin(cfg.Host, \"https://\"+net.JoinHostPort(host, port), \"https://kubernetes.default.svc\", \"https://kubernetes.default.svc:443\") {\n\t\t// uses service ip or cluster dns\n\n\t\tif cert, err := meta.APIServerCertificate(cfg); err == nil {\n\t\t\t// kube-apiserver cert found\n\n\t\t\tif host, err := meta.TestAKS(cert); err == nil {\n\t\t\t\t// AKS cluster\n\n\t\t\t\th := \"https://\" + host\n\t\t\t\tglog.Infof(\"resetting Kubeconfig host to %s from %s for AKS to workaround https://github.com/Azure/AKS/issues/522\", h, cfg.Host)\n\t\t\t\tcfg.Host = h\n\t\t\t}\n\t\t}\n\t}\n\treturn cfg\n}", "func (nb *NetBuilder) DeleteEndpoint(nw *Network, ep *Endpoint) error {\n\t// Generate network name here as endpoint name is dependent upon network name.\n\tnw.Name = nb.generateHNSNetworkName(nw)\n\t// Query the namespace identifier.\n\tnsType, namespaceIdentifier := nb.getNamespaceIdentifier(ep)\n\n\t// Find the HNS endpoint ID.\n\tendpointName := nb.generateHNSEndpointName(nw.Name, namespaceIdentifier)\n\thnsEndpoint, err := hcsshim.GetHNSEndpointByName(endpointName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Detach the HNS endpoint from the container's network namespace.\n\tlog.Infof(\"Detaching HNS endpoint %s from container %s netns.\", hnsEndpoint.Id, ep.ContainerID)\n\tif nsType == hcsNamespace {\n\t\t// Detach the HNS endpoint from the namespace, if we can.\n\t\t// HCN Namespace and HNS Endpoint have a 1-1 relationship, therefore,\n\t\t// even if detachment of endpoint from namespace fails, we can still proceed to delete it.\n\t\terr = hcn.RemoveNamespaceEndpoint(namespaceIdentifier, hnsEndpoint.Id)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to detach endpoint, ignoring: %v\", err)\n\t\t}\n\t} else {\n\t\terr = hcsshim.HotDetachEndpoint(ep.ContainerID, hnsEndpoint.Id)\n\t\tif err != nil && err != hcsshim.ErrComputeSystemDoesNotExist {\n\t\t\treturn err\n\t\t}\n\n\t\t// The rest of the delete logic applies to infrastructure container only.\n\t\tif nsType == nonInfraContainerNS {\n\t\t\t// For non-infra containers, the network must not be deleted.\n\t\t\tnw.UseExisting = true\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// Delete the HNS endpoint.\n\tlog.Infof(\"Deleting HNS endpoint name: %s ID: %s\", endpointName, hnsEndpoint.Id)\n\t_, err = hnsEndpoint.Delete()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to delete HNS endpoint: %v.\", err)\n\t}\n\n\treturn err\n}", "func (nng *MangosTransport) Scheme() string {\n\treturn \"ws\"\n}", "func (c *HttpConnector) addEndpoint(endpoint *cfg.Endpoint) error {\n\tvar ok bool\n\tif _, ok = c.routes[endpoint.Method]; !ok {\n\t\tc.routes[endpoint.Method] = map[string]*route{}\n\t}\n\n\tif _, ok = c.routes[endpoint.Method][endpoint.Url]; ok {\n\t\treturn fmt.Errorf(\"duplicate path %s for method %s\", endpoint.Url, endpoint.Method)\n\t}\n\n\troute := &route{name: endpoint.Name}\n\n\troute.params = getParamsFromPath(endpoint.Url)\n\tif len(route.params) > 0 {\n\t\troute.tester = getDynamicRouteTester(endpoint.Url, route.params)\n\t}\n\n\tc.routes[endpoint.Method][endpoint.Url] = route\n\treturn nil\n}", "func (c *Client) SetEndpoint(endpoint string) {\n\tif endpoint == \"\" {\n\t\tc.endpoint = DefaultEndpoint\n\t\treturn\n\t}\n\tc.endpoint = endpoint\n}", "func (c *ServerConfig) ParseEndpoint() error {\n\tvar op errors.Op = \"cli.ServerConfig.ParseEndpoint\"\n\tnurl, err := url.ParseRequestURI(c.Endpoint)\n\tif err != nil {\n\t\treturn errors.E(op, err)\n\t}\n\tc.ParsedEndpoint = nurl\n\treturn nil\n}", "func (s *EndpointServer) applyEndpoint(ctx context.Context, c *vertexai.Client, request *vertexaipb.ApplyVertexaiEndpointRequest) (*vertexaipb.VertexaiEndpoint, error) {\n\tp := ProtoToEndpoint(request.GetResource())\n\tres, err := c.ApplyEndpoint(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := EndpointToProto(res)\n\treturn r, nil\n}", "func flattenServiceEndpointSonarQube(d *schema.ResourceData, serviceEndpoint *serviceendpoint.ServiceEndpoint, projectID *uuid.UUID) {\n\tdoBaseFlattening(d, serviceEndpoint, projectID)\n\n\td.Set(\"url\", *serviceEndpoint.Url)\n}", "func setDefaultScheme(scheme string) (string) {\n\tif scheme != \"\" {\n\t\treturn scheme\n\t}\n\n\treturn \"http\"\n}", "func ParseEndpoint(\n\tscheme, host string,\n\tdoer goahttp.Doer,\n\tenc func(*http.Request) goahttp.Encoder,\n\tdec func(*http.Response) goahttp.Decoder,\n\trestore bool,\n) (goa.Endpoint, interface{}, error) {\n\tvar (\n\t\twantGoFlags = flag.NewFlagSet(\"want-go\", flag.ContinueOnError)\n\n\t\twantGoGetSimpleCardListFlags = flag.NewFlagSet(\"get-simple-card-list\", flag.ExitOnError)\n\n\t\twantGoGetCardInfoFlags = flag.NewFlagSet(\"get-card-info\", flag.ExitOnError)\n\t\twantGoGetCardInfoCardIDFlag = wantGoGetCardInfoFlags.String(\"card-id\", \"REQUIRED\", \"\")\n\n\t\twantGoPostCardInfoFlags = flag.NewFlagSet(\"post-card-info\", flag.ExitOnError)\n\t\twantGoPostCardInfoBodyFlag = wantGoPostCardInfoFlags.String(\"body\", \"REQUIRED\", \"\")\n\n\t\twantGoPutCardInfoFlags = flag.NewFlagSet(\"put-card-info\", flag.ExitOnError)\n\t\twantGoPutCardInfoBodyFlag = wantGoPutCardInfoFlags.String(\"body\", \"REQUIRED\", \"\")\n\t\twantGoPutCardInfoCardIDFlag = wantGoPutCardInfoFlags.String(\"card-id\", \"REQUIRED\", \"\")\n\n\t\twantGoDeleteCardInfoFlags = flag.NewFlagSet(\"delete-card-info\", flag.ExitOnError)\n\t\twantGoDeleteCardInfoCardIDFlag = wantGoDeleteCardInfoFlags.String(\"card-id\", \"REQUIRED\", \"card id\")\n\t)\n\twantGoFlags.Usage = wantGoUsage\n\twantGoGetSimpleCardListFlags.Usage = wantGoGetSimpleCardListUsage\n\twantGoGetCardInfoFlags.Usage = wantGoGetCardInfoUsage\n\twantGoPostCardInfoFlags.Usage = wantGoPostCardInfoUsage\n\twantGoPutCardInfoFlags.Usage = wantGoPutCardInfoUsage\n\twantGoDeleteCardInfoFlags.Usage = wantGoDeleteCardInfoUsage\n\n\tif err := flag.CommandLine.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif flag.NArg() < 2 { // two non flag args are required: SERVICE and ENDPOINT (aka COMMAND)\n\t\treturn nil, nil, fmt.Errorf(\"not enough arguments\")\n\t}\n\n\tvar (\n\t\tsvcn string\n\t\tsvcf *flag.FlagSet\n\t)\n\t{\n\t\tsvcn = flag.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"want-go\":\n\t\t\tsvcf = wantGoFlags\n\t\tdefault:\n\t\t\treturn nil, nil, fmt.Errorf(\"unknown service %q\", svcn)\n\t\t}\n\t}\n\tif err := svcf.Parse(flag.Args()[1:]); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tepn string\n\t\tepf *flag.FlagSet\n\t)\n\t{\n\t\tepn = svcf.Arg(0)\n\t\tswitch svcn {\n\t\tcase \"want-go\":\n\t\t\tswitch epn {\n\t\t\tcase \"get-simple-card-list\":\n\t\t\t\tepf = wantGoGetSimpleCardListFlags\n\n\t\t\tcase \"get-card-info\":\n\t\t\t\tepf = wantGoGetCardInfoFlags\n\n\t\t\tcase \"post-card-info\":\n\t\t\t\tepf = wantGoPostCardInfoFlags\n\n\t\t\tcase \"put-card-info\":\n\t\t\t\tepf = wantGoPutCardInfoFlags\n\n\t\t\tcase \"delete-card-info\":\n\t\t\t\tepf = wantGoDeleteCardInfoFlags\n\n\t\t\t}\n\n\t\t}\n\t}\n\tif epf == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unknown %q endpoint %q\", svcn, epn)\n\t}\n\n\t// Parse endpoint flags if any\n\tif svcf.NArg() > 1 {\n\t\tif err := epf.Parse(svcf.Args()[1:]); err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\n\tvar (\n\t\tdata interface{}\n\t\tendpoint goa.Endpoint\n\t\terr error\n\t)\n\t{\n\t\tswitch svcn {\n\t\tcase \"want-go\":\n\t\t\tc := wantgoc.NewClient(scheme, host, doer, enc, dec, restore)\n\t\t\tswitch epn {\n\t\t\tcase \"get-simple-card-list\":\n\t\t\t\tendpoint = c.GetSimpleCardList()\n\t\t\t\tdata = nil\n\t\t\tcase \"get-card-info\":\n\t\t\t\tendpoint = c.GetCardInfo()\n\t\t\t\tdata, err = wantgoc.BuildGetCardInfoPayload(*wantGoGetCardInfoCardIDFlag)\n\t\t\tcase \"post-card-info\":\n\t\t\t\tendpoint = c.PostCardInfo()\n\t\t\t\tdata, err = wantgoc.BuildPostCardInfoPayload(*wantGoPostCardInfoBodyFlag)\n\t\t\tcase \"put-card-info\":\n\t\t\t\tendpoint = c.PutCardInfo()\n\t\t\t\tdata, err = wantgoc.BuildPutCardInfoPayload(*wantGoPutCardInfoBodyFlag, *wantGoPutCardInfoCardIDFlag)\n\t\t\tcase \"delete-card-info\":\n\t\t\t\tendpoint = c.DeleteCardInfo()\n\t\t\t\tdata, err = wantgoc.BuildDeleteCardInfoPayload(*wantGoDeleteCardInfoCardIDFlag)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn endpoint, data, nil\n}", "func parseEndpoint() (*url.URL, error) {\n\tepEnv := ParseEnvVar(common.IMPORTER_ENDPOINT, false)\n\tif epEnv == \"\" {\n\t\treturn nil, fmt.Errorf(\"parseEndpoint: endpoint %q is missing or blank\\n\", common.IMPORTER_ENDPOINT)\n\t}\n\tep, err := url.Parse(epEnv)\n \tif err != nil {\n \treturn nil, fmt.Errorf(\"parseEndpoint: %v\\n\", err)\n\t}\n\treturn ep, nil\n}", "func (u URIExpr) Scheme() string {\n\tustr := string(u)\n\t// Did not use url package to find scheme because the url may\n\t// contain params (i.e. http://{version}.example.com) which needs\n\t// substition for url.Parse to succeed. Also URIs in host must have\n\t// a scheme otherwise validations would have failed.\n\tswitch {\n\tcase strings.HasPrefix(ustr, \"https\"):\n\t\treturn \"https\"\n\tcase strings.HasPrefix(ustr, \"grpcs\"):\n\t\treturn \"grpcs\"\n\tcase strings.HasPrefix(ustr, \"grpc\"):\n\t\treturn \"grpc\"\n\tdefault:\n\t\t// No need to worry about other values because the URIExpr would have failed\n\t\t// validation.\n\t\treturn \"http\"\n\t}\n}", "func (u *UpYunForm) SetEndpoint(ed int) error {\n\tif ed >= Auto && ed <= Ctt {\n\t\tu.endpoint = fmt.Sprintf(\"v%d.api.upyun.com\", ed)\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Invalid endpoint, pick from Auto, Telecom, Cnc, Ctt\")\n}", "func (st *state) apiEndpoint(path, query string) (*url.URL, error) {\n\treturn &url.URL{\n\t\tScheme: st.serverScheme,\n\t\tHost: st.Addr(),\n\t\tPath: path,\n\t\tRawQuery: query,\n\t}, nil\n}", "func RemoveLocalEndpoint(dbConn ucdb.Db, containerID string) error {\n\tlog.Debug(\"\")\n\tattempts := 1\n\tremoveEndpointCmd := fmt.Sprintf(\"%s %s\", os.Getenv(\"REMOVE_ENDPOINT\"), containerID)\n\tfor attempts <= 10 {\n\t\tlog.Debug(\"Attempt %d for container %v...\", attempts, containerID)\n\t\tendpoint, err := dbConn.GetEndpoint(containerID)\n\t\tif err != nil || endpoint.Container == \"\" {\n\t\t\tlog.Debug(\"Could not find entry for %s\", containerID)\n\t\t\tconst delay = 1 * time.Second\n\t\t\ttime.Sleep(delay)\n\t\t\tattempts++\n\t\t\tcontinue\n\t\t}\n\t\tlog.Debug(\"Found endpoint: %+v\", endpoint)\n\t\tif endpoint.Node == os.Getenv(\"HOST_IP\") {\n\t\t\tremoveEndpointCmd += \" \" + endpoint.Interface\n\t\t}\n\t\tbreak\n\t}\n\tif _, err := execShCommand(removeEndpointCmd); err != nil {\n\t\tlog.Debug(\"Error: %+v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) endpoint(route string) string {\n\treturn baseEndpoint + route\n}", "func (ml *ManagedListener) SetEndpoint(ep *v1.Endpoints) {\n\tdefer ml.Monitor()()\n\tif InCluster() {\n\t\tif ml.Endpoints != nil && ep != nil {\n\t\t\tlhsPorts := EndpointIPs(ml.Endpoints)\n\t\t\tlhsIPs := EndpointSubsetPorts(ml.Endpoints)\n\t\t\trhsPorts := EndpointIPs(ep)\n\t\t\trhsIPs := EndpointSubsetPorts(ep)\n\t\t\tif !lhsPorts.Equal(rhsPorts) || !lhsIPs.Equal(rhsIPs) {\n\t\t\t\tml.EndpointsChanged = true\n\t\t\t\tml.Endpoints = ep\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *DefaultApiService) UpdateEndpoint(ctx _context.Context, id string) ApiUpdateEndpointRequest {\n\treturn ApiUpdateEndpointRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func RegisterFleaHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {\n\tconn, err := grpc.Dial(endpoint, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif cerr := conn.Close(); cerr != nil {\n\t\t\t\tgrpclog.Infof(\"Failed to close conn to %s: %v\", endpoint, cerr)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tgo func() {\n\t\t\t<-ctx.Done()\n\t\t\tif cerr := conn.Close(); cerr != nil {\n\t\t\t\tgrpclog.Infof(\"Failed to close conn to %s: %v\", endpoint, cerr)\n\t\t\t}\n\t\t}()\n\t}()\n\n\treturn RegisterFleaHandler(ctx, mux, conn)\n}", "func makeEndpoint(hostport, serviceName string) *zipkincore.Endpoint {\n\thost, port, err := net.SplitHostPort(hostport)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tportInt, err := strconv.ParseInt(port, 10, 16)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\taddrs, err := net.LookupIP(host)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvar addr4, addr16 net.IP\n\tfor i := range addrs {\n\t\tif addr := addrs[i].To4(); addr == nil {\n\t\t\tif addr16 == nil {\n\t\t\t\taddr16 = addrs[i].To16() // IPv6 - 16 bytes\n\t\t\t}\n\t\t} else {\n\t\t\tif addr4 == nil {\n\t\t\t\taddr4 = addr // IPv4 - 4 bytes\n\t\t\t}\n\t\t}\n\t\tif addr16 != nil && addr4 != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif addr4 == nil {\n\t\tif addr16 == nil {\n\t\t\treturn nil\n\t\t}\n\t\t// we have an IPv6 but no IPv4, code IPv4 as 0 (none found)\n\t\taddr4 = []byte(\"\\x00\\x00\\x00\\x00\")\n\t}\n\n\tendpoint := zipkincore.NewEndpoint()\n\tendpoint.Ipv4 = (int32)(binary.BigEndian.Uint32(addr4))\n\tendpoint.Ipv6 = []byte(addr16)\n\tendpoint.Port = int16(portInt)\n\tendpoint.ServiceName = serviceName\n\n\treturn endpoint\n}", "func ParseEndpoint(endpoint string) (*url.URL, error) {\n\tendpoint = FormatEndpoint(endpoint)\n\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn u, nil\n}", "func (o *PaymentInitiationPaymentGetResponse) UnsetScheme() {\n\to.Scheme.Unset()\n}", "func (vl *VlanBridge) RemoveEndpoint(endpoint *OfnetEndpoint) error {\n\tlog.Infof(\"Received DELETE endpoint: %+v\", endpoint)\n\n\t// Remove the endpoint from policy tables\n\terr := vl.policyAgent.DelEndpoint(endpoint)\n\tif err != nil {\n\t\tlog.Errorf(\"Error deleting endpoint to policy agent{%+v}. Err: %v\", endpoint, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ParseEndpoint(endpoint string) (string, string, string, error) {\n\turl, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tsplits := strings.Split(url.Host, \":\")\n\tif len(splits) != 2 {\n\t\treturn \"\", \"\", \"\", fmt.Errorf(\"invalid host: %s\", url.Host)\n\t}\n\treturn url.Scheme, splits[0], splits[1], nil\n}", "func (m method) JesterEndpoint() string {\n\te := strings.Replace(m.Endpoint, \"{\", \"@\", -1)\n\treturn strings.Replace(e, \"}\", \"\", -1)\n}", "func FormatEndpointMethod(n string) string {\n\tp := strings.Split(n, \"/\")\n\tm := \"\"\n\tfor _, s := range p {\n\t\tm = fmt.Sprintf(\"%s%s\", m, strings.Title(s))\n\t}\n\treturn m\n}", "func (api *API) addEndpoint(endpoint APIEndpoint) {\n\t// httpMethod check\n\tif endpoint.httpMethod != http.MethodGet &&\n\t\tendpoint.httpMethod != http.MethodPost &&\n\t\tendpoint.httpMethod != http.MethodPatch &&\n\t\tendpoint.httpMethod != http.MethodPut &&\n\t\tendpoint.httpMethod != http.MethodDelete {\n\t\tapi.logger.Fatal(1, \"Cannot call 'AddHandler' an invalid method \\\"%s\\\" for URL %s/%s/%s\",\n\t\t\tendpoint.httpMethod, api.root, endpoint.version, endpoint.url)\n\t}\n\n\t// endpoint handler check\n\tvar handler http.HandlerFunc\n\n\tif endpoint.publicHandler != nil {\n\t\t// Public handler: leverage ServeHTTP method\n\t\thandler = endpoint.publicHandler\n\t} else if endpoint.protectedHandler != nil {\n\t\t// Protected handler\n\t\thandler = DoIfAccess(endpoint.accessChecker, endpoint.protectedHandler).ServeHTTP\n\t} else {\n\t\t// Error: missing handler\n\t\tapi.logger.Fatal(1, \"[API] Endpoint %s:%s does not have any handler\", endpoint.httpMethod, endpoint.url)\n\t\treturn\n\t}\n\n\t// CORS config is the same for both public and protected\n\tcorsConfig := CorsConfig{\n\t\tHosts: api.corsHosts,\n\t\tHeaders: api.corsHeaders,\n\t\tMethods: endpoint.httpMethod,\n\t}\n\n\t// Apply CORS handers\n\tendpoint.handler = AddCorsHeaders(handler, corsConfig).ServeHTTP\n\n\t// Add new endpoints to the list\n\tapi.endpoints = append(api.endpoints, endpoint)\n}", "func TestEndpointCase48(t *testing.T) {\n\tvar params = EndpointParameters{\n\t\tRegion: ptr.String(\"us-east-1\"),\n\t\tUseFIPS: ptr.Bool(false),\n\t\tUseDualStack: ptr.Bool(false),\n\t\tStreamARN: ptr.String(\"arn\"),\n\t}\n\n\tresolver := NewDefaultEndpointResolverV2()\n\tresult, err := resolver.ResolveEndpoint(context.Background(), params)\n\t_, _ = result, err\n\n\tif err == nil {\n\t\tt.Fatalf(\"expect error, got none\")\n\t}\n\tif e, a := \"Invalid ARN: Failed to parse ARN.\", err.Error(); !strings.Contains(a, e) {\n\t\tt.Errorf(\"expect %v error in %v\", e, a)\n\t}\n}", "func DeepCopy__Endpoint(in interface{}, out interface{}, c *conversion.Cloner) error {\n\t{\n\t\tin := in.(*Endpoint)\n\t\tout := out.(*Endpoint)\n\t\t*out = *in\n\t\tif in.Target != nil {\n\t\t\tin, out := &in.Target, &out.Target\n\t\t\t*out = new(v1.ObjectReference)\n\t\t\t**out = **in\n\t\t}\n\t\treturn nil\n\t}\n}", "func (pushBots *PushBots) ApplyEndpointOverride(endpointOverride string) {\n\tpushBots.initializeEndpoints(endpointOverride)\n}", "func (s *HttpsNotificationConfiguration) SetEndpoint(v string) *HttpsNotificationConfiguration {\n\ts.Endpoint = &v\n\treturn s\n}", "func RemoveEndpoint(containerID string) error {\n\tlog.Debug(\"\")\n\tRemoveEndpointCmd := fmt.Sprintf(\"%s %s\", os.Getenv(\"REMOVE_ENDPOINT\"), containerID)\n\tif _, err := execShCommand(RemoveEndpointCmd); err != nil {\n\t\tlog.Debug(\"Error: %+v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func WithEndpoint(v string) (p Pair) {\n\treturn Pair{Key: \"endpoint\", Value: v}\n}", "func getURI(webhook *triggersv1.WebhookInterceptor, ns string) (*url.URL, error) {\n\t// TODO: This should work for any Addressable.\n\t// Use something like https://github.com/knative/eventing-contrib/blob/7c0fc5cfa8bd44da0767d9e7b250264ea6eb7d8d/pkg/controller/sinks/sinks.go#L32\n\tswitch {\n\tcase webhook.URL != nil:\n\t\treturn webhook.URL.URL(), nil\n\tcase webhook.ObjectRef.Kind == \"Service\" && webhook.ObjectRef.APIVersion == \"v1\":\n\t\t// TODO: Also assuming port 80 and http here. Use DNS/or the env vars?\n\t\tif webhook.ObjectRef.Namespace != \"\" {\n\t\t\tns = webhook.ObjectRef.Namespace\n\t\t}\n\t\treturn url.Parse(fmt.Sprintf(\"http://%s.%s.svc/\", webhook.ObjectRef.Name, ns))\n\tdefault:\n\t\treturn nil, errors.New(\"invalid objRef\")\n\t}\n}", "func roundTripAdapter(next http.RoundTripper) http.RoundTripper {\n\treturn roundTripFunc(func(req *http.Request) (*http.Response, error) {\n\t\tif req.URL == nil {\n\t\t\treturn nil, fmt.Errorf(\"unix transport: no request URL\")\n\t\t}\n\n\t\tif req.URL.Scheme != \"unix\" {\n\t\t\treturn nil, fmt.Errorf(\"unix transport: invalid scheme '%s'\", req.URL.Scheme)\n\t\t}\n\n\t\tvar socketPath string\n\t\tvar requestPath string\n\n\t\tfor _, suffix := range socketSuffixes {\n\t\t\tidx := strings.Index(req.URL.Path, suffix)\n\t\t\tif idx != -1 {\n\t\t\t\tsepIdx := idx + len(suffix)\n\t\t\t\tsocketPath = req.URL.Path[0:sepIdx]\n\t\t\t\trequestPath = req.URL.Path[sepIdx:len(req.URL.Path)]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif socketPath == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"unix transport: could not extract socket path: missing .sock/.socket file suffix\")\n\t\t}\n\n\t\tencodedHost := base64.RawURLEncoding.EncodeToString([]byte(socketPath))\n\n\t\treq = req.Clone(req.Context())\n\t\treq.URL.Scheme = \"http\" // Remove?\n\t\treq.URL.Host = encodedHost\n\t\treq.URL.Path = requestPath\n\n\t\treturn next.RoundTrip(req)\n\t})\n}", "func stripPort(hostportURL *url.URL) string {\n\tvar hostport string\n\tif hostportURL.Host != \"\" {\n\t\thostport = hostportURL.Host\n\t} else {\n\t\thostport = hostportURL.String()\n\t}\n\n\tcolon := strings.IndexByte(hostport, ':')\n\tif colon == -1 {\n\t\treturn hostport\n\t}\n\tif i := strings.IndexByte(hostport, ']'); i != -1 {\n\t\treturn strings.TrimPrefix(hostport[:i], \"[\")\n\t}\n\treturn hostport[:colon]\n}", "func (server *HTTPRouterServer) RemoveEndpoint(path string) error {\n\tdelete(server.endpointsMap, path)\n\treturn nil\n}", "func (p *fullEndpoint) delete(expectedOldValue *Endpoint) {\n\tatomic.CompareAndSwapPointer(&p.endpoint, unsafe.Pointer(expectedOldValue), nil)\n}", "func fromProtocolURI(uri string) (source.URI, error) {\n\tunescaped, err := url.PathUnescape(string(uri))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn source.URI(unescaped), nil\n}", "func (ec *ExtensionClient) DeleteEndpoint(extensionID, serviceID, URL string) error {\n\n\turl := url.QueryEscape(URL)\n\trequest, err := extensionc.BuildDeleteEndpointPayload(extensionID, serviceID, url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = ec.c.DeleteEndpoint()(context.Background(), request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *ServerConfig) ListenEndpoint() string {\n\t// if s.Port == \"80\" || s.Port == \"443\" {\n\t// \treturn s.Host\n\t// }\n\treturn s.Host + \":\" + s.Port\n}", "func MakePatchProfileEndpoint(s Service) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (interface{}, error) {\n\t\t// TODO: Create detailed ref spec\n\t\treq := request.(patchProfileRequest)\n\t\te := s.PatchProfile(ctx, req.ProfileID, req.Profile)\n\t\treturn patchProfileResponse{Err: e}, nil\n\t}\n}", "func Scheme(reg name.Registry) string {\n\tif strings.HasPrefix(reg.Name(), \"localhost:\") {\n\t\treturn \"http\"\n\t}\n\tif reLocal.MatchString(reg.Name()) {\n\t\treturn \"http\"\n\t}\n\tif reLoopback.MatchString(reg.Name()) {\n\t\treturn \"http\"\n\t}\n\treturn \"https\"\n}", "func WithEndpoint(endpoint string) ClientOption {\n\treturn func(client *Client) {\n\t\tclient.endpoint = strings.TrimRight(endpoint, \"/\")\n\t}\n}", "func (uri *URI) ChangeHost(hostWithPort string) {\n\tif uri.hostInfo.hostWithPort == hostWithPort {\n\t\treturn\n\t}\n\tvar newRawURI []byte\n\tif len(uri.host) == 0 {\n\t\t// not host in URI before, add it\n\t\tnewRawURI = []byte(hostWithPort)\n\t\tif len(uri.full) == 0 || (len(uri.full) > 0 && uri.full[0] != '/') {\n\t\t\tnewRawURI = append(newRawURI, '/')\n\t\t}\n\t\tnewRawURI = append(newRawURI, uri.full...)\n\t} else if hostIndex := bytes.Index(uri.full, uri.host); hostIndex >= 0 {\n\t\tif len(hostWithPort) == 0 {\n\t\t\tnewRawURI = uri.full[hostIndex+len(uri.host):]\n\t\t} else {\n\t\t\t// host already in URI, replace it\n\t\t\tnewRawURI = bytes.Replace(uri.full, uri.host, []byte(hostWithPort), 1)\n\t\t}\n\t}\n\tif len(newRawURI) == 0 {\n\t\tnewRawURI = []byte(\"/\")\n\t}\n\turi.Parse(uri.isConnect, newRawURI)\n}", "func cleanup(host string) string {\n\tif index := strings.Index(host, \":\"); index > 0 {\n\t\thost = host[:index]\n\t}\n\n\thost = strings.ReplaceAll(host, \"[\", \"\")\n\thost = strings.ReplaceAll(host, \"]\", \"\")\n\n\treturn host\n}", "func RegisterShadowsHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {\n\tconn, err := grpc.Dial(endpoint, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif cerr := conn.Close(); cerr != nil {\n\t\t\t\tgrpclog.Infof(\"Failed to close conn to %s: %v\", endpoint, cerr)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tgo func() {\n\t\t\t<-ctx.Done()\n\t\t\tif cerr := conn.Close(); cerr != nil {\n\t\t\t\tgrpclog.Infof(\"Failed to close conn to %s: %v\", endpoint, cerr)\n\t\t\t}\n\t\t}()\n\t}()\n\n\treturn RegisterShadowsHandler(ctx, mux, conn)\n}" ]
[ "0.6320563", "0.62610084", "0.61440116", "0.56868225", "0.5683344", "0.560318", "0.554496", "0.5536776", "0.55366045", "0.55199313", "0.55152476", "0.550689", "0.55057013", "0.5503566", "0.5499093", "0.5494576", "0.54539376", "0.5447968", "0.5438922", "0.5434849", "0.5428037", "0.54116726", "0.54025066", "0.53952205", "0.53775024", "0.5358555", "0.5356396", "0.5332896", "0.5324998", "0.5309243", "0.5232468", "0.5230766", "0.52287257", "0.5220128", "0.52079326", "0.5200744", "0.5199924", "0.5181663", "0.5176915", "0.5170092", "0.5165232", "0.51624614", "0.51554316", "0.51516694", "0.5144885", "0.513786", "0.51346874", "0.51329166", "0.51285625", "0.5124449", "0.5122321", "0.5114743", "0.51112175", "0.5108366", "0.5097525", "0.5095064", "0.5080435", "0.5076542", "0.5069716", "0.5061518", "0.50555074", "0.50371605", "0.50369465", "0.5034156", "0.5033172", "0.5032638", "0.5020711", "0.5018516", "0.5014009", "0.5010466", "0.50031793", "0.49883085", "0.49871206", "0.4983709", "0.49829364", "0.49796027", "0.49776193", "0.4956179", "0.49537855", "0.49393937", "0.49332482", "0.4932491", "0.49252388", "0.49216297", "0.49201277", "0.4907412", "0.49057564", "0.49054983", "0.48992482", "0.48936266", "0.48749697", "0.48652172", "0.48607793", "0.48557103", "0.48518598", "0.4848847", "0.4845882", "0.48431075", "0.48363426", "0.4834884" ]
0.7643794
0
hash returns a lowercase hash that uniquely identifies the bucket name & endpoint.
func (bc BucketConfig) hash() string { source := strings.ToLower(bc.Name + "/" + bc.Endpoint) hash := sha1.Sum([]byte(source)) return strings.ToLower(hex.EncodeToString(hash[0:6])) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *Bucket) Hash() string {\n\treturn b.descriptor.Hash()\n}", "func (authSvc *AuthService) computeHash(s string) hash.Hash {\n\t\n\tvar hash hash.Hash = sha256.New()\n\tvar bytes []byte = []byte(s)\n\thash.Write(authSvc.secretSalt)\n\thash.Write(bytes)\n\treturn hash\n}", "func (obj *bucket) Hash() hash.Hash {\n\treturn obj.immutable.Hash()\n}", "func HashBucket(str string) int {\n\treturn int(str[0])\n}", "func hash(path string) string {\n\th, err := files.Sha256(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\treturn h[:10]\n}", "func hash(path string) string {\n\th, err := files.Sha256(path)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn h[:10]\n}", "func (id *Public) hash() []byte {\n\treturn hashHelper(id.SigningKey.SerializeUncompressed(),\n\t\tid.EncryptionKey.SerializeUncompressed())\n}", "func hash(s string) string {\n\th := fnv.New32a()\n\t_, err := h.Write([]byte(s))\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprint(h.Sum32())\n}", "func hash(id, app string) string {\n\treturn id + \"|\" + app\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(s string) string {\n\th := sha256.New()\n\th.Write([]byte(s))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func hash(ba string) string {\n\th := sha256.New()\n\th.Write([]byte(ba))\n\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func (bc *Blockchain) Hash() {\n\n}", "func ComputeHashKey(propertyName string) string {\n\t\th := sha256.New()\n\t\th.Write([]byte(propertyName))\n\t\tnameInBytes := h.Sum([]byte(\"\"))\n\t\tnameInString := hex.EncodeToString(nameInBytes)\n\t\treturn nameInString[:62]\n\t}", "func calculateHash(block Block) string {\n\n\t// Time and vehicle identifier (v5c) are the key block items to generate the hash\n\trecord := string(string(block.Index) + block.Timestamp + block.Event.PerformedOnVehicle.V5c + block.PrevHash)\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func calculateHash(block Block) string {\n\trecord := strconv.Itoa(block.Index) + block.Timestamp + strconv.Itoa(block.Key) + block.PrevHash\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func Hashlist(url string, secure bool, accesskey string, secretkey string, bucket string) string {\n\tlog.SetFlags(log.Lshortfile)\n\n\t// New returns an Amazon S3 compatible client object. API compatibility (v2 or v4) is automatically\n\t// determined based on the Endpoint value.\n\ts3Client, err := minio.New(url, accesskey, secretkey, secure)\n\tif err != nil {\n\t\tjc.SendString(fmt.Sprint(err))\n\t\treturn \"ERROR\"\n\t}\n\t// Create a done channel to control 'ListObjects' go routine.\n\tdoneCh := make(chan struct{})\n\n\t// Indicate to our routine to exit cleanly upon return.\n\tdefer close(doneCh)\n\n\t// List all objects from a bucket-name with a matching prefix.\n\tvar snapshots []string\n\tfor object := range s3Client.ListObjects(bucket, \"\", secure, doneCh) {\n\t\tif object.Err != nil {\n\t\t\tjc.SendString(fmt.Sprint(object.Err))\n\t\t\treturn \"ERROR\"\n\t\t}\n\t\tmatched, err := regexp.MatchString(\".hsh$\", object.Key)\n\t\tif err != nil {\n\t\t\treturn \"ERROR\"\n\t\t}\n\t\tif matched == true {\n\t\t\tsnapshots = append(snapshots, object.Key)\n\t\t\tsnapshots = append(snapshots, \"\\n\")\n\t\t}\n\t}\n\tif len(snapshots) > 0 {\n\t\treturn strings.Join(snapshots, \"\\n\")\n\t}\n\treturn \"ERROR\"\n}", "func hash(key, value string) int64 {\n\thash := siphash.New(sipConst)\n\thash.Write([]byte(key + \":::\" + value))\n\treturn int64(hash.Sum64())\n}", "func (c ConnInfo) Hash() string {\n\treturn fmt.Sprintf(\"%v_%s\", c.Type, c.String())\n}", "func (_this *URL) Hash() string {\n\tvar ret string\n\tvalue := _this.Value_JS.Get(\"hash\")\n\tret = (value).String()\n\treturn ret\n}", "func (r *RequestDelete) Hash() string {\n\treturn r.Key\n}", "func hash(fn string) (res string) {\n\th := sha256.New()\n\n\tfi, err := os.Stat(fn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tf, err := os.Open(fn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer f.Close()\n\n\tif fi.IsDir() {\n\t\tns, err := f.Readdirnames(0)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, e := range ns {\n\t\t\th.Write([]byte(e))\n\t\t}\n\t} else {\n\t\tif _, err := io.Copy(h, f); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn string(h.Sum(nil))\n}", "func (c cacheObjects) hashIndex(bucket, object string) int {\n\treturn crcHashMod(pathJoin(bucket, object), len(c.cache))\n}", "func (r *RequestKeys) Hash() string {\n\treturn \"\"\n}", "func getHash() hash.Hash {\n\tswitch hashFunc {\n\tcase \"md5\":\n\t\treturn md5.New()\n\tcase \"sha1\":\n\t\treturn sha1.New()\n\tcase \"sha384\":\n\t\treturn sha512.New384()\n\tcase \"sha512\":\n\t\treturn sha512.New()\n\tdefault:\n\t\treturn sha256.New()\n\t}\n}", "func secretHash(sec *v1.Secret) (string, error) {\n\tencoded, err := encodeSecret(sec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\th, err := hasher.Encode(hasher.Hash(encoded))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn h, nil\n}", "func Hash(src string, secret string) string {\n key := []byte(secret)\n h := hmac.New(sha256.New, key)\n h.Write([]byte(src))\n return base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func (c *Client) generateHash(method, path, timestamp string) string {\n\tdata := fmt.Sprintf(\"%v+%v%v?apiuserid=%v&timestamp=%v\", method, c.BaseURL.Host, path, c.APIUserID, timestamp)\n\tmac := hmac.New(sha256.New, []byte(c.APIUserKey))\n\tmac.Write([]byte(data))\n\n\treturn hex.EncodeToString(mac.Sum(nil))\n}", "func hashSHA256(input string) string {\n\th := sha1.New()\n\th.Write([]byte(input))\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func (b BlockChain) Hash() {\n\n}", "func Hashit(tox string) string {\n h:= sha256.New()\n h.Write([]byte(tox))\n bs := h.Sum([]byte{})\n str := base64.StdEncoding.EncodeToString(bs)\n return str\n}", "func hash(s string) uint32 {\n h := fnv.New32a()\n h.Write([]byte(s))\n return h.Sum32()\n}", "func hash(value string) uint32 {\n\th := fnv.New32a()\n\th.Write([]byte(value))\n\n\treturn h.Sum32()\n}", "func (o *ObjectIndex) Hash() uint32 {\n\tvar h uint32 = 17\n\n\tvar str string\n\tstr += fmt.Sprintf(\"%08x\", o.machine)\n\tstr += fmt.Sprintf(\"%04x\", o.pid)\n\tstr += fmt.Sprintf(\"%08x\", o.id)\n\tstr += fmt.Sprintf(\"%08x\", o.Rand)\n\tfor _, v := range str {\n\t\th += h*23 + uint32(v)\n\t}\n\treturn h\n}", "func hash(key string) int{\n\tvar num = 0\n\t// get the lenght of the key\n\tvar length = len(key)\n\n\t// add the ascii character value to creat a sum \n\tfor i := 0; i < length; i++{\n\n\t\tnum += int(key[i])\n\t}\n\t\n\t// square in the middle hash method\n\tvar avg = num * int((math.Pow(5.0, 0.5) - 1)) / 2\n\tvar numeric = avg - int(math.Floor(float64(avg)))\n\n\n\t// hash value to place into the table slice between -1 and CAPACITY - 1\n\treturn int(math.Floor(float64(numeric * CAPACITY)))\n}", "func (r *RequestListIndex) Hash() string {\n\treturn r.Key\n}", "func hash(s string) string {\n\thash := fnv.New32a()\n\thash.Write([]byte(s))\n\tintHash := hash.Sum32()\n\tresult := fmt.Sprintf(\"%08x\", intHash)\n\treturn result\n}", "func (r *RequestStore) Hash() string {\n\treturn r.Key\n}", "func hashSHA256(str string) string {\n\ts := sha256.New()\n\ts.Write([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(s.Sum(nil))\n}", "func calculateHash(index int, previousHash string, timestamp int64, data transaction.Transaction) string {\n\tvar foo = strconv.Itoa(index) + string(previousHash) + strconv.Itoa(int(timestamp)) + hex.EncodeToString(data.Id)\n\tinput :=strings.NewReader(foo)\n\tvar newHash = sha256.New()\n\tif _, err := io.Copy(newHash, input); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn hex.EncodeToString(newHash.Sum(nil))\n}", "func calculateHash (block Block) string{\n h := sha256.New()\n unique := block.Data + block.PrevHash + block.TimeStamp + strconv.Itoa(block.Nonce)\n h.Write([]byte(unique))\n \n return hex.EncodeToString(h.Sum(nil))\n}", "func (this *Ring) Hash(key string) uint32 {\n\treturn crc32.ChecksumIEEE([]byte(key))\n}", "func hashUrl(raw string) string {\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tvar queries []string\n\tfor k := range u.Query() {\n\t\tqueries = append(queries, k)\n\t}\n\tsort.Strings(queries)\n\tquery := strings.Join(queries, \"-\")\n\tdata := fmt.Sprintf(\"%v-%v-%v\", u.Hostname(), u.Path, query)\n\treturn genHash(data)\n}", "func computeHash(name string) string {\n\tdata := []byte(name)\n\thash := sha256.New()\n\tif _, err := hash.Write(data); err != nil {\n\t\t// Impossible case\n\t\tlog.Errorf(\"Fail to create Span name hash for %s: %v\", name, err)\n\t}\n\n\treturn fmt.Sprintf(\"%x\", hash.Sum(nil))[:TraceNameHashLength]\n}", "func hashme(s interface{}) string {\n\tbytes, _ := json.Marshal(s)\n\th := sha256.New()\n\th.Write(bytes)\n\treturn hex.EncodeToString(h.Sum(nil))\n}", "func GetHash(b string) (hash string) {\n\t// Hash input b and capture/format its output as a string literal\n\thash = fmt.Sprintf(\"%X\", sha256.Sum256([]byte(b)[:]))\n\treturn\n}", "func (r *RequestLoad) Hash() string {\n\treturn r.Key\n}", "func hash(s string) string {\n\treturn fmt.Sprintf(\"%x\", md5.Sum([]byte(s)))\n}", "func (ds *Datasource) GetHash(log *logrus.Entry, admin bool, nodb bool) string {\n\tvar toHash string\n\n\tif ds.dstype == File {\n\t\ttoHash = ds.file.FilePath\n\t} else {\n\t\tswitch {\n\t\tcase nodb:\n\t\t\ttoHash = ds.urlNoDb\n\t\tcase admin:\n\t\t\ttoHash = ds.urlAdmin\n\t\tdefault:\n\t\t\ttoHash = ds.url\n\t\t}\n\t}\n\n\thashed := fmt.Sprintf(\"%x\", sha256.Sum256([]byte(toHash)))\n\n\t//log.Debugf(\"Hashing: %s => %s\", toHash, hashed)\n\n\treturn hashed\n}", "func strhash(p *string, h uintptr) uintptr", "func hashPayload(payload []byte) string {\n\thasher := hmac.New(sha256.New, []byte(GetConfig().AccessKey))\n\thasher.Write(payload)\n\thash := hasher.Sum(nil)\n\treturn hex.EncodeToString(hash)\n}", "func (d Descriptor) Hash() string {\n\treturn fmt.Sprintf(\"%s%s\", d.Name, d.Type)\n}", "func Hash(obj interface{}) (string, error) {\n\tb, err := GetBytes(obj)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thasher := sha256.New()\n\thasher.Write(b)\n\n\treturn base64.URLEncoding.EncodeToString(hasher.Sum(nil)), nil\n}", "func (r *Route) Hash() uint64 {\n\th := fnv.New64()\n\th.Reset()\n\th.Write([]byte(r.Service + r.Address + r.Gateway + r.Network + r.Router + r.Link))\n\treturn h.Sum64()\n}", "func computeHash(nstObj megav1.NamespaceTemplate) uint64 {\n\thash, err := hashstructure.Hash(nstObj, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"computeHash: %d\\n\", hash)\n\treturn hash\n}", "func calcHash(data string) string {\n\th := sha256.New()\n\th.Write([]byte(data))\n\thash := fmt.Sprintf(\"%x\", h.Sum(nil))\n\treturn hash\n}", "func hashString(input string) string {\n\tdefer loggerHighwayHasher.Reset()\n\tloggerHighwayHasher.Write([]byte(input))\n\tchecksum := loggerHighwayHasher.Sum(nil)\n\treturn hex.EncodeToString(checksum)\n}", "func strhash(a unsafe.Pointer, h uintptr) uintptr", "func getHash(s string) uint32 {\n\ttbl := crc32.MakeTable(crc32.IEEE)\n\treturn crc32.Checksum([]byte(s), tbl)\n}", "func computeHash(w http.ResponseWriter, req *http.Request) {\n\tvalues := req.URL.Query()\n\tdata := values.Get(\"data\")\n\tif data == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - data param not present\"))\n\t\treturn\n\t}\n\tsalt := values.Get(\"salt\")\n\tif salt == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - salt param not present\"))\n\t\treturn\n\t}\n\th := sha256.Sum256([]byte(data+salt))\n\tencodedStr := hex.EncodeToString(h[:])\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(encodedStr))\n}", "func (t *openAddressing) hash(key string, round int) uint32 {\n\tnum := uint(stringToInt(key))\n\tmax := uint(len(t.values) - 1)\n\treturn uint32((hashDivision(num, max) + uint(round)*hashDivision2(num, max)) % max)\n}", "func (o *Object) Hash() string {\n\treturn Hash(o, true, false, true)\n}", "func hash(f []byte) (string, error) {\n\tsha := sha256.New()\n\t_, err := sha.Write(f)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn fmt.Sprintf(\"%x\", sha.Sum(nil)), nil\n}", "func hordeHashKey(hordeName string) string {\n\treturn \"hordeHash:\" + hordeName\n}", "func Hash(length int, key string) int64 {\n\tif key == \"\" {\n\t\treturn 0\n\t}\n\thc := hashCode(key)\n\treturn (hc ^ (hc >> 16)) % int64(length)\n}", "func (e Aes128CtsHmacSha256128) GetHashFunc() func() hash.Hash {\n\treturn sha256.New\n}", "func (h *Header) Hash() [32]byte {\n\tvar f []string\n\tif h.Description.Value != \"\" {\n\t\tf = append(f, h.Description.Value)\n\t}\n\tf = append(f, fmt.Sprint(h.Required.Value))\n\tf = append(f, fmt.Sprint(h.Deprecated.Value))\n\tf = append(f, fmt.Sprint(h.AllowEmptyValue.Value))\n\tif h.Style.Value != \"\" {\n\t\tf = append(f, h.Style.Value)\n\t}\n\tf = append(f, fmt.Sprint(h.Explode.Value))\n\tf = append(f, fmt.Sprint(h.AllowReserved.Value))\n\tif h.Schema.Value != nil {\n\t\tf = append(f, low.GenerateHashString(h.Schema.Value))\n\t}\n\tif h.Example.Value != nil {\n\t\tf = append(f, fmt.Sprint(h.Example.Value))\n\t}\n\tif len(h.Examples.Value) > 0 {\n\t\tfor k := range h.Examples.Value {\n\t\t\tf = append(f, fmt.Sprintf(\"%s-%x\", k.Value, h.Examples.Value[k].Value.Hash()))\n\t\t}\n\t}\n\tif len(h.Content.Value) > 0 {\n\t\tfor k := range h.Content.Value {\n\t\t\tf = append(f, fmt.Sprintf(\"%s-%x\", k.Value, h.Content.Value[k].Value.Hash()))\n\t\t}\n\t}\n\tkeys := make([]string, len(h.Extensions))\n\tz := 0\n\tfor k := range h.Extensions {\n\t\tkeys[z] = fmt.Sprintf(\"%s-%x\", k.Value, sha256.Sum256([]byte(fmt.Sprint(h.Extensions[k].Value))))\n\t\tz++\n\t}\n\tsort.Strings(keys)\n\tf = append(f, keys...)\n\treturn sha256.Sum256([]byte(strings.Join(f, \"|\")))\n}", "func hash(s string) int {\n\th := fnv.New32a()\n\tif _, err := h.Write([]byte(s)); err != nil {\n\t\tpanic(err) // should never happen\n\t}\n\n\treturn int(h.Sum32() & 0x7FFFFFFF) // mask MSB of uint32 as this will be sign bit\n}", "func getHash(scheme SignatureScheme) crypto.Hash {\n\tswitch scheme {\n\tcase ECDSAWithP256AndSHA256:\n\t\treturn crypto.SHA256\n\tcase ECDSAWithP384AndSHA384:\n\t\treturn crypto.SHA384\n\tcase ECDSAWithP521AndSHA512:\n\t\treturn crypto.SHA512\n\tcase Ed25519:\n\t\treturn directSigning\n\tcase PKCS1WithSHA256, PSSWithSHA256:\n\t\treturn crypto.SHA256\n\tcase PSSWithSHA384:\n\t\treturn crypto.SHA384\n\tcase PSSWithSHA512:\n\t\treturn crypto.SHA512\n\tdefault:\n\t\treturn 0 //Unknown hash function\n\t}\n}", "func (a *Authorization) HashFunc() func() hash.Hash {\n\treturn a.H\n}", "func CalcHash(data string) string {\r\n\thashed := sha256.Sum256([]byte(data))\r\n\treturn hex.EncodeToString(hashed[:])\r\n}", "func hash(obj interface{}) KHash {\n\tvar buffer bytes.Buffer\n\tencoder := json.NewEncoder(&buffer)\n\terr := encoder.Encode(obj)\n\tif err != nil {\n\t\tpanic(\"cannot encode object\")\n\t}\n\n\tdata := buffer.Bytes()\n\th := sha256.Sum256(data)\n\n\t// log.Printf(\"hashing %#v represented as %s with hash %X\", obj, data, h)\n\treturn h\n}", "func (s sha256hashing) HashString(hashme string, digest []byte) error {\n\thashAlgo := sha256.New()\n\thashAlgo.Write([]byte(hashme))\n\n\tcopySHA256(digest, hashAlgo.Sum(nil))\n\n\treturn nil\n}", "func newSHA256() hash.Hash { return sha256.New() }", "func Hash(input []byte) string {\n\treturn fmt.Sprintf(\"%x\", sha256.Sum256(input))\n}", "func (cb *cachedBatch) hash(namespace string, key []byte) hash.CacheHash {\n\tstream := hash.Hash160b([]byte(namespace))\n\tstream = append(stream, key...)\n\treturn byteutil.BytesToCacheHash(hash.Hash160b(stream))\n}", "func getSHA256Hash(data []byte) string {\n\treturn hex.EncodeToString(getSHA256Sum(data))\n}", "func (hasher *SHA256) HashKey() string {\n\treturn \"\"\n}", "func (pssOpts *PSSOptions) HashFunc() crypto.Hash", "func hashKey(b []byte) string {\n\th := sha1.New() // #nosec G401 Used only to generate random value to be used to generate hash string\n\t_, err := h.Write(b)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to hash key with error:\", err)\n\t}\n\n\treturn string(h.Sum(nil))\n}", "func (n Node) CalSHA256Hash(input []byte) []byte {\r\n\th := sha256.New()\r\n\th.Write(input)\r\n\treturn h.Sum(nil)\r\n}", "func (spec Spec) DeepHash() string {\n\thash := sha512.New512_224()\n\tspec.DefaultService.hash(hash)\n\tfor _, rule := range spec.Rules {\n\t\trule.hash(hash)\n\t}\n\tsvcs := make([]string, len(spec.AllServices))\n\ti := 0\n\tfor k := range spec.AllServices {\n\t\tsvcs[i] = k\n\t\ti++\n\t}\n\tsort.Strings(svcs)\n\tfor _, svc := range svcs {\n\t\thash.Write([]byte(svc))\n\t\tspec.AllServices[svc].hash(hash)\n\t}\n\tspec.ShardCluster.hash(hash)\n\thash.Write([]byte(spec.VCL))\n\tfor _, auth := range spec.Auths {\n\t\tauth.hash(hash)\n\t}\n\tfor _, acl := range spec.ACLs {\n\t\tacl.hash(hash)\n\t}\n\tfor _, rw := range spec.Rewrites {\n\t\trw.hash(hash)\n\t}\n\tfor _, reqDisp := range spec.Dispositions {\n\t\treqDisp.hash(hash)\n\t}\n\th := new(big.Int)\n\th.SetBytes(hash.Sum(nil))\n\treturn h.Text(62)\n}", "func TestHash(t *testing.T) {\n\tdata := \"bce-auth-v1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/2015-04-27T08:23:49Z/1800\"\n\tkey := \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n\tresult := \"1d5ce5f464064cbee060330d973218821825ac6952368a482a592e6615aef479\"\n\ttestResult := hash(data, key)\n\tif result == testResult {\n\t\tt.Log(\"hash test success\")\n\t} else {\n\t\tt.Error(\"hash test fail\")\n\t}\n}", "func hashString(str string) string {\n\thash := sha256.Sum256([]byte(str))\n\treturn base64.StdEncoding.EncodeToString(hash[:])\n}", "func (l Location) Hash() string {\n\treturn l.val.Get(\"hash\").String()\n}", "func (r *Subresource) Hash() int {\n\thf := schema.HashResource(&schema.Resource{Schema: r.schema})\n\treturn hf(r.data)\n}", "func hash(data []byte) [32]byte {\n\tvar hash [32]byte\n\n\th := sha256.New()\n\t// The hash interface never returns an error, for that reason\n\t// we are not handling the error below. For reference, it is\n\t// stated here https://golang.org/pkg/hash/#Hash\n\t// #nosec G104\n\th.Write(data)\n\th.Sum(hash[:0])\n\n\treturn hash\n}", "func (c CloudWatchAlarmList) Hash() string {\n\tif len(c) == 0 {\n\t\treturn \"\"\n\t}\n\n\tbuf, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to marshal cloudwatch alarm list: %v\", err)\n\t\treturn \"\"\n\t}\n\n\thash := sha256.New()\n\thash.Write(buf)\n\n\treturn hex.EncodeToString(hash.Sum(nil))\n}", "func ComputeHash(body []byte) string {\n\th := md5.New()\n\th.Write(body)\n\th.Write(kSecret)\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func CalculateHash(obj interface{}) (string, error) {\n\tconfigStr, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tconfigSum := md5.Sum(configStr)\n\treturn fmt.Sprintf(\"%x\", configSum), nil\n}", "func strhash0(p unsafe.Pointer, h uintptr) uintptr", "func generateHash(src, secret string) string {\n\tkey := []byte(secret)\n\th := hmac.New(sha256.New, key)\n\th.Write([]byte(src))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}", "func (source *Source) Hash() int {\n\tvar hash int\n\n\tif len(source.Prefix) > 0 {\n\t\tfor _, b := range source.Prefix {\n\t\t\thash = int(b*31) + hash\n\t\t}\n\t}\n\n\thash = int(source.PrefixLen*31) + hash\n\thash = int(source.RouterId*31) + hash\n\n\treturn hash\n}", "func Hash(s string) string {\n\tfmt.Println(\"Hashing string:\", s)\n\thash := sha256.Sum256([]byte(s))\n\tniceHash := fmt.Sprintf(\"%x\", hash)\n\tfmt.Println(\"Created hash:\", hash)\n\treturn niceHash\n}", "func (a *Alert) Hash() [16]byte {\n\tb := getBuf()\n\tdefer putBuf(b)\n\n\tfor _, k := range a.names() {\n\t\tb = append(b, k...)\n\t\tb = append(b, a.Labels[k]...)\n\t}\n\n\treturn md5.Sum(b)\n}", "func Hasher(value string) string {\n\th := fnv.New32a()\n\t_, _ = h.Write([]byte(value))\n\treturn fmt.Sprintf(\"%v\", h.Sum32())\n}", "func hashSignature(alg Algorithm, signatureValue string, secret *pbauth.Secret) (string, error) {\n\tif strings.TrimSpace(signatureValue) == \"\" {\n\t\treturn \"\", consts.ErrInvalidSignatureValue\n\t}\n\tif err := ValidateSecret(secret); err != nil {\n\t\treturn \"\", err\n\t}\n\tkey := []byte(secret.Key)\n\tvar h hash.Hash\n\tswitch alg {\n\tcase Hs256:\n\t\th = hmac.New(sha256.New, key)\n\tcase Hs512:\n\t\th = hmac.New(sha512.New, key)\n\tdefault:\n\t\treturn \"\", consts.ErrNoHashAlgorithm\n\t}\n\th.Write([]byte(signatureValue))\n\treturn base64.URLEncoding.EncodeToString(h.Sum(nil)), nil\n}", "func CalculateHash(args []string) string {\n\tvar str = \"\"\n\tfor _,v := range args {\n\t\tstr += v\n\t}\n\thasher := sha256.New()\n\thasher.Write([]byte(str))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}", "func (sc StringCircle) GetHash() int {\n\treturn sc.list[0] * sc.list[1]\n}" ]
[ "0.69260216", "0.6708413", "0.649422", "0.6427349", "0.63813674", "0.6372707", "0.63630694", "0.6348366", "0.6326957", "0.6312707", "0.6312707", "0.6312707", "0.63097775", "0.62950593", "0.6239183", "0.6225217", "0.6214106", "0.6207067", "0.6190727", "0.61862934", "0.6180711", "0.6174648", "0.61722136", "0.6159501", "0.61564416", "0.61495835", "0.6148882", "0.61401606", "0.6135816", "0.61304945", "0.6126642", "0.6122751", "0.6115413", "0.6109811", "0.61093044", "0.6107933", "0.60943127", "0.6091968", "0.6089909", "0.6085762", "0.6080626", "0.6073912", "0.60731995", "0.607177", "0.60697806", "0.60547966", "0.60428065", "0.6041509", "0.6032498", "0.6017052", "0.601327", "0.6008198", "0.6003769", "0.59947044", "0.59920603", "0.59900707", "0.59860796", "0.5984107", "0.59779066", "0.597241", "0.5962078", "0.59542054", "0.5942463", "0.5934077", "0.59324116", "0.5913098", "0.5912819", "0.58969307", "0.58957916", "0.5895232", "0.5888497", "0.58813846", "0.5877296", "0.5872013", "0.5864709", "0.5864345", "0.5860013", "0.58500713", "0.5846471", "0.5838296", "0.58360887", "0.58353084", "0.58342755", "0.58268785", "0.5826191", "0.5823238", "0.5821366", "0.5803312", "0.57983243", "0.57917", "0.57898116", "0.578597", "0.5775071", "0.57721305", "0.57711506", "0.57694554", "0.57664496", "0.57661927", "0.57615274", "0.575909" ]
0.8359008
0